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