update dasboard ,noti
This commit is contained in:
86
backend/announcements.js
Normal file
86
backend/announcements.js
Normal 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 };
|
||||
183
backend/announcements.test.js
Normal file
183
backend/announcements.test.js
Normal 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
131
backend/dashboard.test.js
Normal 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, /<img src=x onerror=alert\(1\)>/);
|
||||
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);
|
||||
});
|
||||
75
backend/notifications-ui.test.js
Normal file
75
backend/notifications-ui.test.js
Normal 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/);
|
||||
});
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user