From 63866b14a14538e0cae8c95c952f30026b3b2735 Mon Sep 17 00:00:00 2001 From: DungTT Date: Wed, 4 Nov 2026 09:54:17 +0700 Subject: [PATCH] update dasboard ,noti --- backend/announcements.js | 86 +++++ backend/announcements.test.js | 183 ++++++++++ backend/dashboard.test.js | 131 +++++++ backend/notifications-ui.test.js | 75 ++++ backend/server.js | 33 +- database/setup.sql | 13 + public/css/announcements.css | 48 +++ public/css/dashboard.css | 139 ++++++++ public/js/app.js | 567 ++++++++++++++++++++++++------- public/pages/index.html | 30 +- 10 files changed, 1169 insertions(+), 136 deletions(-) create mode 100644 backend/announcements.js create mode 100644 backend/announcements.test.js create mode 100644 backend/dashboard.test.js create mode 100644 backend/notifications-ui.test.js create mode 100644 public/css/announcements.css create mode 100644 public/css/dashboard.css diff --git a/backend/announcements.js b/backend/announcements.js new file mode 100644 index 0000000..ce20e48 --- /dev/null +++ b/backend/announcements.js @@ -0,0 +1,86 @@ +const express = require('express'); + +// Every popup and dismissal is evaluated against the authenticated recipient. +const visibleAnnouncement = `n.Source = 'admin' AND n.IsActive = 1 + AND (n.ExpiresAt IS NULL OR n.ExpiresAt > DATEADD(HOUR, 7, SYSUTCDATETIME())) + AND EXISTS ( + SELECT 1 FROM NotificationAudiences a WHERE a.NotificationId = n.NotificationId + AND (a.AudienceType = 'all' + OR (a.AudienceType = 'user' AND a.AudienceValue = CONVERT(NVARCHAR(100), @userId)) + OR (a.AudienceType = 'role' AND LOWER(a.AudienceValue) = LOWER(@userRole))) + )`; + +function createAnnouncementRouter({ getPool, sql, requireManage, getUserId, getRole, sendInternalError }) { + const router = express.Router(); + const recipientRequest = req => getPool().request() + .input('userId', sql.Int, getUserId(req)) + .input('userRole', sql.NVarChar(100), getRole(req)); + + router.get('/announcements', async (req, res) => { + try { + const result = await recipientRequest(req).query(` + SELECT n.NotificationId, n.Source, n.Severity, n.Title, n.Message, n.ActionUrl, + n.CreatedDate, n.ExpiresAt, n.CreatedBy, + COALESCE(NULLIF(LTRIM(RTRIM(u.FullName)), ''), u.Username) AS CreatedByName, + CAST(CASE WHEN receipts.ReadAt IS NULL THEN 0 ELSE 1 END AS BIT) AS IsRead + FROM Notifications n + LEFT JOIN Users u ON u.UserId = n.CreatedBy + LEFT JOIN NotificationReceipts receipts ON receipts.NotificationId = n.NotificationId AND receipts.UserId = @userId + WHERE ${visibleAnnouncement} + AND NOT EXISTS (SELECT 1 FROM NotificationPopupDismissals d + WHERE d.NotificationId = n.NotificationId AND d.UserId = @userId) + ORDER BY n.CreatedDate DESC, n.NotificationId DESC; + `); + res.json({ success: true, data: result.recordset }); + } catch (error) { sendInternalError(res, error); } + }); + + router.put('/:id/dismiss', async (req, res) => { + const notificationId = Number(req.params.id); + if (!Number.isSafeInteger(notificationId) || notificationId <= 0) { + return res.status(400).json({ success: false, message: 'Thông báo không hợp lệ' }); + } + try { + const result = await recipientRequest(req).input('notificationId', sql.BigInt, notificationId).query(` + IF EXISTS (SELECT 1 FROM Notifications n WHERE n.NotificationId = @notificationId AND ${visibleAnnouncement}) + BEGIN + MERGE NotificationPopupDismissals WITH (HOLDLOCK) AS target + USING (SELECT @notificationId AS NotificationId, @userId AS UserId) AS source + ON target.NotificationId = source.NotificationId AND target.UserId = source.UserId + WHEN NOT MATCHED THEN INSERT (NotificationId, UserId) + VALUES (source.NotificationId, source.UserId); + SELECT CAST(1 AS BIT) AS Found; + END + ELSE SELECT CAST(0 AS BIT) AS Found; + `); + if (!result.recordset?.[0]?.Found) return res.status(404).json({ success: false, message: 'Thông báo đã kết thúc hoặc không dành cho bạn' }); + res.json({ success: true }); + } catch (error) { sendInternalError(res, error); } + }); + + router.get('/manage', requireManage, async (req, res) => { + const page = Math.max(1, Number.parseInt(req.query.page, 10) || 1); + const pageSize = Math.min(50, Math.max(1, Number.parseInt(req.query.pageSize, 10) || 20)); + try { + const result = await getPool().request() + .input('offset', sql.Int, (page - 1) * pageSize) + .input('pageSize', sql.Int, pageSize) + .query(` + SET NOCOUNT ON; + SELECT COUNT_BIG(*) AS Total FROM Notifications WHERE Source = 'admin'; + SELECT n.NotificationId, n.Source, n.Severity, n.Title, n.Message, n.ActionUrl, + n.CreatedBy, n.CreatedDate, n.ExpiresAt, n.IsActive, + COALESCE(NULLIF(LTRIM(RTRIM(u.FullName)), ''), u.Username) AS CreatedByName + FROM Notifications n LEFT JOIN Users u ON u.UserId = n.CreatedBy + WHERE n.Source = 'admin' + ORDER BY n.CreatedDate DESC, n.NotificationId DESC + OFFSET @offset ROWS FETCH NEXT @pageSize ROWS ONLY; + `); + const total = Number(result.recordsets?.[0]?.[0]?.Total) || 0; + res.json({ success: true, data: result.recordsets?.[1] || [], pagination: { page, pageSize, total, totalPages: Math.max(1, Math.ceil(total / pageSize)) } }); + } catch (error) { sendInternalError(res, error); } + }); + return router; +} + +module.exports = { createAnnouncementRouter }; diff --git a/backend/announcements.test.js b/backend/announcements.test.js new file mode 100644 index 0000000..27a8bb9 --- /dev/null +++ b/backend/announcements.test.js @@ -0,0 +1,183 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const { createRequire } = require('node:module'); +const express = require('express'); + +async function fixture(t) { + const notices = [], audiences = [], reads = new Set(), dismissals = new Set(), queries = []; + const users = { 1: 'admin', 2: 'user', 3: 'user', 4: 'asset' }; + const visible = (notice, inputs) => notice.IsActive && (!notice.ExpiresAt || +new Date(notice.ExpiresAt) > Date.now()) + && audiences.some(a => a.id === notice.NotificationId && (a.type === 'all' || a.type === 'user' && +a.value === inputs.userId || a.type === 'role' && a.value === inputs.userRole)); + class Request { + constructor() { this.inputs = {}; } + input(name, _type, value) { this.inputs[name] = value; return this; } + async query(query) { + const p = this.inputs; + queries.push({ query, inputs: p }); + if (query.includes('INSERT INTO Notifications')) { + const notice = { NotificationId: notices.length + 1, Source: p.source, Title: p.title, Message: p.message, + Severity: p.severity, ActionUrl: p.actionUrl, CreatedBy: p.createdBy, CreatedByName: 'Publisher', + ExpiresAt: p.expiresAt, CreatedDate: new Date(), IsActive: true }; + notices.push(notice); + return { recordset: [{ NotificationId: notice.NotificationId }] }; + } + if (query.includes('INSERT INTO NotificationAudiences')) { + audiences.push({ id: p.notificationId, type: p.audienceType, value: p.audienceValue }); + return { recordset: [] }; + } + if (query.includes('INTO #VisibleNotifications')) { + assert.match(query, /receipts\.UserId = @userId/); + assert.match(query, /AudienceType = 'user' AND audiences\.AudienceValue = CONVERT\(NVARCHAR\(100\), @userId\)/); + let rows = notices.filter(n => visible(n, p) && (!p.source || n.Source === p.source)) + .map(n => ({ ...n, IsRead: reads.has(`${n.NotificationId}:${p.userId}`) })); + const unread = rows.filter(n => !n.IsRead).length; + if (p.unreadOnly) rows = rows.filter(n => !n.IsRead); + return { recordsets: [[{ Total: rows.length }], [{ UnreadCount: unread }], rows.slice(p.offset, p.offset + p.pageSize)] }; + } + if (query.includes('MERGE NotificationPopupDismissals')) { + assert.match(query, /WITH \(HOLDLOCK\)/); + assert.match(query, /n\.Source = 'admin' AND n\.IsActive = 1/); + assert.match(query, /a\.AudienceValue = CONVERT\(NVARCHAR\(100\), @userId\)/); + const found = notices.some(n => n.NotificationId === p.notificationId && n.Source === 'admin' && visible(n, p)); + if (found) dismissals.add(`${p.notificationId}:${p.userId}`); + return { recordset: [{ Found: found }] }; + } + if (query.includes('FROM NotificationPopupDismissals d')) { + assert.match(query, /d\.UserId = @userId/); + assert.match(query, /n\.ExpiresAt > DATEADD/); + return { recordset: notices.filter(n => n.Source === 'admin' && visible(n, p) && !dismissals.has(`${n.NotificationId}:${p.userId}`)) + .map(n => ({ ...n, IsRead: reads.has(`${n.NotificationId}:${p.userId}`) })) }; + } + if (query.includes('COUNT_BIG(*) AS Total FROM Notifications')) { + const rows = notices.filter(n => n.Source === 'admin'); + return { recordsets: [[{ Total: rows.length }], rows.slice(p.offset, p.offset + p.pageSize)] }; + } + if (query.includes('MERGE NotificationReceipts')) { + const found = notices.some(n => n.NotificationId === p.notificationId && visible(n, p)); + if (found) reads.add(`${p.notificationId}:${p.userId}`); + return { recordset: [{ Found: found }] }; + } + if (query.includes('INSERT INTO NotificationReceipts')) { + notices.filter(n => visible(n, p)).forEach(n => reads.add(`${n.NotificationId}:${p.userId}`)); + return { recordset: [] }; + } + if (query.includes('UPDATE Notifications')) { + assert.match(query, /@isAdmin = 1 OR CreatedBy = @userId/); + const found = notices.find(n => n.NotificationId === p.notificationId && n.Source === 'admin' && n.IsActive && (p.isAdmin || n.CreatedBy === p.userId)); + if (found) found.IsActive = false; + return { recordset: [{ Affected: found ? 1 : 0 }] }; + } + if (query.includes('FROM AssetBorrowRequests br WITH')) return { recordset: [{ BorrowId: 11, AssetId: 17, RequestType: 'borrow', RequestStatus: 'pending', CreatedBy: 2, BorrowerName: 'User 2', AssetCode: 'TS-17', AssetName: 'PLC' }] }; + if (query.includes('UPDATE AssetBorrowRequests')) return { recordset: [] }; + throw new Error(`Unexpected SQL in test: ${query.slice(0, 80)}`); + } + } + class Transaction { async begin() {} async commit() {} async rollback() {} } + const filename = path.join(__dirname, 'server.js'); + const localRequire = createRequire(filename); + const sql = { ...localRequire('mssql'), Request, Transaction }; + const sandbox = { + require: name => name === 'mssql' ? sql : name === 'dotenv' ? { config() {} } : localRequire(name), + module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, console, + testPool: { request: () => new Request() }, + process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'announcement-tests-only-secret-more-than-32-characters' }, on() {} } + }; + vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}\npool=testPool; getUserDisplayNameById=async()=> 'Manager';`, sandbox, { filename }); + const review = express(); + review.use(express.json()); + review.use((req, _res, next) => { const id = Number(req.headers['x-test-user'] || 2); req.user = { UserId: id, Role: users[id] }; next(); }); + for (const layer of sandbox.module.exports.app.router.stack) { + if (layer.handle?.stack?.some(entry => entry.route?.path === '/announcements')) review.use('/api/notifications', layer.handle); + if (!layer.route || !(layer.route.path.startsWith('/api/notifications') || layer.route.path === '/api/asset-borrows/:id/process')) continue; + for (const method of Object.keys(layer.route.methods)) review[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle)); + } + const missingApi = sandbox.module.exports.app.router.stack.find(layer => !layer.route && layer.handle.toString().includes('API_NOT_FOUND')); + if (missingApi) review.use('/api', missingApi.handle); + const server = review.listen(0, '127.0.0.1'); + await new Promise(resolve => server.once('listening', resolve)); + t.after(() => new Promise(resolve => server.close(resolve))); + const call = async (route, user = 2, method = 'GET', body) => { + const response = await fetch(`http://127.0.0.1:${server.address().port}/api/${route}`, { + method, headers: { 'x-test-user': String(user), 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined + }); + return { status: response.status, ...(await response.json()) }; + }; + const publish = (user = 1, extra = {}) => call('notifications', user, 'POST', { + title: 'Lịch bảo trì', message: 'Hệ thống bảo trì vào cuối tuần.', expiresAt: new Date(Date.now() + 86400000).toISOString(), ...extra + }); + return { call, publish, notices, audiences, reads, dismissals, queries }; +} + +test('Admin and Asset can publish; viewers cannot publish or access management; expiry is required', async t => { + const f = await fixture(t); + assert.equal((await f.publish(1)).status, 201); + assert.equal((await f.publish(4)).status, 201); + assert.equal((await f.publish(2)).status, 403); + for (const expiresAt of [null, 'bad-date', '2020-01-01T00:00:00Z']) assert.equal((await f.publish(4, { expiresAt })).status, 400); + assert.equal((await f.call('notifications/manage', 2)).status, 403); + assert.equal((await f.call('notifications/manage', 4)).data.length, 2); + assert.equal(f.notices[1].CreatedBy, 4); +}); + +test('reading broadcasts does not suppress popups; dismissal persists per user and per announcement', async t => { + const f = await fixture(t); + await f.publish(); await f.publish(); + await f.call('notifications/read-all', 2, 'PUT'); + assert.equal((await f.call('notifications/announcements', 2)).data.length, 2); + assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT', { userId: 3 })).status, 200); + assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT')).status, 200); + assert.equal(f.dismissals.size, 1); + assert.deepEqual((await f.call('notifications/announcements', 2)).data.map(n => n.NotificationId), [2]); + assert.equal((await f.call('notifications/announcements', 3)).data.length, 2); + assert.equal((await f.call('notifications', 2)).data.length, 2, 'dismissed announcements remain in the personal inbox'); +}); + +test('expired or withdrawn announcements stop appearing and Asset may withdraw only their own posts', async t => { + const f = await fixture(t); + await f.publish(1); await f.publish(4); await f.publish(1); + f.notices[2].ExpiresAt = new Date(Date.now() - 1000); + assert.equal((await f.call('notifications/1', 4, 'DELETE')).status, 404); + assert.equal((await f.call('notifications/2', 4, 'DELETE')).status, 200); + assert.deepEqual((await f.call('notifications/announcements')).data.map(n => n.NotificationId), [1]); + assert.equal((await f.call('notifications/3/dismiss', 2, 'PUT')).status, 404); + assert.equal((await f.call('notifications/manage', 1)).data.length, 3); + assert.equal((await f.call('notifications/1', 1, 'DELETE')).status, 200); + assert.equal((await f.call('notifications/announcements')).data.length, 0); +}); + +test('real borrow decision handler notifies only the owner; other users cannot read, dismiss or see it in popups', async t => { + const f = await fixture(t); + const result = await f.call('asset-borrows/11/process', 4, 'POST', { action: 'rejected', rejectReason: 'Chưa đủ thiết bị' }); + assert.equal(result.status, 200); + assert.deepEqual(f.audiences, [{ id: 1, type: 'user', value: '2' }]); + assert.equal((await f.call('notifications', 2)).data.length, 1); + assert.equal((await f.call('notifications', 3)).data.length, 0); + assert.equal((await f.call('notifications/1/read', 3, 'PUT')).status, 404); + assert.equal((await f.call('notifications/1/read', 2, 'PUT')).status, 200); + assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT')).status, 404); + assert.equal((await f.call('notifications/announcements', 2)).data.length, 0); + assert.equal((await f.call('notifications', 3)).unreadCount, 0); +}); + +test('new notification APIs are protected by the production session middleware', async t => { + const { app } = require('./server'); + const server = app.listen(0, '127.0.0.1'); + await new Promise(resolve => server.once('listening', resolve)); + t.after(() => new Promise(resolve => server.close(resolve))); + const base = `http://127.0.0.1:${server.address().port}`; + for (const [route, method] of [['announcements', 'GET'], ['manage', 'GET'], ['1/dismiss', 'PUT']]) { + const response = await fetch(`${base}/api/notifications/${route}`, { method, headers: { 'x-user-id': '1', 'x-user-role': 'admin' } }); + assert.equal(response.status, 401); + } +}); + +test('unknown authenticated API paths return JSON instead of an HTML error page', async t => { + const f = await fixture(t); + const result = await f.call('notifications/missing-endpoint', 1); + assert.equal(result.status, 404); + assert.equal(result.code, 'API_NOT_FOUND'); + assert.equal(result.success, false); +}); diff --git a/backend/dashboard.test.js b/backend/dashboard.test.js new file mode 100644 index 0000000..7a27ffe --- /dev/null +++ b/backend/dashboard.test.js @@ -0,0 +1,131 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); + +const source = fs.readFileSync(require.resolve('../public/js/app.js'), 'utf8'); + +function fixture(fetch = async () => ({ ok: true, json: async () => ({ success: true, data: [] }) })) { + const context = vm.createContext({ + window: { fetch }, fetch, console, AbortSignal, + document: { addEventListener() {}, getElementById: () => null, querySelectorAll: () => [] } + }); + vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context); + const manager = context.manager; + Object.assign(manager, { + assets: [], consumables: [], robots: [], robotTypes: [], accounts: [], applications: [], documents: [], + assetBorrows: [], consumableBorrowRequests: [], assetProjects: [], assetDepartments: [], + currentUser: { Role: 'admin' }, currentPage: 'assets', apiBase: '/api', + dashboardSourceErrors: {}, dashboardLoading: false, dashboardUpdatedAt: null, + selectedAssetIds: new Set(), updatePendingAssetRequestsBadge() {}, updateConsumableBorrowRequestBadges() {} + }); + return manager; +} + +test('overview counts catalog codes, excludes archived assets and uses available stock calculations', () => { + const manager = fixture(); + manager.assets = [ + { AssetId: 1, Quantity: '20', ImportInPeriod: '5', EndingBalance: '25', ExportInPeriod: '0', Unit: 'cái' }, + { AssetId: 2, Quantity: 10, EndingBalance: 7, ExportInPeriod: 3, Unit: 'bộ' }, + { AssetId: 3, Quantity: 2, EndingBalance: 0, ExportInPeriod: 2 }, + // An inflated imported balance cannot make a fully allocated asset available. + { AssetId: 4, Quantity: 3, EndingBalance: 100, ExportInPeriod: 3 }, + { AssetId: 5, Quantity: 1000, IsArchived: 1 } + ]; + manager.consumables = [{ EndingBalance: '10' }, { EndingBalance: 0 }, { EndingBalance: '0' }]; + manager.assetBorrows = [{ RequestStatus: 'pending' }, { RequestStatus: 'approved' }, { RequestStatus: 'rejected' }]; + manager.consumableBorrowRequests = [{ RequestStatus: 'pending' }, { RequestStatus: 'approved' }]; + const summary = manager.getDashboardSummary(); + assert.equal(summary.assets.length, 4); + assert.deepEqual(JSON.parse(JSON.stringify(summary.assetStock)), { inStock: 1, inUse: 1, exported: 2 }); + assert.equal(summary.outOfStock.length, 2); + assert.equal(summary.pendingAssets.length + summary.pendingConsumables.length, 2); + const html = manager.renderDashboard(); + assert.match(html, /4mã tài sản/); + assert.match(html, /3mã vật tư/); + assert.doesNotMatch(html, /System Overview|Recent Accounts|Add Account/); +}); + +test('recent updates combine modules, sort by actual timestamps and escape user content', () => { + const manager = fixture(); + manager.assets = [{ AssetName: '', Quantity: 1, CreatedDate: '2026-11-01T01:00:00Z' }]; + manager.consumables = [{ ConsumableName: 'Vật tư', UpdatedDate: '2026-11-02T01:00:00Z' }]; + manager.robots = [{ Name: 'Robot mới', CreatedDate: '2026-11-03T01:00:00Z' }, { Name: 'Robot không có ngày' }]; + manager.documents = [{ Title: 'Tài liệu', UploadedDate: '2026-10-31T01:00:00Z' }, { Title: 'Ngày lỗi', UploadedDate: 'invalid' }]; + const originalRobots = [...manager.robots]; + const summary = manager.getDashboardSummary(); + assert.deepEqual(Array.from(summary.recent, row => row.source), ['Robot', 'Vật tư', 'Tài sản', 'Tài liệu']); + assert.equal(manager.robots[0], originalRobots[0]); + const html = manager.renderDashboard(); + assert.match(html, /<img src=x onerror=alert\(1\)>/); + assert.doesNotMatch(html, / { + const manager = fixture(); + const empty = manager.renderDashboard(); + assert.match(empty, /Chưa có tài sản trong danh mục/); + assert.match(empty, /Không có yêu cầu chờ duyệt hoặc vật tư hết tồn/); + manager.assets = [{ Quantity: 10, AssetName: 'Stale asset', CreatedDate: '2026-11-01' }]; + manager.dashboardSourceErrors = { assets: 'Tài sản', assetBorrows: 'Yêu cầu tài sản' }; + const html = manager.renderDashboard(); + assert.match(html, /role="alert"/); + assert.match(html, /—mã tài sản/); + assert.match(html, /Dữ liệu yêu cầu chưa đầy đủ/); + assert.doesNotMatch(html, /Stale asset|Không có yêu cầu chờ duyệt hoặc vật tư hết tồn/); + assert.equal(manager.assets.length, 1); +}); + +test('refresh uses existing API routes, tolerates one failed module and recovers on retry', async () => { + const requests = []; + let failRobots = true; + const manager = fixture(async (url, options) => { + requests.push({ url, options }); + if (url === '/api/robots' && failRobots) throw new Error('Offline'); + return { ok: true, json: async () => ({ success: true, data: url === '/api/assets' ? [{ AssetId: 10, Quantity: 5 }] : [] }) }; + }); + manager.robots = [{ Name: 'Stale robot' }]; + await manager.refreshDashboard(); + assert.equal(requests.length, 10); + assert.ok(requests.some(request => request.url === '/api/accounts/all')); + assert.ok(requests.some(request => request.url === '/api/robots/types')); + assert.ok(requests.every(request => request.options.cache === 'no-store' && request.options.signal)); + assert.equal(manager.assets[0].EndingBalance, 5); + assert.equal(manager.dashboardSourceErrors.robots, 'Robot'); + assert.equal(manager.getDashboardSummary().robots.length, 0); + assert.equal(manager.currentPage, 'assets', 'a completed refresh preserves navigation'); + assert.equal(manager.dashboardLoading, false); + assert.ok(manager.dashboardUpdatedAt); + failRobots = false; + await manager.refreshDashboard(); + assert.equal(Object.keys(manager.dashboardSourceErrors).length, 0); +}); + +test('refresh rejects unsuccessful HTTP responses and malformed data rather than treating them as empty', async () => { + const manager = fixture(async url => ({ + ok: url !== '/api/assets', + json: async () => url === '/api/consumables' ? { success: true, data: null } : { success: true, data: [] } + })); + await manager.refreshDashboard(); + assert.equal(manager.dashboardSourceErrors.assets, 'Tài sản'); + assert.equal(manager.dashboardSourceErrors.consumables, 'Vật tư tiêu hao'); +}); + +test('overlapping refreshes share the in-progress work instead of issuing a duplicate batch', async () => { + let release; + let requestCount = 0; + const gate = new Promise(resolve => { release = resolve; }); + const manager = fixture(async () => { + requestCount++; + await gate; + return { ok: true, json: async () => ({ success: true, data: [] }) }; + }); + const pending = manager.refreshDashboard(); + await manager.refreshDashboard(); + assert.equal(requestCount, 10); + release(); + await pending; + assert.equal(manager.dashboardLoading, false); +}); diff --git a/backend/notifications-ui.test.js b/backend/notifications-ui.test.js new file mode 100644 index 0000000..323f5f6 --- /dev/null +++ b/backend/notifications-ui.test.js @@ -0,0 +1,75 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const source = fs.readFileSync(require.resolve('../public/js/app.js'), 'utf8'); + +function fixture(fetch) { + const context = vm.createContext({ + window: { fetch }, fetch, console, URLSearchParams, + document: { addEventListener() {}, getElementById: () => null } + }); + vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context); + return Object.assign(context.manager, { + apiBase: '/api', currentPage: 'notification-management', currentUser: { Role: 'admin' }, + notificationItems: [], notificationPreviewItems: [], notificationPage: 1, notificationPageSize: 20, + notificationFilter: 'all', notificationSourceFilter: '', notificationUnreadCount: 0, + notificationPagination: { page: 1, total: 0, totalPages: 1 }, + renderNotificationsPage() {}, notifyFailure() {} + }); +} + +test('a missing API or HTML fallback produces an actionable message without a JSON parser error', async () => { + for (const status of [200, 404]) { + const manager = fixture(async () => new Response('Cannot GET /api/notifications/manage', { status, headers: { 'Content-Type': 'text/html' } })); + await assert.rejects(manager.fetchNotificationJson('/manage'), error => { + assert.match(error.message, /khởi động lại backend/); + assert.doesNotMatch(error.message, /Unexpected token| { + for (const [response, expected] of [ + [new Response('Bad Gateway', { status: 502, headers: { 'Content-Type': 'text/html' } }), /HTTP 502/], + [new Response('{broken', { headers: { 'Content-Type': 'application/json' } }), /không hợp lệ/], + [Response.json({ success: false, message: 'Thông báo đã kết thúc' }, { status: 404 }), /Thông báo đã kết thúc/], + [Response.json({ success: false, code: 'API_NOT_FOUND' }, { status: 404 }), /khởi động lại backend/] + ]) { + const manager = fixture(async () => response); + await assert.rejects(manager.fetchNotificationJson('/1/dismiss', { method: 'PUT' }), expected); + } +}); + +test('notification requests preserve JSON headers and never retry a write automatically', async () => { + const calls = []; + const manager = fixture(async (url, options) => { + calls.push({ url, options }); + return Response.json({ success: true }); + }); + await manager.fetchNotificationJson('', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"title":"Notice"}' }); + assert.equal(calls.length, 1); + assert.equal(calls[0].url, '/api/notifications'); + assert.equal(calls[0].options.headers.Accept, 'application/json'); + assert.equal(calls[0].options.headers['Content-Type'], 'application/json'); + assert.equal(calls[0].options.method, 'POST'); + assert.equal(calls[0].options.cache, 'no-store'); +}); + +test('a failed management load shows an error and retry control, then clears both after recovery', async () => { + let offline = true; + const manager = fixture(async () => offline + ? new Response('Not found', { status: 404, headers: { 'Content-Type': 'text/html' } }) + : Response.json({ success: true, data: [], pagination: { page: 1, total: 0, totalPages: 1 } })); + await manager.refreshNotificationsPage(); + assert.equal(manager.notificationLoading, false); + assert.match(manager.getNotificationsContent(), /role="alert"/); + assert.match(manager.getNotificationsContent(), /id="retryNotificationsBtn"/); + assert.doesNotMatch(manager.getNotificationsContent(), /Không có thông báo phù hợp/); + offline = false; + await manager.refreshNotificationsPage(); + assert.equal(manager.notificationLoadError, ''); + assert.doesNotMatch(manager.getNotificationsContent(), /retryNotificationsBtn/); + assert.match(manager.getNotificationsContent(), /Không có thông báo phù hợp/); +}); diff --git a/backend/server.js b/backend/server.js index bea2175..e39ac3f 100644 --- a/backend/server.js +++ b/backend/server.js @@ -18,6 +18,7 @@ const { buildExportRequestWorkbook } = require('./export-request-workbook'); const { ensureAssetExportDocumentSchema } = require('./asset-export-documents'); const { ensureRobotSchema, createRobotRouter } = require('./robots'); const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom'); +const { createAnnouncementRouter } = require('./announcements'); const { getDocumentFormat, isPdfBuffer, validateDocumentFile, normalizeUploadedFileName, sanitizeDocumentFileName, getDocumentContentDisposition, accept: documentAccept } = require('./document-files'); @@ -3071,6 +3072,18 @@ async function createTables() { ) END`, + `IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationPopupDismissals') + BEGIN + CREATE TABLE NotificationPopupDismissals ( + NotificationId BIGINT NOT NULL, + UserId INT NOT NULL, + DismissedAt DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())), + PRIMARY KEY (NotificationId, UserId), + FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE, + FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE + ) + END`, + // AuditLog Table `IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog') BEGIN @@ -4273,6 +4286,11 @@ async function safeCreateSystemNotification(payload) { // API ROUTES - Notifications // ========================================== +app.use('/api/notifications', createAnnouncementRouter({ + getPool: () => pool, sql, requireManage: requireAssetOrAdmin, + getUserId: getUserIdFromRequest, getRole: getRequesterRole, sendInternalError +})); + app.get('/api/notifications', async (req, res) => { try { const userId = getUserIdFromRequest(req); @@ -4360,7 +4378,7 @@ app.get('/api/notifications', async (req, res) => { } }); -app.post('/api/notifications', requireAdmin, async (req, res) => { +app.post('/api/notifications', requireAssetOrAdmin, async (req, res) => { try { const title = String(req.body?.title || '').trim(); const message = String(req.body?.message || '').trim(); @@ -4379,7 +4397,7 @@ app.post('/api/notifications', requireAdmin, async (req, res) => { if (rawActionUrl && !actionUrl) { return res.status(400).json({ success: false, message: 'Liên kết chỉ được dùng đường dẫn nội bộ bắt đầu bằng / hoặc #' }); } - if (expiresAt && (Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now())) { + if (!expiresAt || Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now()) { return res.status(400).json({ success: false, message: 'Thời gian hết hạn phải ở tương lai' }); } @@ -4490,7 +4508,7 @@ app.put('/api/notifications/:id/read', async (req, res) => { } }); -app.delete('/api/notifications/:id', requireAdmin, async (req, res) => { +app.delete('/api/notifications/:id', requireAssetOrAdmin, async (req, res) => { try { const notificationId = Number(req.params.id); if (!Number.isInteger(notificationId) || notificationId <= 0) { @@ -4499,10 +4517,13 @@ app.delete('/api/notifications/:id', requireAdmin, async (req, res) => { const result = await pool.request() .input('notificationId', sql.BigInt, notificationId) + .input('userId', sql.Int, getUserIdFromRequest(req)) + .input('isAdmin', sql.Bit, getRequesterRole(req) === 'admin') .query(` UPDATE Notifications SET IsActive = 0 - WHERE NotificationId = @notificationId AND Source = 'admin' AND IsActive = 1; + WHERE NotificationId = @notificationId AND Source = 'admin' AND IsActive = 1 + AND (@isAdmin = 1 OR CreatedBy = @userId); SELECT @@ROWCOUNT AS Affected; `); @@ -9721,6 +9742,10 @@ app.get('/api/database/info', requireAdmin, async (req, res) => { // Error Handling // ========================================== +app.use('/api', (req, res) => { + res.status(404).json({ success: false, code: 'API_NOT_FOUND', message: 'API không tồn tại. Vui lòng cập nhật backend rồi thử lại.' }); +}); + app.use((err, req, res, next) => { console.error('Unhandled request error:', err.message); if (err instanceof multer.MulterError) { diff --git a/database/setup.sql b/database/setup.sql index a7ad783..1431790 100644 --- a/database/setup.sql +++ b/database/setup.sql @@ -923,6 +923,19 @@ BEGIN END -- =========================================== +-- Popup dismissal is independent of the per-user read receipt. +IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationPopupDismissals') +BEGIN + CREATE TABLE NotificationPopupDismissals ( + NotificationId BIGINT NOT NULL, + UserId INT NOT NULL, + DismissedAt DATETIME NOT NULL DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME())), + PRIMARY KEY (NotificationId, UserId), + FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE, + FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE + ); +END + -- 12. CREATE AUDIT LOG TABLE -- =========================================== IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog') diff --git a/public/css/announcements.css b/public/css/announcements.css new file mode 100644 index 0000000..cadf71a --- /dev/null +++ b/public/css/announcements.css @@ -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; } +} diff --git a/public/css/dashboard.css b/public/css/dashboard.css new file mode 100644 index 0000000..811026f --- /dev/null +++ b/public/css/dashboard.css @@ -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; } +} diff --git a/public/js/app.js b/public/js/app.js index 249421a..c022961 100644 --- a/public/js/app.js +++ b/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 = `
+ +

THÔNG BÁO CHUNG

${this.escapeHtml(item.Title)}

+ +
+

${this.escapeHtml(item.CreatedByName || 'Admin / Asset')}${item.ExpiresAt ? ` · Kết thúc: ${this.escapeHtml(this.formatDateTime(item.ExpiresAt))}` : ''}

+

${this.escapeHtml(item.Message)}

+ +
+ `; + 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 ` -
+
${meta.icon} @@ -797,7 +966,7 @@ class AccountManager {

${this.escapeHtml(item.Title)}

- ${isRead ? '' : ''} + ${isRead || managing ? '' : ''}

${this.escapeHtml(author)} · ${this.formatNotificationTime(item.CreatedDate)}

@@ -806,9 +975,11 @@ class AccountManager {

${this.escapeHtml(item.Message)}

+ ${item.ExpiresAt ? `

Kết thúc: ${this.escapeHtml(this.formatDateTime(item.ExpiresAt))}

` : ''} + ${managing ? `

${!active ? 'Đã thu hồi' : expired ? 'Đã kết thúc' : 'Đang hiển thị popup'}

` : ''}
${item.ActionUrl ? `` : ''} - ${!isRead ? `` : ''} + ${!isRead && !managing ? `` : ''} ${canWithdraw ? `` : ''}
@@ -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 ? `
progress_activity

Đang tải thông báo...

` + : this.notificationLoadError + ? `` : this.notificationItems.length ? this.notificationItems.map(item => this.getNotificationCardHtml(item)).join('') : `
notifications_off

Không có thông báo phù hợp

Hãy thử thay đổi bộ lọc.

`; @@ -832,14 +1006,14 @@ class AccountManager {
-
notificationsTrung tâm thông báo
-

Thông tin cần bạn chú ý

-

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.

+
${managing ? 'campaign' : 'notifications'}${managing ? 'Quản trị viên' : 'Trung tâm thông báo'}
+

${managing ? 'Đăng thông báo' : 'Thông báo của bạn'}

+

${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.'}

- ${this.isCurrentUserAdmin() ? `` : ''} + ${managing ? `` : ''}
-
+ ${!managing ? `

Chưa đọc

${this.notificationUnreadCount}

Theo bộ lọc

${total}

@@ -850,12 +1024,12 @@ class AccountManager {
- + ` : `

${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.

`}
${listHtml}
@@ -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 = `
+
+

QUẢN LÝ THÔNG BÁO

Thu hồi thông báo?

+ +
+

Thông báo này sẽ ngừng hiển thị với tất cả người dùng.

+
${this.escapeHtml(item.Title || 'Thông báo')} + ${item.CreatedByName ? `

Đăng bởi ${this.escapeHtml(item.CreatedByName)}

` : ''}
+

Thông báo đã thu hồi vẫn được lưu trong danh sách quản trị.

+
+
+ + +
`; + 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 = ` `; 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 = 'Đ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 ` -
- -
-
-

System Overview

-

Account & Service Management

-
- + 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 => ``; + const empty = message => `
${icon('inbox')}

${message}

`; + const card = (href, symbol, tone, label, value, unit, detail) => ` + +
${icon(symbol)}${label}${icon('arrow_outward')}
+
${value}${unit}

${detail}

+
`; + const stockRow = (label, value, total, tone) => ` +
${label}${number(value)} mã
+
`; + const requestButton = (kind, total, label) => ``; + const secondary = (key, href, symbol, label) => `${icon(symbol)}${label}${count(key, length(key))}${icon('chevron_right')}`; + return `
+
+
+
KHÔNG GIAN QUẢN LÝ

Tổng quan hệ thống

Theo dõi tài sản, vật tư tiêu hao và robot tại một nơi.

+
${this.dashboardUpdatedAt ? `Lần tải gần nhất: ${safe(this.formatDateTime(this.dashboardUpdatedAt))}` : 'Đang tổng hợp dữ liệu…'} +
- - -
-
- Applications -
- ${this.applications.length} - ${this.applications.filter(a => (a.Status || a.status) === 'online').length} Active -
-
-
- Total Accounts -
- ${this.accounts.length} - Managed -
-
-
- Last Updated -
- ${APP_DATE_FORMATTER.format(new Date())} -
-
-
- Status -
- Operational - check_circle -
-
+ ${failedSources.length ? `` : ''} +
+ ${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ư`)}
- - -
-
-

- history - Recent Accounts -

+
+
+
+
+ +

Phân bổ theo mã tài sản trong danh mục hiện tại

+ ${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.')} +
+
+ +

Theo dõi số mã vật tư còn tồn và hết tồn

+ ${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')} + ${icon('swap_horiz')}Xem mượn / trả vật tư ${icon('arrow_forward')}` : empty('Chưa có vật tư tiêu hao.')} +
+
+
+

${icon('history')}Cập nhật gần đây

Tài sản · Vật tư · Robot · Tài liệu
+ ${summary.recent.length ? `` : 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.')} +
+
+ ${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')} +
+
+
+
+

${icon('notifications_active')}Cần chú ý

${requestsFailed || errors.consumables ? 'Chưa đủ dữ liệu' : `${number(pendingCount + summary.outOfStock.length)} mục`}
+ ${requestsFailed ? '

Chưa tải đủ yêu cầu tài sản / vật tư.

' : ''} + ${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 ? `${icon('inventory')}Vật tư đã hết tồnCần kiểm tra kế hoạch bổ sung${number(summary.outOfStock.length)}${icon('chevron_right')} +
${summary.outOfStock.slice(0, 3).map(item => `${safe(item.ConsumableName || item.ConsumableCode || 'Vật tư')}Hết tồn`).join('')}${summary.outOfStock.length > 3 ? `Xem thêm ${number(summary.outOfStock.length - 3)} mã vật tư` : ''}
` : ''} + ${!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.') : ''} +
+
+

${icon('smart_toy')}Robot gần đây

Tất cả ${icon('arrow_forward')}
+ ${errors.robots ? empty('Chưa tải được dữ liệu robot.') : summary.robots.length ? summary.robots.slice(0, 3).map(robot => ` + ${this.getRobotAvatarHtml(robot)}${safe(robot.Name || 'Robot')}${safe([robot.Model, robot.Type].filter(Boolean).join(' · ') || 'Chưa có thông tin model')}${number(this.parseNonNegativeInteger(robot.DocumentCount, 0))} tài liệu đính kèm${icon('chevron_right')}`).join('') : empty('Chưa có robot. Quản lý robot tại mục Robot.')} + ${icon('account_tree')}Tra cứu BOM robot ${icon('arrow_forward')} +
- ${this.accounts.length > 0 ? ` -
- ${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 ` -
-
-

${username}

-

${service} ? ${owner}

-
-
- `;}).join('')} -
- ` : ` -
-

No accounts yet. Create one

-
- `}
- `; +
`; } getAccountsContent() { diff --git a/public/pages/index.html b/public/pages/index.html index 49a11ab..f0e8e9e 100644 --- a/public/pages/index.html +++ b/public/pages/index.html @@ -251,6 +251,8 @@ + + @@ -286,11 +288,6 @@ Tài khoản -
  • - - Thông báo - -
  • @@ -364,11 +361,22 @@ Tài liệu
  • - @@ -437,6 +445,6 @@ - +