update dasboard ,noti
This commit is contained in:
48
public/css/announcements.css
Normal file
48
public/css/announcements.css
Normal file
@@ -0,0 +1,48 @@
|
||||
.announcement-dialog {
|
||||
width: min(560px, calc(100vw - 32px));
|
||||
max-height: calc(100dvh - 40px);
|
||||
margin: auto;
|
||||
padding: 0;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 16px;
|
||||
background: white;
|
||||
color: #243248;
|
||||
box-shadow: 0 24px 80px #0f172a40;
|
||||
}
|
||||
.announcement-dialog::backdrop { background: rgb(15 23 42 / 55%); backdrop-filter: blur(3px); }
|
||||
.announcement-heading { display: flex; align-items: flex-start; gap: 14px; padding: 24px 24px 20px; border-bottom: 1px solid #edf1f7; }
|
||||
.announcement-symbol { display: flex; align-items: center; justify-content: center; flex-shrink: 0; width: 44px; height: 44px; border-radius: 12px; background: #edf1ff; color: #3755c3; font-size: 25px; }
|
||||
.announcement-heading > div { flex: 1; min-width: 0; }
|
||||
.announcement-heading p { margin: 2px 0 6px; color: #64748b; font-size: 10px; font-weight: 700; letter-spacing: 0.09em; }
|
||||
.announcement-heading h2 { font-size: 19px; font-weight: 800; line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.announcement-heading button { display: flex; padding: 5px; border-radius: 7px; color: #64748b; }
|
||||
.announcement-heading button:hover { background: #f1f5f9; }
|
||||
.announcement-body { padding: 20px 24px 24px; }
|
||||
.announcement-author { margin-bottom: 16px; color: #64748b; font-size: 11px; line-height: 1.8; }
|
||||
#announcementMessage { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 14px; line-height: 1.85; }
|
||||
.announcement-error { margin-top: 16px; border-radius: 8px; padding: 10px 12px; background: #fff1f2; color: #be123c; font-size: 12px; line-height: 1.6; }
|
||||
.announcement-footer { padding: 18px 24px 22px; border-top: 1px solid #edf1f7; background: #f8fafc; }
|
||||
.announcement-footer label { display: flex; align-items: center; gap: 9px; width: fit-content; min-height: 32px; font-size: 13px; font-weight: 600; cursor: pointer; }
|
||||
.announcement-footer input { width: 16px; height: 16px; border: 1px solid #94a3b8; border-radius: 4px; color: #3755c3; }
|
||||
.announcement-footer > p { margin: 3px 0 18px; color: #64748b; font-size: 11px; line-height: 1.6; }
|
||||
.announcement-footer > div { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 10px; }
|
||||
.announcement-footer button { min-height: 42px; padding: 10px 18px; border: 1px solid #dbe2ef; border-radius: 8px; font-size: 12px; font-weight: 700; }
|
||||
.announcement-footer .announcement-primary { border-color: #3755c3; background: #3755c3; color: white; }
|
||||
.announcement-footer .announcement-secondary { background: white; color: #3755c3; }
|
||||
.announcement-dialog button:disabled { opacity: 0.6; cursor: wait; }
|
||||
.announcement-dialog :is(button, input):focus-visible { outline: 2px solid #3755c3; outline-offset: 3px; }
|
||||
.announcement-management-note { margin-top: 20px; border: 1px solid #dce4f6; border-radius: 10px; padding: 14px 16px; background: #f0f4ff; color: #435577; font-size: 12px; line-height: 1.8; }
|
||||
.announcement-post-status { margin-top: 8px; color: #64748b; font-size: 11px; font-weight: 600; }
|
||||
.notification-withdraw-dialog .bom-confirm-icon { color: #dc2626; background: #fef2f2; }
|
||||
.notification-withdraw-dialog .bom-dialog-footer { justify-content: flex-end; }
|
||||
.notification-withdraw-summary { margin-bottom: 18px; padding: 16px; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc; overflow-wrap: anywhere; }
|
||||
.notification-withdraw-summary strong { font-size: 14px; font-weight: 700; }
|
||||
.notification-withdraw-summary p { margin-top: 6px; color: #64748b; font-size: 11px; line-height: 1.6; }
|
||||
#notificationComposerModal > div { max-height: calc(100dvh - 32px); overflow-y: auto; }
|
||||
@media (max-width: 480px) {
|
||||
.announcement-heading { padding: 18px 16px 16px; gap: 10px; }
|
||||
.announcement-heading h2 { font-size: 17px; }
|
||||
.announcement-body, .announcement-footer { padding: 16px; }
|
||||
.announcement-symbol { width: 36px; height: 36px; font-size: 22px; }
|
||||
}
|
||||
139
public/css/dashboard.css
Normal file
139
public/css/dashboard.css
Normal file
@@ -0,0 +1,139 @@
|
||||
/* Overview of the existing management modules; all stock totals count catalog codes. */
|
||||
.dashboard-page {
|
||||
color: #263449;
|
||||
background: #f7f9fc;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
.dashboard-shell {
|
||||
max-width: 1680px;
|
||||
margin: 0 auto;
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
|
||||
.dashboard-shell .dashboard-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.dashboard-eyebrow { margin-bottom: 7px; font-size: 10px; font-weight: 800; letter-spacing: 0.12em; color: #62708a; }
|
||||
.dashboard-header h1 { font-size: 25px; line-height: 1.3; font-weight: 800; letter-spacing: -0.035em; }
|
||||
.dashboard-header p { margin-top: 6px; font-size: 12px; line-height: 1.6; color: #64748b; }
|
||||
.dashboard-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
|
||||
.dashboard-updated { font-size: 11px; color: #64748b; }
|
||||
.dashboard-refresh { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 9px 13px; border: 1px solid #dce3ee; border-radius: 8px; background: white; font-size: 12px; font-weight: 700; box-shadow: 0 1px 2px #172a4610; }
|
||||
.dashboard-refresh:hover { background: #eef2ff; border-color: #b9c7f4; }
|
||||
.dashboard-refresh:disabled { opacity: 0.6; cursor: wait; }
|
||||
.dashboard-refresh .material-symbols-outlined { font-size: 18px; }
|
||||
.dashboard-warning { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 18px; border: 1px solid #f4d59c; border-radius: 10px; padding: 12px 16px; background: #fffbeb; color: #92400e; font-size: 12px; line-height: 1.6; }
|
||||
.dashboard-metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 20px; }
|
||||
.dashboard-metric { display: block; min-width: 0; padding: 19px 20px 16px; background: white; border: 1px solid #e3e9f1; border-radius: 12px; box-shadow: 0 2px 4px #172a4603; transition: border-color 0.15s, box-shadow 0.15s; }
|
||||
.dashboard-metric:hover { border-color: #b8c6e8; box-shadow: 0 4px 14px #263f7110; }
|
||||
.dashboard-metric-top { display: flex; align-items: center; gap: 10px; font-size: 12px; font-weight: 700; color: #536176; }
|
||||
.dashboard-metric-top > .material-symbols-outlined { margin-left: auto; font-size: 16px; color: #94a3b8; }
|
||||
.dashboard-icon { width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; border-radius: 10px; color: var(--dashboard-accent, #3755c3); background: var(--dashboard-soft, #edf1ff); }
|
||||
.dashboard-icon .material-symbols-outlined { font-size: 20px; }
|
||||
.dashboard-tone-blue { --dashboard-accent: #3755c3; --dashboard-soft: #edf1ff; }
|
||||
.dashboard-tone-green { --dashboard-accent: #087f69; --dashboard-soft: #e8f7f0; }
|
||||
.dashboard-tone-purple { --dashboard-accent: #7c51c5; --dashboard-soft: #f2edfb; }
|
||||
.dashboard-tone-amber { --dashboard-accent: #a66313; --dashboard-soft: #fff5e2; }
|
||||
.dashboard-tone-rose { --dashboard-accent: #be4658; --dashboard-soft: #fff0f2; }
|
||||
.dashboard-metric-value { display: flex; align-items: baseline; flex-wrap: wrap; column-gap: 8px; margin-top: 16px; font-size: 32px; font-weight: 800; line-height: 1.2; letter-spacing: -0.04em; }
|
||||
.dashboard-metric-value > span { color: #718096; font-size: 11px; font-weight: 500; letter-spacing: 0; }
|
||||
.dashboard-metric > p { margin-top: 10px; padding-top: 12px; border-top: 1px solid #f0f3f8; color: #64748b; font-size: 11px; line-height: 1.6; }
|
||||
.dashboard-layout { display: grid; grid-template-columns: minmax(0, 1.85fr) minmax(300px, 1fr); align-items: start; gap: 20px; }
|
||||
.dashboard-main-column, .dashboard-side-column { display: grid; min-width: 0; gap: 20px; }
|
||||
.dashboard-stock-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; }
|
||||
.dashboard-panel { min-width: 0; padding: 20px; background: white; border: 1px solid #e3e9f1; border-radius: 12px; }
|
||||
.dashboard-panel-heading { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
|
||||
.dashboard-panel-heading h2 { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 800; }
|
||||
.dashboard-panel-heading h2 .material-symbols-outlined { font-size: 18px; color: #6a7eaa; }
|
||||
.dashboard-panel-heading > a { display: inline-flex; align-items: center; gap: 4px; color: #3755c3; font-size: 11px; font-weight: 700; }
|
||||
.dashboard-panel-heading > a .material-symbols-outlined { font-size: 15px; }
|
||||
.dashboard-panel-note { color: #7a8799; font-size: 10px; line-height: 1.6; }
|
||||
p.dashboard-panel-note { margin-top: 6px; }
|
||||
.dashboard-stock-row { margin-top: 20px; }
|
||||
.dashboard-stock-row > div:first-child { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 9px; font-size: 11px; }
|
||||
.dashboard-stock-row > div:first-child > span { display: inline-flex; align-items: center; gap: 7px; color: #5f6e82; }
|
||||
.dashboard-stock-row strong { font-size: 13px; white-space: nowrap; }
|
||||
.dashboard-stock-row small { font-size: 10px; font-weight: 400; color: #7a8799; }
|
||||
.dashboard-dot { display: inline-block; flex-shrink: 0; width: 7px; height: 7px; border-radius: 50%; }
|
||||
.dashboard-track { height: 6px; overflow: hidden; background: #f0f3f8; border-radius: 4px; }
|
||||
.dashboard-track > span { display: block; height: 100%; border-radius: inherit; }
|
||||
.dashboard-fill-blue { background: #5a79d5; }
|
||||
.dashboard-fill-purple { background: #a285d5; }
|
||||
.dashboard-fill-green { background: #43a78d; }
|
||||
.dashboard-fill-amber { background: #e4b05f; }
|
||||
.dashboard-fill-rose { background: #dd8190; }
|
||||
.dashboard-inline-link { display: flex; align-items: center; gap: 6px; margin-top: 19px; color: #3755c3; font-size: 11px; font-weight: 600; }
|
||||
.dashboard-inline-link .material-symbols-outlined { font-size: 17px; }
|
||||
.dashboard-inline-link > .material-symbols-outlined:last-child { margin-left: auto; }
|
||||
.dashboard-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; min-height: 140px; padding: 20px 8px; text-align: center; color: #7a8799; font-size: 12px; line-height: 1.7; }
|
||||
.dashboard-empty > .material-symbols-outlined { font-size: 28px; color: #c3cddd; }
|
||||
.dashboard-recent-list { margin-top: 12px; }
|
||||
.dashboard-recent-row { display: grid; grid-template-columns: 36px minmax(0, 1fr) auto auto 14px; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid #f0f3f8; }
|
||||
.dashboard-recent-row:last-child { border-bottom: 0; padding-bottom: 0; }
|
||||
.dashboard-recent-name { min-width: 0; }
|
||||
.dashboard-recent-name strong, .dashboard-robot-row strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; }
|
||||
.dashboard-recent-name small, .dashboard-robot-row small { display: block; margin-top: 4px; color: #7a8799; font-size: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dashboard-recent-row time { color: #7a8799; font-size: 10px; white-space: nowrap; }
|
||||
.dashboard-recent-row > .material-symbols-outlined, .dashboard-robot-row > .material-symbols-outlined { color: #a5b0c1; font-size: 16px; }
|
||||
.dashboard-tag { display: inline-flex; align-items: center; justify-content: center; padding: 4px 7px; border-radius: 5px; font-size: 10px; font-weight: 600; color: var(--dashboard-accent); background: var(--dashboard-soft); white-space: nowrap; }
|
||||
.dashboard-attention-row { display: flex; align-items: center; gap: 10px; width: 100%; margin-top: 14px; text-align: left; }
|
||||
.dashboard-attention-row > span:nth-child(2) { min-width: 0; flex: 1; }
|
||||
.dashboard-attention-row strong { display: block; font-size: 11px; font-weight: 600; line-height: 1.5; }
|
||||
.dashboard-attention-row small { display: block; margin-top: 3px; color: #7a8799; font-size: 10px; line-height: 1.5; }
|
||||
.dashboard-attention-row > b { font-size: 16px; color: #a66313; }
|
||||
.dashboard-attention-row > .material-symbols-outlined { font-size: 15px; color: #a5b0c1; }
|
||||
.dashboard-shortage-list { display: grid; gap: 10px; margin: 14px 0 0 46px; padding-left: 12px; border-left: 2px solid #f0f3f8; }
|
||||
.dashboard-shortage-list a { display: flex; justify-content: space-between; gap: 12px; min-width: 0; font-size: 11px; }
|
||||
.dashboard-shortage-list a > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #64748b; }
|
||||
.dashboard-shortage-list small { flex-shrink: 0; font-size: 10px; color: #be4658; }
|
||||
.dashboard-shortage-list .dashboard-inline-link { margin-top: 0; }
|
||||
.dashboard-robot-row { display: flex; align-items: center; gap: 12px; margin-top: 16px; }
|
||||
.dashboard-robot-row > div:first-child { height: 54px; width: 54px; border-radius: 9px; }
|
||||
.dashboard-robot-row > span:nth-child(2) { flex: 1; min-width: 0; }
|
||||
.dashboard-resources { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
.dashboard-resource { display: flex; align-items: center; gap: 10px; min-width: 0; padding: 14px 16px; background: white; border: 1px solid #e3e9f1; border-radius: 10px; font-size: 12px; color: #64748b; }
|
||||
.dashboard-resource > .material-symbols-outlined { font-size: 19px; color: #8997b2; }
|
||||
.dashboard-resource strong { margin-left: auto; font-size: 16px; color: #334155; }
|
||||
.dashboard-resource > .material-symbols-outlined:last-child { font-size: 14px; }
|
||||
.dashboard-shell a:hover strong, .dashboard-attention-row:hover strong { color: #3755c3; }
|
||||
.dashboard-shell :is(a, button):focus-visible { outline: 2px solid #3755c3; outline-offset: 4px; border-radius: 6px; }
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.dashboard-layout { grid-template-columns: minmax(0, 1fr); }
|
||||
.dashboard-side-column { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; }
|
||||
.dashboard-metric { padding: 16px; }
|
||||
.dashboard-metric-top { gap: 7px; font-size: 11px; }
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.dashboard-shell .dashboard-header { align-items: flex-start; gap: 12px; margin-bottom: 18px; }
|
||||
.dashboard-actions { width: 100%; justify-content: space-between; gap: 8px; }
|
||||
.dashboard-updated { font-size: 10px; }
|
||||
.dashboard-refresh { min-height: 40px; }
|
||||
.dashboard-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin-bottom: 14px; }
|
||||
.dashboard-metric { padding: 12px; }
|
||||
.dashboard-metric-top { flex-wrap: wrap; gap: 7px; font-size: 11px; }
|
||||
.dashboard-metric-top > .material-symbols-outlined { display: none; }
|
||||
.dashboard-metric .dashboard-icon { height: 28px; width: 28px; border-radius: 8px; }
|
||||
.dashboard-metric .dashboard-icon .material-symbols-outlined { font-size: 17px; }
|
||||
.dashboard-metric-value { font-size: 28px; margin-top: 12px; gap: 5px; }
|
||||
.dashboard-metric-value > span { font-size: 10px; }
|
||||
.dashboard-metric > p { min-height: 39px; margin-top: 9px; padding-top: 9px; font-size: 10px; }
|
||||
.dashboard-stock-grid, .dashboard-side-column { grid-template-columns: minmax(0, 1fr); gap: 14px; }
|
||||
.dashboard-layout, .dashboard-main-column { gap: 14px; }
|
||||
.dashboard-panel { padding: 16px; }
|
||||
.dashboard-recent-row { grid-template-columns: 32px minmax(0, 1fr) auto; gap: 8px; }
|
||||
.dashboard-recent-row > .dashboard-icon { width: 32px; height: 32px; grid-row: span 2; }
|
||||
.dashboard-recent-row time { grid-column: 2 / 4; }
|
||||
.dashboard-recent-row > .material-symbols-outlined { display: none; }
|
||||
.dashboard-resource { padding: 12px; gap: 7px; font-size: 11px; }
|
||||
.dashboard-resource > .material-symbols-outlined:last-child { display: none; }
|
||||
.dashboard-resources { gap: 10px; }
|
||||
}
|
||||
567
public/js/app.js
567
public/js/app.js
@@ -89,7 +89,14 @@ class AccountManager {
|
||||
this.notificationSourceFilter = '';
|
||||
this.notificationPagination = { page: 1, pageSize: 20, total: 0, totalPages: 1 };
|
||||
this.notificationLoading = false;
|
||||
this.notificationLoadError = '';
|
||||
this.notificationWithdrawalPending = false;
|
||||
this.notificationPollTimer = undefined;
|
||||
this.announcementItems = [];
|
||||
this.announcementShownIds = new Set();
|
||||
this.announcementLoading = false;
|
||||
this.announcementClosing = false;
|
||||
this.announcementExpiryTimer = undefined;
|
||||
this.accountPage = 1;
|
||||
this.accountPageSize = 9;
|
||||
this.appPage = 1;
|
||||
@@ -108,6 +115,9 @@ class AccountManager {
|
||||
this.myBorrowedAssetPageSize = 10;
|
||||
this.apiBase = '/api';
|
||||
this.currentPage = 'dashboard';
|
||||
this.dashboardLoading = false;
|
||||
this.dashboardSourceErrors = {};
|
||||
this.dashboardUpdatedAt = null;
|
||||
this.accountSearchTerm = '';
|
||||
this.applicationSearchTerm = '';
|
||||
this.accountServiceFilter = '';
|
||||
@@ -293,6 +303,8 @@ class AccountManager {
|
||||
|
||||
if (this.canCurrentUserManageAssets()) {
|
||||
await this.fetchUsers();
|
||||
const administrationSection = document.getElementById('usersSection');
|
||||
if (administrationSection) administrationSection.style.display = '';
|
||||
}
|
||||
|
||||
// Check if user is admin and fetch roles
|
||||
@@ -313,11 +325,13 @@ class AccountManager {
|
||||
// Single-page navigation based on hash
|
||||
this.handleRoute(location.hash || '#dashboard');
|
||||
window.addEventListener('hashchange', () => this.handleRoute(location.hash));
|
||||
this.fetchAnnouncementPopups();
|
||||
}
|
||||
|
||||
handleRoute(hash) {
|
||||
const route = (hash || '#dashboard').replace('#', '') || 'dashboard';
|
||||
if (route !== this.currentPage) document.getElementById('robotDeleteDialog')?.close();
|
||||
if (route !== this.currentPage) document.getElementById('notificationWithdrawDialog')?.close();
|
||||
if (this.currentPage === 'robot-bom' && route !== 'robot-bom') {
|
||||
if (this.robotBom?.dirty && !this.robotBom.discardChanges()) {
|
||||
history.replaceState(null, '', '#robot-bom');
|
||||
@@ -332,6 +346,13 @@ class AccountManager {
|
||||
}
|
||||
|
||||
renderView(page) {
|
||||
if (page === 'notification-management' && !this.canCurrentUserManageAssets()) page = 'notifications';
|
||||
if (page !== this.currentPage && ['notifications', 'notification-management'].includes(page)) {
|
||||
this.notificationPage = 1;
|
||||
this.notificationItems = [];
|
||||
this.notificationLoadError = '';
|
||||
this.notificationPagination = { page: 1, pageSize: this.notificationPageSize, total: 0, totalPages: 1 };
|
||||
}
|
||||
if (page === 'asset-borrows' && this.currentPage !== 'asset-borrows') {
|
||||
this.assetBorrowCatalogFilter = 'current';
|
||||
this.assetBorrowPage = 1;
|
||||
@@ -396,7 +417,7 @@ class AccountManager {
|
||||
} else if (page === 'documents') {
|
||||
mainContent.innerHTML = this.getDocumentsContent();
|
||||
this.setupDocumentListeners();
|
||||
} else if (page === 'notifications') {
|
||||
} else if (page === 'notifications' || page === 'notification-management') {
|
||||
mainContent.innerHTML = this.getNotificationsContent();
|
||||
this.setupNotificationsPageListeners();
|
||||
this.refreshNotificationsPage();
|
||||
@@ -412,6 +433,8 @@ class AccountManager {
|
||||
}
|
||||
} else {
|
||||
mainContent.innerHTML = this.renderDashboard();
|
||||
this.setupDashboardListeners();
|
||||
this.refreshDashboard();
|
||||
}
|
||||
|
||||
if (page === 'asset-borrows') {
|
||||
@@ -591,13 +614,40 @@ class AccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
async fetchNotificationJson(endpoint = '', options = {}) {
|
||||
const response = await fetch(`${this.apiBase}/notifications${endpoint}`, {
|
||||
cache: 'no-store',
|
||||
...options,
|
||||
headers: { Accept: 'application/json', ...options.headers }
|
||||
});
|
||||
const contentType = response.headers.get('content-type') || '';
|
||||
if (!/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(contentType)) {
|
||||
const unavailable = response.status === 404 || response.ok;
|
||||
const error = new Error(unavailable
|
||||
? 'Chức năng thông báo chưa được nạp trên máy chủ. Vui lòng khởi động lại backend rồi tải lại trang.'
|
||||
: `Không tải được thông báo (HTTP ${response.status}). Vui lòng thử lại sau.`);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
let data;
|
||||
try {
|
||||
data = await response.json();
|
||||
} catch {
|
||||
throw new Error('Dữ liệu thông báo trả về không hợp lệ. Vui lòng tải lại trang hoặc thử lại sau.');
|
||||
}
|
||||
if (!response.ok || !data?.success) {
|
||||
const error = new Error(data?.code === 'API_NOT_FOUND'
|
||||
? 'Chức năng thông báo chưa được nạp trên máy chủ. Vui lòng khởi động lại backend rồi tải lại trang.'
|
||||
: data?.message || 'Không thể xử lý thông báo. Vui lòng thử lại sau.');
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
const data = await this.fetchNotificationJson('?page=1&pageSize=5&filter=all');
|
||||
this.notificationPreviewItems = Array.isArray(data.data) ? data.data : [];
|
||||
this.notificationUnreadCount = Number(data.unreadCount) || 0;
|
||||
this.renderNotificationShell();
|
||||
@@ -608,7 +658,118 @@ class AccountManager {
|
||||
|
||||
startNotificationPolling() {
|
||||
if (this.notificationPollTimer) window.clearInterval(this.notificationPollTimer);
|
||||
this.notificationPollTimer = window.setInterval(() => this.fetchNotificationPreview(), 60000);
|
||||
this.notificationPollTimer = window.setInterval(() => Promise.all([
|
||||
this.fetchNotificationPreview(), this.fetchAnnouncementPopups()
|
||||
]), 60000);
|
||||
}
|
||||
|
||||
async fetchAnnouncementPopups() {
|
||||
if (this.announcementLoading) return;
|
||||
this.announcementLoading = true;
|
||||
try {
|
||||
const data = await this.fetchNotificationJson('/announcements', { signal: AbortSignal.timeout(15000) });
|
||||
if (!Array.isArray(data.data)) throw new Error('Không tải được thông báo popup');
|
||||
this.announcementItems = data.data;
|
||||
const current = document.getElementById('announcementDialog');
|
||||
if (current && !this.announcementClosing && !data.data.some(item => Number(item.NotificationId) === Number(current.dataset.notificationId))) {
|
||||
window.clearTimeout(this.announcementExpiryTimer);
|
||||
current.close();
|
||||
current.remove();
|
||||
}
|
||||
this.showNextAnnouncement();
|
||||
} catch (error) {
|
||||
console.error('Fetch announcement error:', error);
|
||||
} finally {
|
||||
this.announcementLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
getNextAnnouncement() {
|
||||
return this.announcementItems.find(item => String(item.Source).toLowerCase() === 'admin'
|
||||
&& !this.announcementShownIds.has(Number(item.NotificationId))
|
||||
&& (!item.ExpiresAt || new Date(item.ExpiresAt).getTime() > Date.now()));
|
||||
}
|
||||
|
||||
showNextAnnouncement() {
|
||||
if (document.getElementById('announcementDialog')) return;
|
||||
const item = this.getNextAnnouncement();
|
||||
if (!item) return;
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.id = 'announcementDialog';
|
||||
dialog.className = 'announcement-dialog';
|
||||
dialog.dataset.notificationId = String(Number(item.NotificationId));
|
||||
dialog.setAttribute('aria-labelledby', 'announcementTitle');
|
||||
dialog.setAttribute('aria-describedby', 'announcementMessage');
|
||||
dialog.innerHTML = `<div class="announcement-heading">
|
||||
<span class="announcement-symbol material-symbols-outlined" aria-hidden="true">campaign</span>
|
||||
<div><p>THÔNG BÁO CHUNG</p><h2 id="announcementTitle">${this.escapeHtml(item.Title)}</h2></div>
|
||||
<button type="button" data-announcement-close aria-label="Đóng thông báo"><span class="material-symbols-outlined" aria-hidden="true">close</span></button>
|
||||
</div>
|
||||
<div class="announcement-body"><p class="announcement-author">${this.escapeHtml(item.CreatedByName || 'Admin / Asset')}${item.ExpiresAt ? ` · Kết thúc: ${this.escapeHtml(this.formatDateTime(item.ExpiresAt))}` : ''}</p>
|
||||
<p id="announcementMessage">${this.escapeHtml(item.Message)}</p>
|
||||
<p id="announcementError" class="announcement-error" role="alert" hidden></p>
|
||||
</div>
|
||||
<div class="announcement-footer"><label><input id="announcementDontShowAgain" type="checkbox" /> <span>Không hiện lại thông báo này</span></label>
|
||||
<p>Nếu chỉ đóng, thông báo sẽ hiện lại vào lần truy cập sau.</p>
|
||||
<div>${item.ActionUrl ? '<button type="button" class="announcement-secondary" data-announcement-action>Xem nội dung</button>' : ''}<button type="button" class="announcement-primary" data-announcement-close autofocus>Đã hiểu</button></div>
|
||||
</div>`;
|
||||
document.body.appendChild(dialog);
|
||||
this.announcementShownIds.add(Number(item.NotificationId));
|
||||
dialog.querySelectorAll('[data-announcement-close]').forEach(button => button.addEventListener('click', () => this.finishAnnouncement()));
|
||||
dialog.querySelector('[data-announcement-action]')?.addEventListener('click', () => this.finishAnnouncement({ navigate: true }));
|
||||
dialog.addEventListener('cancel', event => { event.preventDefault(); this.finishAnnouncement(); });
|
||||
dialog.addEventListener('click', event => {
|
||||
if (event.target !== dialog) return;
|
||||
const rect = dialog.getBoundingClientRect();
|
||||
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) this.finishAnnouncement();
|
||||
});
|
||||
dialog.showModal();
|
||||
this.scheduleAnnouncementExpiry(item);
|
||||
}
|
||||
|
||||
scheduleAnnouncementExpiry(item) {
|
||||
window.clearTimeout(this.announcementExpiryTimer);
|
||||
if (!item.ExpiresAt) return;
|
||||
const remaining = new Date(item.ExpiresAt).getTime() - Date.now();
|
||||
this.announcementExpiryTimer = window.setTimeout(() => {
|
||||
if (new Date(item.ExpiresAt).getTime() > Date.now()) this.scheduleAnnouncementExpiry(item);
|
||||
else this.finishAnnouncement({ expired: true });
|
||||
}, Math.max(0, Math.min(remaining, 2147483647)));
|
||||
}
|
||||
|
||||
async finishAnnouncement({ navigate = false, expired = false } = {}) {
|
||||
const dialog = document.getElementById('announcementDialog');
|
||||
if (!dialog || this.announcementClosing) return;
|
||||
const notificationId = Number(dialog.dataset.notificationId);
|
||||
const item = this.announcementItems.find(entry => Number(entry.NotificationId) === notificationId);
|
||||
this.announcementClosing = true;
|
||||
dialog.querySelectorAll('button').forEach(button => { button.disabled = true; });
|
||||
try {
|
||||
if (!expired && dialog.querySelector('#announcementDontShowAgain').checked) {
|
||||
await this.fetchNotificationJson(`/${notificationId}/dismiss`, { method: 'PUT', signal: AbortSignal.timeout(15000) });
|
||||
}
|
||||
if (!expired && item && !item.IsRead) await this.markNotificationRead(notificationId);
|
||||
window.clearTimeout(this.announcementExpiryTimer);
|
||||
dialog.close();
|
||||
dialog.remove();
|
||||
if (navigate && item) {
|
||||
this.closeNotificationPopover();
|
||||
const actionUrl = String(item.ActionUrl || '');
|
||||
if (actionUrl.startsWith('#')) window.location.hash = actionUrl;
|
||||
else if (/^\/(?!\/)[^\\\r\n]*$/.test(actionUrl)) window.location.assign(actionUrl);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorBox = dialog.querySelector('#announcementError');
|
||||
errorBox.textContent = error.message || 'Không lưu được lựa chọn.';
|
||||
errorBox.hidden = false;
|
||||
dialog.querySelectorAll('button').forEach(button => { button.disabled = false; });
|
||||
} finally {
|
||||
this.announcementClosing = false;
|
||||
}
|
||||
if (document.getElementById('announcementDialog') === dialog && item?.ExpiresAt && new Date(item.ExpiresAt).getTime() <= Date.now()) {
|
||||
return this.finishAnnouncement({ expired: true });
|
||||
}
|
||||
if (!document.getElementById('announcementDialog')) this.showNextAnnouncement();
|
||||
}
|
||||
|
||||
setupNotificationShell() {
|
||||
@@ -664,15 +825,15 @@ class AccountManager {
|
||||
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' }
|
||||
success: { icon: 'check_circle', iconClass: 'bg-emerald-100 text-emerald-700' },
|
||||
warning: { icon: 'warning', iconClass: 'bg-amber-100 text-amber-700' },
|
||||
error: { icon: 'error', iconClass: 'bg-red-100 text-red-700' },
|
||||
info: { icon: 'info', iconClass: 'bg-blue-100 text-blue-700' }
|
||||
};
|
||||
const source = String(item.Source || 'system').toLowerCase();
|
||||
return {
|
||||
...(severityMap[severity] || severityMap.info),
|
||||
sourceLabel: source === 'admin' ? 'Quản trị viên' : 'Hệ thống',
|
||||
sourceLabel: source === 'admin' ? 'Thông báo chung' : 'Cá nhân / Hệ thống',
|
||||
sourceIcon: source === 'admin' ? 'campaign' : 'settings_suggest'
|
||||
};
|
||||
}
|
||||
@@ -750,20 +911,23 @@ class AccountManager {
|
||||
});
|
||||
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');
|
||||
const route = this.currentPage;
|
||||
const endpoint = route === 'notification-management' ? '/manage' : '';
|
||||
const data = await this.fetchNotificationJson(`${endpoint}?${params.toString()}`);
|
||||
if (this.currentPage !== route) return;
|
||||
this.notificationItems = Array.isArray(data.data) ? data.data : [];
|
||||
this.notificationPagination = data.pagination || this.notificationPagination;
|
||||
}
|
||||
|
||||
async refreshNotificationsPage() {
|
||||
this.notificationLoading = true;
|
||||
this.notificationLoadError = '';
|
||||
this.renderNotificationsPage();
|
||||
try {
|
||||
await this.fetchNotifications();
|
||||
} catch (err) {
|
||||
console.error('Fetch notifications error:', err);
|
||||
this.notificationLoadError = err.message || 'Không thể tải thông báo';
|
||||
this.notifyFailure(err.message || 'Không thể tải thông báo');
|
||||
} finally {
|
||||
this.notificationLoading = false;
|
||||
@@ -772,7 +936,7 @@ class AccountManager {
|
||||
}
|
||||
|
||||
renderNotificationsPage() {
|
||||
if (this.currentPage !== 'notifications') return;
|
||||
if (!['notifications', 'notification-management'].includes(this.currentPage)) return;
|
||||
const mainContent = document.getElementById('mainContent');
|
||||
if (!mainContent) return;
|
||||
mainContent.innerHTML = this.getNotificationsContent();
|
||||
@@ -782,12 +946,17 @@ class AccountManager {
|
||||
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 managing = this.currentPage === 'notification-management';
|
||||
const active = item.IsActive !== false && item.IsActive !== 0;
|
||||
const expired = item.ExpiresAt && new Date(item.ExpiresAt).getTime() <= Date.now();
|
||||
const canWithdraw = managing && active && this.canCurrentUserManageAssets()
|
||||
&& (this.isCurrentUserAdmin() || Number(item.CreatedBy) === Number(this.getUserId()))
|
||||
&& String(item.Source).toLowerCase() === 'admin';
|
||||
const author = String(item.Source).toLowerCase() === 'admin'
|
||||
? (item.CreatedByName || 'Quản trị viên')
|
||||
? (item.CreatedByName || 'Admin / Asset')
|
||||
: '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' : ''}">
|
||||
<article class="rounded-2xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 p-4 shadow-sm ${isRead && !managing ? '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>
|
||||
@@ -797,7 +966,7 @@ class AccountManager {
|
||||
<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>'}
|
||||
${isRead || managing ? '' : '<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>
|
||||
@@ -806,9 +975,11 @@ class AccountManager {
|
||||
</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>
|
||||
${item.ExpiresAt ? `<p class="mt-2 text-xs text-slate-500">Kết thúc: ${this.escapeHtml(this.formatDateTime(item.ExpiresAt))}</p>` : ''}
|
||||
${managing ? `<p class="announcement-post-status">${!active ? 'Đã thu hồi' : expired ? 'Đã kết thúc' : 'Đang hiển thị popup'}</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>` : ''}
|
||||
${!isRead && !managing ? `<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>
|
||||
@@ -817,12 +988,15 @@ class AccountManager {
|
||||
}
|
||||
|
||||
getNotificationsContent() {
|
||||
const managing = this.currentPage === 'notification-management' && this.canCurrentUserManageAssets();
|
||||
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.notificationLoadError
|
||||
? `<div class="announcement-management-note" role="alert"><p>${this.escapeHtml(this.notificationLoadError)}</p><button id="retryNotificationsBtn" type="button" class="mt-3 rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-bold text-primary">Thử lại</button></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>`;
|
||||
@@ -832,14 +1006,14 @@ class AccountManager {
|
||||
<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 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">${managing ? 'campaign' : 'notifications'}</span>${managing ? 'Quản trị viên' : 'Trung tâm thông báo'}</div>
|
||||
<h1 class="mt-3 text-2xl font-extrabold text-slate-900 dark:text-slate-50">${managing ? 'Đăng thông báo' : 'Thông báo của bạn'}</h1>
|
||||
<p class="mt-1 text-sm text-slate-500">${managing ? 'Admin / Asset đăng thông báo popup cho người dùng và đặt thời gian kết thúc.' : 'Thông báo chung và kết quả mượn / trả dành riêng cho tài khoản của bạ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>` : ''}
|
||||
${managing ? `<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>Đăng thông báo</button>` : ''}
|
||||
</header>
|
||||
|
||||
<section class="mt-6 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
${!managing ? `<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>
|
||||
@@ -850,12 +1024,12 @@ class AccountManager {
|
||||
<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>
|
||||
<option value="admin" ${this.notificationSourceFilter === 'admin' ? 'selected' : ''}>Thông báo chung</option>
|
||||
<option value="system" ${this.notificationSourceFilter === 'system' ? 'selected' : ''}>Mượn/trả & 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>
|
||||
</section>` : `<p class="announcement-management-note">${total} thông báo đã đăng. Popup tự dừng khi hết hạn hoặc bị thu hồi. Asset có thể thu hồi thông báo do mình đăng; Admin có thể thu hồi mọi thông báo.</p>`}
|
||||
|
||||
<div class="mt-4 space-y-3">${listHtml}</div>
|
||||
|
||||
@@ -892,21 +1066,21 @@ class AccountManager {
|
||||
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());
|
||||
document.getElementById('retryNotificationsBtn')?.addEventListener('click', () => this.refreshNotificationsPage());
|
||||
}
|
||||
|
||||
findNotification(notificationId) {
|
||||
return this.notificationItems.find(item => Number(item.NotificationId) === Number(notificationId))
|
||||
|| this.notificationPreviewItems.find(item => Number(item.NotificationId) === Number(notificationId));
|
||||
|| this.notificationPreviewItems.find(item => Number(item.NotificationId) === Number(notificationId))
|
||||
|| this.announcementItems?.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 => {
|
||||
await this.fetchNotificationJson(`/${notificationId}/read`, { method: 'PUT' });
|
||||
[...this.notificationItems, ...this.notificationPreviewItems, ...(this.announcementItems || [])].forEach(entry => {
|
||||
if (Number(entry.NotificationId) === Number(notificationId)) entry.IsRead = true;
|
||||
});
|
||||
this.notificationUnreadCount = Math.max(0, this.notificationUnreadCount - 1);
|
||||
@@ -931,9 +1105,7 @@ class AccountManager {
|
||||
|
||||
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');
|
||||
await this.fetchNotificationJson('/read-all', { method: 'PUT' });
|
||||
this.notificationItems.forEach(item => { item.IsRead = true; });
|
||||
this.notificationPreviewItems.forEach(item => { item.IsRead = true; });
|
||||
this.notificationUnreadCount = 0;
|
||||
@@ -945,21 +1117,65 @@ class AccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
confirmNotificationWithdrawal(item) {
|
||||
if (document.getElementById('notificationWithdrawDialog')) return Promise.resolve(false);
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.id = 'notificationWithdrawDialog';
|
||||
dialog.className = 'bom-dialog bom-confirm-dialog notification-withdraw-dialog';
|
||||
dialog.setAttribute('aria-labelledby', 'notificationWithdrawTitle');
|
||||
dialog.setAttribute('aria-describedby', 'notificationWithdrawDescription');
|
||||
dialog.innerHTML = `<header class="bom-dialog-header">
|
||||
<div class="bom-confirm-heading"><span class="bom-confirm-icon material-symbols-outlined" aria-hidden="true">cancel</span>
|
||||
<div><p class="bom-eyebrow">QUẢN LÝ THÔNG BÁO</p><h2 id="notificationWithdrawTitle">Thu hồi thông báo?</h2></div></div>
|
||||
<button type="button" data-cancel-notification-withdraw aria-label="Đóng"><span class="material-symbols-outlined" aria-hidden="true">close</span></button>
|
||||
</header>
|
||||
<div class="bom-confirm-body"><p id="notificationWithdrawDescription">Thông báo này sẽ ngừng hiển thị với tất cả người dùng.</p>
|
||||
<div class="notification-withdraw-summary"><strong>${this.escapeHtml(item.Title || 'Thông báo')}</strong>
|
||||
${item.CreatedByName ? `<p>Đăng bởi ${this.escapeHtml(item.CreatedByName)}</p>` : ''}</div>
|
||||
<div class="bom-publish-note"><span class="material-symbols-outlined" aria-hidden="true">info</span><p>Thông báo đã thu hồi vẫn được lưu trong danh sách quản trị.</p></div>
|
||||
</div>
|
||||
<footer class="bom-dialog-footer"><div>
|
||||
<button type="button" data-cancel-notification-withdraw class="bom-btn">Hủy</button>
|
||||
<button type="button" data-confirm-notification-withdraw class="bom-btn bom-btn-danger"><span class="material-symbols-outlined" aria-hidden="true">cancel</span>Thu hồi</button>
|
||||
</div></footer>`;
|
||||
return new Promise(resolve => {
|
||||
dialog.addEventListener('click', event => {
|
||||
if (event.target.closest('[data-confirm-notification-withdraw]')) dialog.close('confirm');
|
||||
else if (event.target.closest('[data-cancel-notification-withdraw]')) dialog.close();
|
||||
else if (event.target === dialog) {
|
||||
const rect = dialog.getBoundingClientRect();
|
||||
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close();
|
||||
}
|
||||
});
|
||||
dialog.addEventListener('close', () => {
|
||||
dialog.remove();
|
||||
resolve(dialog.returnValue === 'confirm');
|
||||
}, { once: true });
|
||||
document.body.appendChild(dialog);
|
||||
dialog.showModal();
|
||||
dialog.querySelector('.bom-dialog-footer [data-cancel-notification-withdraw]').focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
if (this.notificationWithdrawalPending || !this.canCurrentUserManageAssets()) return;
|
||||
const item = this.findNotification(notificationId);
|
||||
if (!item) return;
|
||||
this.notificationWithdrawalPending = true;
|
||||
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');
|
||||
if (!await this.confirmNotificationWithdrawal(item)) return;
|
||||
await this.fetchNotificationJson(`/${notificationId}`, { method: 'DELETE' });
|
||||
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');
|
||||
} finally {
|
||||
this.notificationWithdrawalPending = false;
|
||||
}
|
||||
}
|
||||
|
||||
openNotificationComposer() {
|
||||
if (!this.isCurrentUserAdmin()) return;
|
||||
if (!this.canCurrentUserManageAssets()) return;
|
||||
document.getElementById('notificationComposerModal')?.remove();
|
||||
const container = document.createElement('div');
|
||||
container.id = 'notificationComposerModal';
|
||||
@@ -967,18 +1183,20 @@ class AccountManager {
|
||||
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>
|
||||
<div><h2 id="notificationComposerTitle" class="text-lg font-extrabold text-slate-900 dark:text-slate-50">Đăng thông báo popup</h2><p class="mt-1 text-xs text-slate-500">Hiện mỗi lần truy cập đến khi kết thúc hoặc người dùng chọn “Không hiện lại”.</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><label for="notificationExpiryInput" class="mb-1.5 block text-xs font-bold text-slate-700 dark:text-slate-200">Ngày giờ kết thúc <span class="text-red-500">*</span></label><input id="notificationExpiryInput" type="datetime-local" 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" /><p class="mt-1 text-xs text-slate-500">Theo giờ Việt Nam (UTC+7). Thông báo sẽ tự ngừng hiển thị khi đến hạn.</p></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 expiryParts = this.getAppTimeParts(new Date(Date.now() + 7 * 86400000));
|
||||
document.getElementById('notificationExpiryInput').value = `${expiryParts.year}-${expiryParts.month}-${expiryParts.day}T${expiryParts.hour}:${expiryParts.minute}`;
|
||||
const close = () => container.remove();
|
||||
document.getElementById('closeNotificationComposerBtn')?.addEventListener('click', close);
|
||||
document.getElementById('cancelNotificationComposerBtn')?.addEventListener('click', close);
|
||||
@@ -991,24 +1209,28 @@ class AccountManager {
|
||||
|
||||
async submitNotification(event, closeComposer) {
|
||||
event.preventDefault();
|
||||
if (!this.canCurrentUserManageAssets()) return;
|
||||
const expiryValue = document.getElementById('notificationExpiryInput')?.value || '';
|
||||
const expiry = expiryValue ? new Date(`${expiryValue}+07:00`) : null;
|
||||
if (!expiry || !Number.isFinite(expiry.getTime()) || expiry.getTime() <= Date.now()) {
|
||||
this.notifyWarning('Vui lòng chọn ngày giờ kết thúc trong tương lai (giờ Việt Nam).');
|
||||
return;
|
||||
}
|
||||
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
|
||||
expiresAt: expiry.toISOString()
|
||||
};
|
||||
const sendButton = document.getElementById('sendNotificationBtn');
|
||||
if (sendButton) sendButton.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/notifications`, {
|
||||
await this.fetchNotificationJson('', {
|
||||
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;
|
||||
@@ -3169,85 +3391,188 @@ class AccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
getDashboardSummary() {
|
||||
const rows = key => this.dashboardSourceErrors?.[key] ? [] : (Array.isArray(this[key]) ? this[key] : []);
|
||||
const assets = rows('assets').filter(item => !this.isArchivedAsset(item));
|
||||
const assetStock = { inStock: 0, inUse: 0, exported: 0 };
|
||||
for (const asset of assets) {
|
||||
const metrics = this.buildAssetQuantityMetrics(asset);
|
||||
const available = this.getAssetAvailableForExport(asset);
|
||||
assetStock[available <= 0 ? 'exported' : metrics.exportInPeriod > 0 ? 'inUse' : 'inStock']++;
|
||||
}
|
||||
const consumables = rows('consumables');
|
||||
const outOfStock = consumables.filter(item => this.getConsumableStockStatusMeta(item).key === 'out_of_stock');
|
||||
const pendingAssets = rows('assetBorrows').filter(item => this.normalizeAssetRequestStatus(item.RequestStatus) === 'pending');
|
||||
const pendingConsumables = rows('consumableBorrowRequests').filter(item => this.getConsumableBorrowRequestStatusMeta(item.RequestStatus).key === 'pending');
|
||||
const recent = [
|
||||
...assets.map(item => ({ source: 'Tài sản', icon: 'inventory_2', tone: 'blue', href: '#assets', name: item.AssetName, code: item.AssetCode, date: item.UpdatedDate || item.CreatedDate })),
|
||||
...consumables.map(item => ({ source: 'Vật tư', icon: 'category', tone: 'green', href: '#consumables', name: item.ConsumableName, code: item.ConsumableCode, date: item.UpdatedDate || item.CreatedDate })),
|
||||
...rows('robots').map(item => ({ source: 'Robot', icon: 'smart_toy', tone: 'purple', href: '#robots', name: item.Name, code: item.Model, date: item.UpdatedDate || item.CreatedDate })),
|
||||
...rows('documents').map(item => ({ source: 'Tài liệu', icon: 'description', tone: 'blue', href: '#documents', name: item.Title || item.OriginalFileName || item.FileName, code: item.RobotName, date: item.UploadedDate || item.CreatedDate }))
|
||||
].filter(item => item.date && Number.isFinite(new Date(item.date).getTime()))
|
||||
.sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 6);
|
||||
const robots = [...rows('robots')].sort((a, b) => (Date.parse(b.UpdatedDate || b.CreatedDate) || 0) - (Date.parse(a.UpdatedDate || a.CreatedDate) || 0));
|
||||
return { assets, assetStock, consumables, outOfStock, pendingAssets, pendingConsumables, recent, robots };
|
||||
}
|
||||
|
||||
setupDashboardListeners() {
|
||||
document.getElementById('refreshDashboardBtn')?.addEventListener('click', () => this.refreshDashboard());
|
||||
document.querySelectorAll('[data-dashboard-action]').forEach(button => {
|
||||
button.addEventListener('click', async () => {
|
||||
if (button.dataset.dashboardAction === 'consumable-requests') {
|
||||
await this.openConsumableBorrowRequestsModal();
|
||||
} else if (this.canCurrentUserManageAssets()) {
|
||||
await this.openPendingAssetRequestsModal();
|
||||
} else {
|
||||
location.hash = '#asset-borrows';
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async refreshDashboard() {
|
||||
if (this.dashboardLoading) return;
|
||||
this.dashboardSourceErrors ||= {};
|
||||
this.dashboardLoading = true;
|
||||
const button = document.getElementById('refreshDashboardBtn');
|
||||
if (button) {
|
||||
button.disabled = true;
|
||||
button.setAttribute('aria-busy', 'true');
|
||||
button.innerHTML = '<span class="material-symbols-outlined" aria-hidden="true">sync</span>Đang tải…';
|
||||
}
|
||||
const sources = [
|
||||
['assets', 'assets', 'Tài sản'], ['consumables', 'consumables', 'Vật tư tiêu hao'],
|
||||
['robots', 'robots', 'Robot'], ['robotTypes', 'robots/types', 'Thể loại robot'],
|
||||
['assetBorrows', 'asset-borrows', 'Yêu cầu tài sản'],
|
||||
['consumableBorrowRequests', 'consumable-borrows', 'Yêu cầu vật tư'],
|
||||
['documents', 'documents', 'Tài liệu'], ['accounts', 'accounts/all', 'Tài khoản'],
|
||||
['assetProjects', 'asset-projects', 'Dự án'],
|
||||
['assetDepartments', 'asset-departments', 'Phòng ban']
|
||||
];
|
||||
const results = await Promise.allSettled(sources.map(async ([, endpoint]) => {
|
||||
const response = await fetch(`${this.apiBase}/${endpoint}`, { cache: 'no-store', signal: AbortSignal.timeout(15000) });
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success || !Array.isArray(data.data)) throw new Error('Không tải được dữ liệu');
|
||||
return data.data;
|
||||
}));
|
||||
results.forEach((result, index) => {
|
||||
const [key, , label] = sources[index];
|
||||
if (result.status === 'fulfilled') {
|
||||
this[key] = key === 'assets' ? result.value.map(asset => this.normalizeAssetComputedFields(asset)) : result.value;
|
||||
if (key === 'robots') this.robotLoadError = '';
|
||||
if (key === 'robotTypes') this.robotTypesLoadError = '';
|
||||
delete this.dashboardSourceErrors[key];
|
||||
} else {
|
||||
this.dashboardSourceErrors[key] = label;
|
||||
}
|
||||
});
|
||||
this.dashboardLoading = false;
|
||||
this.dashboardUpdatedAt = new Date();
|
||||
this.syncSelectedAssetIds();
|
||||
this.updatePendingAssetRequestsBadge();
|
||||
this.updateConsumableBorrowRequestBadges();
|
||||
if (this.currentPage === 'dashboard') {
|
||||
const mainContent = document.getElementById('mainContent');
|
||||
if (mainContent) {
|
||||
const scrollTop = mainContent.querySelector('.dashboard-page')?.scrollTop || 0;
|
||||
mainContent.innerHTML = this.renderDashboard();
|
||||
this.setupDashboardListeners();
|
||||
mainContent.querySelector('.dashboard-page').scrollTop = scrollTop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
renderDashboard() {
|
||||
return `
|
||||
<div class="dashboard-page flex-1 flex flex-col p-4 md:p-6 space-y-6 min-h-0 overflow-auto">
|
||||
<!-- Title and Stats -->
|
||||
<div class="dashboard-header flex items-end justify-between shrink-0">
|
||||
<div>
|
||||
<h1 class="text-2xl font-extrabold text-on-surface tracking-tight leading-none">System Overview</h1>
|
||||
<p class="text-xs text-on-surface-variant font-medium mt-1">Account & Service Management</p>
|
||||
</div>
|
||||
<div class="dashboard-actions flex gap-2">
|
||||
<a href="#accounts" class="py-1.5 px-3 bg-primary text-on-primary rounded-lg text-xs font-bold flex items-center gap-1.5 shadow-sm active:scale-95 duration-100">
|
||||
<span class="material-symbols-outlined text-sm">add</span>
|
||||
Add Account
|
||||
</a>
|
||||
</div>
|
||||
const summary = this.getDashboardSummary();
|
||||
const errors = this.dashboardSourceErrors || {};
|
||||
const failedSources = Object.values(errors);
|
||||
const safe = value => this.escapeHtml(value);
|
||||
const number = value => Number(value).toLocaleString('vi-VN');
|
||||
const count = (key, value) => errors[key] ? '—' : number(value);
|
||||
const length = key => Array.isArray(this[key]) ? this[key].length : 0;
|
||||
const requestsFailed = errors.assetBorrows || errors.consumableBorrowRequests;
|
||||
const pendingCount = summary.pendingAssets.length + summary.pendingConsumables.length;
|
||||
const icon = name => `<span class="material-symbols-outlined" aria-hidden="true">${name}</span>`;
|
||||
const empty = message => `<div class="dashboard-empty">${icon('inbox')}<p>${message}</p></div>`;
|
||||
const card = (href, symbol, tone, label, value, unit, detail) => `
|
||||
<a href="${href}" class="dashboard-metric dashboard-tone-${tone}">
|
||||
<div class="dashboard-metric-top"><span class="dashboard-icon">${icon(symbol)}</span><span>${label}</span>${icon('arrow_outward')}</div>
|
||||
<div class="dashboard-metric-value">${value}<span>${unit}</span></div><p>${detail}</p>
|
||||
</a>`;
|
||||
const stockRow = (label, value, total, tone) => `
|
||||
<div class="dashboard-stock-row"><div><span><i class="dashboard-dot dashboard-fill-${tone}"></i>${label}</span><strong>${number(value)} <small>mã</small></strong></div>
|
||||
<div class="dashboard-track" aria-hidden="true"><span class="dashboard-fill-${tone}" style="width:${total ? Math.round(value / total * 100) : 0}%"></span></div></div>`;
|
||||
const requestButton = (kind, total, label) => `<button type="button" class="dashboard-attention-row" data-dashboard-action="${kind}">
|
||||
<span class="dashboard-icon dashboard-tone-amber">${icon('pending_actions')}</span><span><strong>${label}</strong><small>${this.canCurrentUserManageAssets() ? 'Xem và xử lý yêu cầu' : 'Theo dõi yêu cầu của bạn'}</small></span><b>${number(total)}</b>${icon('chevron_right')}</button>`;
|
||||
const secondary = (key, href, symbol, label) => `<a href="${href}" class="dashboard-resource">${icon(symbol)}<span>${label}</span><strong>${count(key, length(key))}</strong>${icon('chevron_right')}</a>`;
|
||||
return `<div class="dashboard-page h-full w-full overflow-y-auto p-4 md:p-6">
|
||||
<div class="dashboard-shell">
|
||||
<div class="dashboard-header">
|
||||
<div><div class="dashboard-eyebrow">KHÔNG GIAN QUẢN LÝ</div><h1>Tổng quan hệ thống</h1><p>Theo dõi tài sản, vật tư tiêu hao và robot tại một nơi.</p></div>
|
||||
<div class="dashboard-actions"><span class="dashboard-updated" role="status">${this.dashboardUpdatedAt ? `Lần tải gần nhất: ${safe(this.formatDateTime(this.dashboardUpdatedAt))}` : 'Đang tổng hợp dữ liệu…'}</span>
|
||||
<button id="refreshDashboardBtn" type="button" class="dashboard-refresh" ${this.dashboardLoading ? 'disabled aria-busy="true"' : ''}>${icon('refresh')}${this.dashboardLoading ? 'Đang tải…' : 'Làm mới'}</button></div>
|
||||
</div>
|
||||
|
||||
<!-- Metric Grid -->
|
||||
<div class="dashboard-stats grid grid-cols-4 gap-4 shrink-0">
|
||||
<div class="bg-surface-container-lowest p-4 rounded-xl border border-outline-variant/15 flex flex-col">
|
||||
<span class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider mb-2">Applications</span>
|
||||
<div class="flex items-baseline justify-between">
|
||||
<span class="text-2xl font-black text-on-surface">${this.applications.length}</span>
|
||||
<span class="text-[10px] font-bold text-on-surface-variant">${this.applications.filter(a => (a.Status || a.status) === 'online').length} Active</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bg-surface-container-lowest p-4 rounded-xl border border-outline-variant/15 flex flex-col">
|
||||
<span class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider mb-2">Total Accounts</span>
|
||||
<div class="flex items-baseline justify-between">
|
||||
<span class="text-2xl font-black text-on-surface">${this.accounts.length}</span>
|
||||
<span class="text-[10px] font-bold text-on-surface-variant/40">Managed</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bg-surface-container-lowest p-4 rounded-xl border border-outline-variant/15 flex flex-col">
|
||||
<span class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider mb-2">Last Updated</span>
|
||||
<div class="flex items-baseline justify-between">
|
||||
<span class="text-sm font-black text-on-surface">${APP_DATE_FORMATTER.format(new Date())}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bg-primary-container/10 p-4 rounded-xl border border-primary/20 flex flex-col">
|
||||
<span class="text-[10px] font-bold text-primary uppercase tracking-wider mb-2">Status</span>
|
||||
<div class="flex items-baseline justify-between">
|
||||
<span class="text-lg font-black text-primary">Operational</span>
|
||||
<span class="material-symbols-outlined text-primary text-sm">check_circle</span>
|
||||
</div>
|
||||
</div>
|
||||
${failedSources.length ? `<div class="dashboard-warning" role="alert">${icon('info')}<span>Chưa tải được: <strong>${safe(failedSources.join(', '))}</strong>. Số liệu liên quan tạm ẩn. Bấm Làm mới để thử lại.</span></div>` : ''}
|
||||
<div class="dashboard-metrics">
|
||||
${card('#assets', 'inventory_2', 'blue', 'Tài sản', count('assets', summary.assets.length), 'mã tài sản', errors.assets ? 'Chưa tải được dữ liệu' : `${number(summary.assetStock.inStock + summary.assetStock.inUse)} mã còn trong kho`)}
|
||||
${card('#consumables', 'category', 'green', 'Vật tư tiêu hao', count('consumables', summary.consumables.length), 'mã vật tư', errors.consumables ? 'Chưa tải được dữ liệu' : `${number(summary.outOfStock.length)} mã hết tồn cần theo dõi`)}
|
||||
${card('#robots', 'smart_toy', 'purple', 'Robot', count('robots', summary.robots.length), 'robot', errors.robots ? 'Chưa tải được dữ liệu' : `${count('robotTypes', length('robotTypes'))} thể loại robot`)}
|
||||
${card('#asset-borrows', 'assignment', 'amber', 'Yêu cầu chờ duyệt', requestsFailed ? '—' : number(pendingCount), 'yêu cầu', requestsFailed ? 'Dữ liệu yêu cầu chưa đầy đủ' : `${number(summary.pendingAssets.length)} tài sản · ${number(summary.pendingConsumables.length)} vật tư`)}
|
||||
</div>
|
||||
|
||||
<!-- Recent Activity -->
|
||||
<div class="bg-surface-container-lowest rounded-xl p-5 border border-outline-variant/15 flex flex-col flex-1 min-h-0">
|
||||
<div class="flex items-center justify-between mb-4 shrink-0">
|
||||
<h3 class="text-sm font-bold text-on-surface flex items-center gap-2">
|
||||
<span class="material-symbols-outlined text-primary text-base">history</span>
|
||||
Recent Accounts
|
||||
</h3>
|
||||
<div class="dashboard-layout">
|
||||
<div class="dashboard-main-column">
|
||||
<div class="dashboard-stock-grid">
|
||||
<section class="dashboard-panel" aria-labelledby="dashboardAssetTitle">
|
||||
<div class="dashboard-panel-heading"><h2 id="dashboardAssetTitle">Tình hình tài sản</h2><a href="#assets" aria-label="Xem tất cả tài sản">Chi tiết ${icon('arrow_forward')}</a></div>
|
||||
<p class="dashboard-panel-note">Phân bổ theo mã tài sản trong danh mục hiện tại</p>
|
||||
${errors.assets ? empty('Chưa tải được dữ liệu tài sản.') : summary.assets.length ? `
|
||||
${stockRow('Sẵn trong kho', summary.assetStock.inStock, summary.assets.length, 'blue')}
|
||||
${stockRow('Đang sử dụng một phần', summary.assetStock.inUse, summary.assets.length, 'purple')}
|
||||
${stockRow('Đã xuất hết / hết tồn', summary.assetStock.exported, summary.assets.length, 'amber')}` : empty('Chưa có tài sản trong danh mục.')}
|
||||
</section>
|
||||
<section class="dashboard-panel" aria-labelledby="dashboardConsumableTitle">
|
||||
<div class="dashboard-panel-heading"><h2 id="dashboardConsumableTitle">Tồn kho vật tư</h2><a href="#consumables" aria-label="Xem tất cả vật tư tiêu hao">Chi tiết ${icon('arrow_forward')}</a></div>
|
||||
<p class="dashboard-panel-note">Theo dõi số mã vật tư còn tồn và hết tồn</p>
|
||||
${errors.consumables ? empty('Chưa tải được dữ liệu vật tư.') : summary.consumables.length ? `
|
||||
${stockRow('Còn tồn trong kho', summary.consumables.length - summary.outOfStock.length, summary.consumables.length, 'green')}
|
||||
${stockRow('Đã hết tồn', summary.outOfStock.length, summary.consumables.length, 'rose')}
|
||||
<a class="dashboard-inline-link" href="#consumable-exports">${icon('swap_horiz')}Xem mượn / trả vật tư ${icon('arrow_forward')}</a>` : empty('Chưa có vật tư tiêu hao.')}
|
||||
</section>
|
||||
</div>
|
||||
<section class="dashboard-panel dashboard-recent" aria-labelledby="dashboardRecentTitle">
|
||||
<div class="dashboard-panel-heading"><h2 id="dashboardRecentTitle">${icon('history')}Cập nhật gần đây</h2><span class="dashboard-panel-note">Tài sản · Vật tư · Robot · Tài liệu</span></div>
|
||||
${summary.recent.length ? `<div class="dashboard-recent-list">${summary.recent.map(item => `<a class="dashboard-recent-row" href="${item.href}">
|
||||
<span class="dashboard-icon dashboard-tone-${item.tone}">${icon(item.icon)}</span><span class="dashboard-recent-name"><strong>${safe(item.name || 'Chưa đặt tên')}</strong><small>${safe(item.code || item.source)}</small></span>
|
||||
<span class="dashboard-tag dashboard-tone-${item.tone}">${item.source}</span><time datetime="${safe(new Date(item.date).toISOString())}">${safe(this.formatDateTime(item.date))}</time>${icon('chevron_right')}
|
||||
</a>`).join('')}</div>` : empty(failedSources.length ? 'Chưa có dữ liệu cập nhật từ các phân hệ đã tải.' : 'Các mục có ngày tạo hoặc cập nhật sẽ hiển thị tại đây.')}
|
||||
</section>
|
||||
<section class="dashboard-resources" aria-label="Các phân hệ khác">
|
||||
${secondary('documents', '#documents', 'folder_open', 'Tài liệu')}
|
||||
${secondary('assetProjects', '#asset-projects', 'work_outline', 'Dự án')}
|
||||
${secondary('assetDepartments', '#asset-departments', 'corporate_fare', 'Phòng ban')}
|
||||
${secondary('accounts', '#accounts', 'manage_accounts', 'Tài khoản')}
|
||||
</section>
|
||||
</div>
|
||||
<div class="dashboard-side-column">
|
||||
<section class="dashboard-panel" aria-labelledby="dashboardAttentionTitle">
|
||||
<div class="dashboard-panel-heading"><h2 id="dashboardAttentionTitle">${icon('notifications_active')}Cần chú ý</h2><span class="dashboard-tag dashboard-tone-amber">${requestsFailed || errors.consumables ? 'Chưa đủ dữ liệu' : `${number(pendingCount + summary.outOfStock.length)} mục`}</span></div>
|
||||
${requestsFailed ? '<p class="dashboard-panel-note">Chưa tải đủ yêu cầu tài sản / vật tư.</p>' : ''}
|
||||
${summary.pendingAssets.length ? requestButton('asset-requests', summary.pendingAssets.length, 'Yêu cầu tài sản chờ duyệt') : ''}
|
||||
${summary.pendingConsumables.length ? requestButton('consumable-requests', summary.pendingConsumables.length, 'Yêu cầu vật tư chờ duyệt') : ''}
|
||||
${summary.outOfStock.length ? `<a href="#consumables" class="dashboard-attention-row"><span class="dashboard-icon dashboard-tone-rose">${icon('inventory')}</span><span><strong>Vật tư đã hết tồn</strong><small>Cần kiểm tra kế hoạch bổ sung</small></span><b>${number(summary.outOfStock.length)}</b>${icon('chevron_right')}</a>
|
||||
<div class="dashboard-shortage-list">${summary.outOfStock.slice(0, 3).map(item => `<a href="#consumables"><span>${safe(item.ConsumableName || item.ConsumableCode || 'Vật tư')}</span><small>Hết tồn</small></a>`).join('')}${summary.outOfStock.length > 3 ? `<a href="#consumables" class="dashboard-inline-link">Xem thêm ${number(summary.outOfStock.length - 3)} mã vật tư</a>` : ''}</div>` : ''}
|
||||
${!pendingCount && !summary.outOfStock.length ? empty(requestsFailed || errors.consumables ? 'Bấm Làm mới để tải lại các mục cần chú ý.' : 'Không có yêu cầu chờ duyệt hoặc vật tư hết tồn.') : ''}
|
||||
</section>
|
||||
<section class="dashboard-panel" aria-labelledby="dashboardRobotTitle">
|
||||
<div class="dashboard-panel-heading"><h2 id="dashboardRobotTitle">${icon('smart_toy')}Robot gần đây</h2><a href="#robots">Tất cả ${icon('arrow_forward')}</a></div>
|
||||
${errors.robots ? empty('Chưa tải được dữ liệu robot.') : summary.robots.length ? summary.robots.slice(0, 3).map(robot => `<a href="#robots" class="dashboard-robot-row">
|
||||
${this.getRobotAvatarHtml(robot)}<span><strong>${safe(robot.Name || 'Robot')}</strong><small>${safe([robot.Model, robot.Type].filter(Boolean).join(' · ') || 'Chưa có thông tin model')}</small><small>${number(this.parseNonNegativeInteger(robot.DocumentCount, 0))} tài liệu đính kèm</small></span>${icon('chevron_right')}</a>`).join('') : empty('Chưa có robot. Quản lý robot tại mục Robot.')}
|
||||
<a href="#robot-bom" class="dashboard-inline-link">${icon('account_tree')}Tra cứu BOM robot ${icon('arrow_forward')}</a>
|
||||
</section>
|
||||
</div>
|
||||
${this.accounts.length > 0 ? `
|
||||
<div class="flex-1 overflow-y-auto space-y-2">
|
||||
${this.accounts.slice(-5).reverse().map(acc => {
|
||||
const username = acc.AccountUsername || acc.username || '-';
|
||||
const service = acc.AppName || acc.service || '-';
|
||||
const owner = acc.Email || acc.owner || this.currentUser?.Username || this.currentUser?.username || '-';
|
||||
return `
|
||||
<div class="flex gap-3 p-3 bg-surface-container-low/50 rounded-lg border-l-2 border-primary/50">
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="text-[11px] font-bold text-on-surface truncate">${username}</p>
|
||||
<p class="text-[9px] text-on-surface-variant">${service} ? ${owner}</p>
|
||||
</div>
|
||||
</div>
|
||||
`;}).join('')}
|
||||
</div>
|
||||
` : `
|
||||
<div class="flex-1 flex items-center justify-center text-center">
|
||||
<p class="text-sm text-on-surface-variant">No accounts yet. <a href="#accounts" class="text-primary font-bold">Create one</a></p>
|
||||
</div>
|
||||
`}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
</div>`;
|
||||
}
|
||||
|
||||
getAccountsContent() {
|
||||
|
||||
@@ -251,6 +251,8 @@
|
||||
|
||||
</style>
|
||||
<link rel="stylesheet" href="../css/responsive.css?v=20261019-3" />
|
||||
<link rel="stylesheet" href="../css/dashboard.css?v=20261103-1" />
|
||||
<link rel="stylesheet" href="../css/announcements.css?v=20261103-2" />
|
||||
</head>
|
||||
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
|
||||
<!-- SideNavBar -->
|
||||
@@ -286,11 +288,6 @@
|
||||
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
|
||||
<span class="sidebar-text">Tài khoản</span>
|
||||
</a></li>
|
||||
<li><a href="#notifications" data-nav="notifications" class="sidebar-link">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">notifications</span>
|
||||
<span class="sidebar-text">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></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li data-nav-group="assets">
|
||||
@@ -364,11 +361,22 @@
|
||||
<span class="material-symbols-outlined" aria-hidden="true">folder_open</span>
|
||||
<span class="sidebar-text">Tài liệu</span>
|
||||
</a></li>
|
||||
<li id="usersSection" class="sidebar-admin" style="display: none;">
|
||||
<a id="usersNav" href="#users" data-nav="users" class="sidebar-link" style="display: none;">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">people</span>
|
||||
<span class="sidebar-text">Người dùng</span>
|
||||
</a>
|
||||
<li id="usersSection" class="sidebar-admin" data-nav-group="administration" style="display: none;">
|
||||
<button id="sidebarAdministrationToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="administration" aria-expanded="false" aria-controls="sidebarAdministration">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">admin_panel_settings</span>
|
||||
<span class="sidebar-text">Quản trị viên</span>
|
||||
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
|
||||
</button>
|
||||
<ul id="sidebarAdministration" class="sidebar-children" aria-labelledby="sidebarAdministrationToggle" hidden>
|
||||
<li><a id="usersNav" href="#users" data-nav="users" class="sidebar-link" style="display: none;">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">people</span>
|
||||
<span class="sidebar-text">Quản lý người dùng</span>
|
||||
</a></li>
|
||||
<li><a href="#notification-management" data-nav="notification-management" class="sidebar-link">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>
|
||||
<span class="sidebar-text">Đăng thông báo</span>
|
||||
</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
@@ -437,6 +445,6 @@
|
||||
|
||||
<script src="../js/document-formats.js?v=20261019-1"></script>
|
||||
<script src="../js/robot-bom.js?v=20261102-5"></script>
|
||||
<script src="../js/app.js?v=20261102-2"></script>
|
||||
<script src="../js/app.js?v=20261103-5"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user