update dasboard ,noti

This commit is contained in:
2026-11-04 09:54:17 +07:00
parent ea6768f90d
commit 63866b14a1
10 changed files with 1169 additions and 136 deletions

86
backend/announcements.js Normal file
View File

@@ -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 };

View File

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

131
backend/dashboard.test.js Normal file
View File

@@ -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, /4<span>mã tài sản/);
assert.match(html, /3<span>mã 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: '<img src=x onerror=alert(1)>', 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, /&lt;img src=x onerror=alert\(1\)&gt;/);
assert.doesNotMatch(html, /<img src=x/);
assert.match(html, /03\/11\/2026/);
assert.doesNotMatch(html, /Invalid Date|NaN/);
});
test('empty data and failed modules have distinct states and a failed module does not expose stale counts', () => {
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, /—<span>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);
});

View File

@@ -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('<!DOCTYPE html><html>Cannot GET /api/notifications/manage</html>', { 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|<!DOCTYPE|Cannot GET/);
return true;
});
}
});
test('proxy errors and invalid JSON have readable errors; JSON business errors keep their original message', async () => {
for (const [response, expected] of [
[new Response('<html>Bad Gateway</html>', { 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('<html>Not found</html>', { 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/);
});

View File

@@ -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) {

View File

@@ -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')

View 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
View 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; }
}

View File

@@ -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() {

View File

@@ -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>