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