notification

This commit is contained in:
2026-08-07 08:52:51 +07:00
parent 26094ee4d6
commit 302d262d33
7 changed files with 1112 additions and 8 deletions

View File

@@ -817,6 +817,58 @@ function normalizeAssetRequestStatus(value) {
return 'pending';
}
const NOTIFICATION_SOURCES = new Set(['admin', 'system']);
const NOTIFICATION_SEVERITIES = new Set(['info', 'success', 'warning', 'error']);
const NOTIFICATION_AUDIENCE_TYPES = new Set(['all', 'role', 'user']);
function normalizeNotificationSeverity(value) {
const normalized = String(value || '').trim().toLowerCase();
return NOTIFICATION_SEVERITIES.has(normalized) ? normalized : 'info';
}
function normalizeNotificationSource(value) {
const normalized = String(value || '').trim().toLowerCase();
return NOTIFICATION_SOURCES.has(normalized) ? normalized : 'system';
}
function normalizeNotificationActionUrl(value) {
const normalized = String(value || '').trim();
if (!normalized) return null;
if (normalized.length > 500) return null;
if (/[\\\r\n\u0000-\u001f]/.test(normalized)) return null;
if (normalized.startsWith('#')) return normalized;
if (normalized.startsWith('/') && !normalized.startsWith('//')) return normalized;
return null;
}
function normalizeNotificationAudiences(audiences = []) {
const normalized = [];
const seen = new Set();
for (const rawAudience of Array.isArray(audiences) ? audiences : []) {
const audienceType = String(rawAudience?.type || '').trim().toLowerCase();
let audienceValue = rawAudience?.value === null || rawAudience?.value === undefined
? null
: String(rawAudience.value).trim();
if (!NOTIFICATION_AUDIENCE_TYPES.has(audienceType)) continue;
if (audienceType === 'all') audienceValue = null;
if (audienceType === 'role') audienceValue = String(audienceValue || '').toLowerCase();
if (audienceType === 'user') {
const userId = Number(audienceValue);
audienceValue = Number.isInteger(userId) && userId > 0 ? String(userId) : '';
}
if (audienceType !== 'all' && !audienceValue) continue;
const key = `${audienceType}:${audienceValue || ''}`;
if (seen.has(key)) continue;
seen.add(key);
normalized.push({ type: audienceType, value: audienceValue });
}
return normalized;
}
function normalizeImportToken(value) {
return String(value || '')
.normalize('NFD')
@@ -2998,6 +3050,51 @@ async function createTables() {
FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
)
END`,
// In-app notifications. Audience and per-user read state stay separate so
// one broadcast does not need to be copied for every account.
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Notifications')
BEGIN
CREATE TABLE Notifications (
NotificationId BIGINT PRIMARY KEY IDENTITY(1,1),
Source NVARCHAR(20) NOT NULL,
Severity NVARCHAR(20) NOT NULL DEFAULT 'info',
Title NVARCHAR(160) NOT NULL,
Message NVARCHAR(2000) NOT NULL,
ActionUrl NVARCHAR(500) NULL,
CreatedBy INT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
ExpiresAt DATETIME NULL,
IsActive BIT NOT NULL DEFAULT 1,
CONSTRAINT CK_Notifications_Source CHECK (Source IN ('admin', 'system')),
CONSTRAINT CK_Notifications_Severity CHECK (Severity IN ('info', 'success', 'warning', 'error')),
FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
)
END`,
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationAudiences')
BEGIN
CREATE TABLE NotificationAudiences (
AudienceId BIGINT PRIMARY KEY IDENTITY(1,1),
NotificationId BIGINT NOT NULL,
AudienceType NVARCHAR(20) NOT NULL,
AudienceValue NVARCHAR(100) NULL,
CONSTRAINT CK_NotificationAudiences_Type CHECK (AudienceType IN ('all', 'role', 'user')),
FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE
)
END`,
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationReceipts')
BEGIN
CREATE TABLE NotificationReceipts (
NotificationId BIGINT NOT NULL,
UserId INT NOT NULL,
ReadAt 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')
@@ -3024,6 +3121,15 @@ async function createTables() {
}
}
// Ensure notification indexes exist for audience lookup and unread counts.
try {
await pool.request().query(`IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_Notifications_ActiveCreated') CREATE INDEX IX_Notifications_ActiveCreated ON Notifications(IsActive, CreatedDate DESC);`);
await pool.request().query(`IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_NotificationAudiences_Lookup') CREATE INDEX IX_NotificationAudiences_Lookup ON NotificationAudiences(NotificationId, AudienceType, AudienceValue);`);
await pool.request().query(`IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_NotificationReceipts_User') CREATE INDEX IX_NotificationReceipts_User ON NotificationReceipts(UserId, NotificationId);`);
} catch (err) {
console.error('Notification index creation error:', err.message);
}
// Ensure AssetInventory indexes exist for lookup/filter performance
try {
await pool.request().query(`IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetInventory_AssetCode') CREATE INDEX IX_AssetInventory_AssetCode ON AssetInventory(AssetCode);`);
@@ -4090,6 +4196,338 @@ function requireRoles(roles = [], message = 'Access denied') {
const requireAdmin = requireRoles(['admin'], 'Admin access required');
const requireAssetOrAdmin = requireRoles(['asset', 'admin'], 'Asset or Admin access required');
async function createNotification({
source = 'system',
severity = 'info',
title,
message,
actionUrl = null,
createdBy = null,
expiresAt = null,
audiences = [{ type: 'all', value: null }]
}) {
const normalizedTitle = String(title || '').trim();
const normalizedMessage = String(message || '').trim();
const normalizedActionUrl = normalizeNotificationActionUrl(actionUrl);
const normalizedAudiences = normalizeNotificationAudiences(audiences);
if (!normalizedTitle || normalizedTitle.length > 160) {
throw new Error('Notification title must contain 1-160 characters');
}
if (!normalizedMessage || normalizedMessage.length > 2000) {
throw new Error('Notification message must contain 1-2000 characters');
}
if (!normalizedAudiences.length) {
throw new Error('Notification must have at least one valid audience');
}
const parsedExpiry = expiresAt ? new Date(expiresAt) : null;
if (parsedExpiry && Number.isNaN(parsedExpiry.getTime())) {
throw new Error('Notification expiry is invalid');
}
const transaction = new sql.Transaction(pool);
await transaction.begin();
try {
const insertResult = await new sql.Request(transaction)
.input('source', sql.NVarChar(20), normalizeNotificationSource(source))
.input('severity', sql.NVarChar(20), normalizeNotificationSeverity(severity))
.input('title', sql.NVarChar(160), normalizedTitle)
.input('message', sql.NVarChar(2000), normalizedMessage)
.input('actionUrl', sql.NVarChar(500), normalizedActionUrl)
.input('createdBy', sql.Int, Number.isInteger(Number(createdBy)) && Number(createdBy) > 0 ? Number(createdBy) : null)
.input('expiresAt', sql.DateTime, parsedExpiry)
.query(`
INSERT INTO Notifications (
Source, Severity, Title, Message, ActionUrl, CreatedBy, ExpiresAt
)
OUTPUT INSERTED.NotificationId
VALUES (
@source, @severity, @title, @message, @actionUrl, @createdBy, @expiresAt
)
`);
const notificationId = Number(insertResult.recordset?.[0]?.NotificationId);
for (const audience of normalizedAudiences) {
await new sql.Request(transaction)
.input('notificationId', sql.BigInt, notificationId)
.input('audienceType', sql.NVarChar(20), audience.type)
.input('audienceValue', sql.NVarChar(100), audience.value)
.query(`
INSERT INTO NotificationAudiences (NotificationId, AudienceType, AudienceValue)
VALUES (@notificationId, @audienceType, @audienceValue)
`);
}
await transaction.commit();
return notificationId;
} catch (err) {
try {
await transaction.rollback();
} catch (_rollbackErr) {
// Preserve the original notification error.
}
throw err;
}
}
async function safeCreateSystemNotification(payload) {
try {
return await createNotification({ ...payload, source: 'system', createdBy: null });
} catch (err) {
// Notifications must never make the completed business transaction fail.
console.error('System notification creation error:', err.message);
return null;
}
}
// ==========================================
// API ROUTES - Notifications
// ==========================================
app.get('/api/notifications', async (req, res) => {
try {
const userId = getUserIdFromRequest(req);
const userRole = getRequesterRole(req);
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));
const offset = (page - 1) * pageSize;
const filter = String(req.query.filter || 'all').trim().toLowerCase();
const source = String(req.query.source || '').trim().toLowerCase();
const sourceFilter = NOTIFICATION_SOURCES.has(source) ? source : null;
const unreadOnly = filter === 'unread';
const result = await pool.request()
.input('userId', sql.Int, userId)
.input('userRole', sql.NVarChar(100), userRole)
.input('source', sql.NVarChar(20), sourceFilter)
.input('unreadOnly', sql.Bit, unreadOnly)
.input('offset', sql.Int, offset)
.input('pageSize', sql.Int, pageSize)
.query(`
SET NOCOUNT ON;
SELECT
n.NotificationId,
n.Source,
n.Severity,
n.Title,
n.Message,
n.ActionUrl,
n.CreatedBy,
n.CreatedDate,
n.ExpiresAt,
COALESCE(NULLIF(LTRIM(RTRIM(u.FullName)), ''), NULLIF(LTRIM(RTRIM(u.Username)), '')) AS CreatedByName,
CAST(CASE WHEN receipts.ReadAt IS NULL THEN 0 ELSE 1 END AS BIT) AS IsRead,
receipts.ReadAt
INTO #VisibleNotifications
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 n.IsActive = 1
AND (n.ExpiresAt IS NULL OR n.ExpiresAt > DATEADD(HOUR, 7, SYSUTCDATETIME()))
AND (@source IS NULL OR n.Source = @source)
AND EXISTS (
SELECT 1
FROM NotificationAudiences audiences
WHERE audiences.NotificationId = n.NotificationId
AND (
audiences.AudienceType = 'all'
OR (audiences.AudienceType = 'user' AND audiences.AudienceValue = CONVERT(NVARCHAR(100), @userId))
OR (audiences.AudienceType = 'role' AND LOWER(audiences.AudienceValue) = LOWER(@userRole))
)
);
SELECT COUNT_BIG(*) AS Total
FROM #VisibleNotifications
WHERE @unreadOnly = 0 OR IsRead = 0;
SELECT COUNT_BIG(*) AS UnreadCount
FROM #VisibleNotifications
WHERE IsRead = 0;
SELECT *
FROM #VisibleNotifications
WHERE @unreadOnly = 0 OR IsRead = 0
ORDER BY CreatedDate DESC, NotificationId DESC
OFFSET @offset ROWS FETCH NEXT @pageSize ROWS ONLY;
`);
const total = Number(result.recordsets?.[0]?.[0]?.Total) || 0;
const unreadCount = Number(result.recordsets?.[1]?.[0]?.UnreadCount) || 0;
res.json({
success: true,
data: result.recordsets?.[2] || [],
pagination: {
page,
pageSize,
total,
totalPages: Math.max(1, Math.ceil(total / pageSize))
},
unreadCount
});
} catch (err) {
sendInternalError(res, err);
}
});
app.post('/api/notifications', requireAdmin, async (req, res) => {
try {
const title = String(req.body?.title || '').trim();
const message = String(req.body?.message || '').trim();
const severity = normalizeNotificationSeverity(req.body?.severity);
const rawActionUrl = String(req.body?.actionUrl || '').trim();
const actionUrl = normalizeNotificationActionUrl(rawActionUrl);
const rawExpiry = String(req.body?.expiresAt || '').trim();
const expiresAt = rawExpiry ? new Date(rawExpiry) : null;
if (title.length < 3 || title.length > 160) {
return res.status(400).json({ success: false, message: 'Tiêu đề phải có từ 3 đến 160 ký tự' });
}
if (message.length < 3 || message.length > 2000) {
return res.status(400).json({ success: false, message: 'Nội dung phải có từ 3 đến 2000 ký tự' });
}
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())) {
return res.status(400).json({ success: false, message: 'Thời gian hết hạn phải ở tương lai' });
}
const notificationId = await createNotification({
source: 'admin',
severity,
title,
message,
actionUrl,
createdBy: getUserIdFromRequest(req),
expiresAt,
audiences: [{ type: 'all', value: null }]
});
res.status(201).json({
success: true,
message: 'Đã gửi thông báo tới mọi người',
data: { notificationId }
});
} catch (err) {
sendInternalError(res, err);
}
});
app.put('/api/notifications/read-all', async (req, res) => {
try {
const userId = getUserIdFromRequest(req);
const userRole = getRequesterRole(req);
await pool.request()
.input('userId', sql.Int, userId)
.input('userRole', sql.NVarChar(100), userRole)
.query(`
INSERT INTO NotificationReceipts (NotificationId, UserId, ReadAt)
SELECT n.NotificationId, @userId, DATEADD(HOUR, 7, SYSUTCDATETIME())
FROM Notifications n
WHERE n.IsActive = 1
AND (n.ExpiresAt IS NULL OR n.ExpiresAt > DATEADD(HOUR, 7, SYSUTCDATETIME()))
AND EXISTS (
SELECT 1 FROM NotificationAudiences audiences
WHERE audiences.NotificationId = n.NotificationId
AND (
audiences.AudienceType = 'all'
OR (audiences.AudienceType = 'user' AND audiences.AudienceValue = CONVERT(NVARCHAR(100), @userId))
OR (audiences.AudienceType = 'role' AND LOWER(audiences.AudienceValue) = LOWER(@userRole))
)
)
AND NOT EXISTS (
SELECT 1 FROM NotificationReceipts receipts
WHERE receipts.NotificationId = n.NotificationId AND receipts.UserId = @userId
);
`);
res.json({ success: true, message: 'Đã đánh dấu tất cả là đã đọc' });
} catch (err) {
sendInternalError(res, err);
}
});
app.put('/api/notifications/:id/read', async (req, res) => {
try {
const notificationId = Number(req.params.id);
const userId = getUserIdFromRequest(req);
const userRole = getRequesterRole(req);
if (!Number.isInteger(notificationId) || notificationId <= 0) {
return res.status(400).json({ success: false, message: 'Thông báo không hợp lệ' });
}
const result = await pool.request()
.input('notificationId', sql.BigInt, notificationId)
.input('userId', sql.Int, userId)
.input('userRole', sql.NVarChar(100), userRole)
.query(`
IF EXISTS (
SELECT 1
FROM Notifications n
WHERE n.NotificationId = @notificationId
AND n.IsActive = 1
AND (n.ExpiresAt IS NULL OR n.ExpiresAt > DATEADD(HOUR, 7, SYSUTCDATETIME()))
AND EXISTS (
SELECT 1 FROM NotificationAudiences audiences
WHERE audiences.NotificationId = n.NotificationId
AND (
audiences.AudienceType = 'all'
OR (audiences.AudienceType = 'user' AND audiences.AudienceValue = CONVERT(NVARCHAR(100), @userId))
OR (audiences.AudienceType = 'role' AND LOWER(audiences.AudienceValue) = LOWER(@userRole))
)
)
)
BEGIN
MERGE NotificationReceipts 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, ReadAt)
VALUES (source.NotificationId, source.UserId, DATEADD(HOUR, 7, SYSUTCDATETIME()));
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: 'Không tìm thấy thông báo' });
}
res.json({ success: true });
} catch (err) {
sendInternalError(res, err);
}
});
app.delete('/api/notifications/:id', requireAdmin, async (req, res) => {
try {
const notificationId = Number(req.params.id);
if (!Number.isInteger(notificationId) || notificationId <= 0) {
return res.status(400).json({ success: false, message: 'Thông báo không hợp lệ' });
}
const result = await pool.request()
.input('notificationId', sql.BigInt, notificationId)
.query(`
UPDATE Notifications
SET IsActive = 0
WHERE NotificationId = @notificationId AND Source = 'admin' AND IsActive = 1;
SELECT @@ROWCOUNT AS Affected;
`);
if (!Number(result.recordset?.[0]?.Affected)) {
return res.status(404).json({ success: false, message: 'Không tìm thấy thông báo quản trị đang hoạt động' });
}
res.json({ success: true, message: 'Đã thu hồi thông báo' });
} catch (err) {
sendInternalError(res, err);
}
});
// ==========================================
// API ROUTES - Roles
// ==========================================
@@ -5766,6 +6204,17 @@ app.post('/api/asset-borrows', async (req, res) => {
await transaction.commit();
await safeCreateSystemNotification({
severity: 'info',
title: `Đơn ${requestType === 'return' ? 'trả' : 'mượn'} tài sản mới`,
message: `${borrowerName} đã gửi đơn #${createdRequestId || '-'} cho ${asset.AssetCode || ''} - ${asset.AssetName || ''} (${borrowQuantity}${unit ? ` ${unit}` : ''}).`,
actionUrl: '#asset-borrows',
audiences: [
{ type: 'role', value: 'admin' },
{ type: 'role', value: 'asset' }
]
});
res.json({
success: true,
message: requestType === 'return'
@@ -5929,6 +6378,17 @@ app.post('/api/asset-borrows/:id/return', async (req, res) => {
await transaction.commit();
await safeCreateSystemNotification({
severity: 'info',
title: 'Đơn trả tài sản mới',
message: `${borrowerName || 'Người dùng'} đã gửi đơn trả #${returnRequestId} từ đơn mượn #${borrowId} (${returnQuantity}${targetRequest.Unit ? ` ${targetRequest.Unit}` : ''}).`,
actionUrl: '#asset-borrows',
audiences: [
{ type: 'role', value: 'admin' },
{ type: 'role', value: 'asset' }
]
});
return res.json({
success: true,
message: 'Da tao don tra tai san. Don dang cho xu ly.',
@@ -6302,6 +6762,19 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
await transaction.commit();
if (Number.isInteger(Number(targetRequest.CreatedBy)) && Number(targetRequest.CreatedBy) > 0) {
const requestType = normalizeAssetRequestType(targetRequest.RequestType);
const resultLabel = action === 'approved' ? 'được duyệt' : 'bị từ chối';
const reasonSuffix = action === 'rejected' && rejectReason ? ` Lý do: ${rejectReason}` : '';
await safeCreateSystemNotification({
severity: action === 'approved' ? 'success' : 'error',
title: `Đơn ${requestType === 'return' ? 'trả' : 'mượn'} tài sản ${resultLabel}`,
message: `Đơn #${borrowId} cho ${targetRequest.AssetCode || ''} - ${targetRequest.AssetName || ''} đã ${resultLabel}.${reasonSuffix}`,
actionUrl: requestType === 'borrow' && action === 'approved' ? '#my-borrowed-assets' : '#asset-borrows',
audiences: [{ type: 'user', value: Number(targetRequest.CreatedBy) }]
});
}
return res.json({
success: true,
message: action === 'approved'
@@ -6617,7 +7090,7 @@ app.post('/api/consumable-borrows', async (req, res) => {
const inventoryResult = await pool.request()
.input('consumableId', sql.Int, consumableId)
.query(`
SELECT TOP 1 ConsumableId, Unit, EndingBalance
SELECT TOP 1 ConsumableId, ConsumableCode, ConsumableName, Unit, EndingBalance
FROM ConsumableInventory
WHERE ConsumableId = @consumableId
`);
@@ -6671,10 +7144,22 @@ app.post('/api/consumable-borrows', async (req, res) => {
)
`);
const createdRequestId = Number(insertResult.recordset?.[0]?.BorrowRequestId) || null;
await safeCreateSystemNotification({
severity: 'info',
title: 'Đơn mượn vật tư mới',
message: `${borrowerName} đã gửi đơn #${createdRequestId || '-'} cho ${inventory.ConsumableCode || ''} - ${inventory.ConsumableName || ''} (${borrowQuantity}${inventory.Unit ? ` ${inventory.Unit}` : ''}).`,
actionUrl: '#consumable-exports',
audiences: [
{ type: 'role', value: 'admin' },
{ type: 'role', value: 'asset' }
]
});
res.json({
success: true,
message: 'Tạo đơn mượn vật tư thành công. Đơn đang chờ duyệt.',
data: { borrowRequestId: Number(insertResult.recordset?.[0]?.BorrowRequestId) || null }
data: { borrowRequestId: createdRequestId }
});
} catch (err) {
console.error('Create consumable borrow request error:', err.message);
@@ -6804,10 +7289,22 @@ app.post('/api/consumable-exports/:id/return-request', async (req, res) => {
)
`);
const createdRequestId = Number(insertResult.recordset?.[0]?.BorrowRequestId) || null;
await safeCreateSystemNotification({
severity: 'info',
title: 'Đơn trả vật tư mới',
message: `${exportRow.CurrentUserName || exportRow.RecipientName || 'Người dùng'} đã gửi đơn #${createdRequestId || '-'} trả ${exportRow.ConsumableCode || ''} - ${exportRow.ConsumableName || ''} (${returnQuantity}${exportRow.Unit ? ` ${exportRow.Unit}` : ''}).`,
actionUrl: '#consumable-exports',
audiences: [
{ type: 'role', value: 'admin' },
{ type: 'role', value: 'asset' }
]
});
res.json({
success: true,
message: 'Tạo đơn trả vật tư thành công. Đơn đang chờ Asset/Admin duyệt.',
data: { borrowRequestId: Number(insertResult.recordset?.[0]?.BorrowRequestId) || null }
data: { borrowRequestId: createdRequestId }
});
} catch (err) {
console.error('Create consumable return request error:', err.message);
@@ -7013,6 +7510,19 @@ app.post('/api/consumable-borrows/:id/process', requireAssetOrAdmin, async (req,
await transaction.commit();
if (Number.isInteger(Number(target.CreatedBy)) && Number(target.CreatedBy) > 0) {
const requestLabel = requestType === 'return' ? 'trả' : 'mượn';
const resultLabel = action === 'approved' ? 'được duyệt' : 'bị từ chối';
const reasonSuffix = action === 'rejected' && rejectReason ? ` Lý do: ${rejectReason}` : '';
await safeCreateSystemNotification({
severity: action === 'approved' ? 'success' : 'error',
title: `Đơn ${requestLabel} vật tư ${resultLabel}`,
message: `Đơn #${borrowRequestId} cho ${target.ConsumableCode || ''} - ${target.ConsumableName || ''} đã ${resultLabel}.${reasonSuffix}`,
actionUrl: '#consumable-exports',
audiences: [{ type: 'user', value: Number(target.CreatedBy) }]
});
}
res.json({
success: true,
message: action === 'approved'
@@ -9157,5 +9667,8 @@ module.exports = {
normalizeOptionalHttpUrl,
isPdfBuffer,
sanitizeDocumentFileName,
getDocumentContentDisposition
getDocumentContentDisposition,
normalizeNotificationActionUrl,
normalizeNotificationAudiences,
normalizeNotificationSeverity
};

View File

@@ -875,6 +875,53 @@ BEGIN
PRINT 'Table AssetDamageDisposalHistory created successfully.';
END
-- In-app notifications: one message, reusable audiences, per-user read state.
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Notifications')
BEGIN
CREATE TABLE Notifications (
NotificationId BIGINT PRIMARY KEY IDENTITY(1,1),
Source NVARCHAR(20) NOT NULL,
Severity NVARCHAR(20) NOT NULL CONSTRAINT DF_Notifications_Severity DEFAULT('info'),
Title NVARCHAR(160) NOT NULL,
Message NVARCHAR(2000) NOT NULL,
ActionUrl NVARCHAR(500) NULL,
CreatedBy INT NULL,
CreatedDate DATETIME NOT NULL CONSTRAINT DF_Notifications_CreatedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME())),
ExpiresAt DATETIME NULL,
IsActive BIT NOT NULL CONSTRAINT DF_Notifications_IsActive DEFAULT(1),
CONSTRAINT CK_Notifications_Source CHECK (Source IN ('admin', 'system')),
CONSTRAINT CK_Notifications_Severity CHECK (Severity IN ('info', 'success', 'warning', 'error')),
CONSTRAINT FK_Notifications_CreatedBy FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
);
PRINT 'Table Notifications created successfully.';
END
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationAudiences')
BEGIN
CREATE TABLE NotificationAudiences (
AudienceId BIGINT PRIMARY KEY IDENTITY(1,1),
NotificationId BIGINT NOT NULL,
AudienceType NVARCHAR(20) NOT NULL,
AudienceValue NVARCHAR(100) NULL,
CONSTRAINT CK_NotificationAudiences_Type CHECK (AudienceType IN ('all', 'role', 'user')),
CONSTRAINT FK_NotificationAudiences_Notification FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE
);
PRINT 'Table NotificationAudiences created successfully.';
END
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationReceipts')
BEGIN
CREATE TABLE NotificationReceipts (
NotificationId BIGINT NOT NULL,
UserId INT NOT NULL,
ReadAt DATETIME NOT NULL CONSTRAINT DF_NotificationReceipts_ReadAt DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT PK_NotificationReceipts PRIMARY KEY (NotificationId, UserId),
CONSTRAINT FK_NotificationReceipts_Notification FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE,
CONSTRAINT FK_NotificationReceipts_User FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE
);
PRINT 'Table NotificationReceipts created successfully.';
END
-- ===========================================
-- 12. CREATE AUDIT LOG TABLE
-- ===========================================
@@ -1072,6 +1119,21 @@ BEGIN
CREATE INDEX IX_AssetDamageDisposalHistory_ActionType ON AssetDamageDisposalHistory(ActionType);
END
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_Notifications_ActiveCreated')
BEGIN
CREATE INDEX IX_Notifications_ActiveCreated ON Notifications(IsActive, CreatedDate DESC);
END
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_NotificationAudiences_Lookup')
BEGIN
CREATE INDEX IX_NotificationAudiences_Lookup ON NotificationAudiences(NotificationId, AudienceType, AudienceValue);
END
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_NotificationReceipts_User')
BEGIN
CREATE INDEX IX_NotificationReceipts_User ON NotificationReceipts(UserId, NotificationId);
END
PRINT 'Indexes created successfully.';
-- ===========================================

File diff suppressed because one or more lines are too long

View File

@@ -24,6 +24,19 @@ textarea {
-webkit-overflow-scrolling: touch;
}
/* Keep every top-bar overlay above sticky table headers. Sticky cells can use
large local z-index values, so the content area needs its own lower context. */
#appMain > header {
position: relative;
z-index: 30;
overflow: visible;
}
#mainContent {
position: relative;
z-index: 0;
}
@media (max-width: 900px) {
body.app-shell,
#appMain,
@@ -58,6 +71,7 @@ textarea {
#mobileMenuBtn,
#profileBtn,
#logoutBtn,
#notificationsBellBtn,
#pendingAssetRequestsBtn {
min-width: 2.75rem;
min-height: 2.75rem;
@@ -436,11 +450,25 @@ textarea {
gap: 0.25rem;
}
#notificationPopover {
position: fixed;
top: calc(3.75rem + env(safe-area-inset-top));
right: 0.75rem;
left: 0.75rem;
width: auto;
max-height: calc(100dvh - 4.5rem - env(safe-area-inset-top));
}
#notificationPopoverList {
max-height: calc(100dvh - 12rem - env(safe-area-inset-top));
}
#pendingAssetRequestsBtn > span:not(.material-symbols-outlined):not(#pendingAssetRequestsBadge) {
display: none;
}
#pendingAssetRequestsBtn,
#notificationsBellBtn,
#profileBtn,
#logoutBtn,
#mobileMenuBtn {

View File

@@ -67,6 +67,16 @@ class AccountManager {
this.consumables = [];
this.documents = [];
this.roles = [];
this.notificationPreviewItems = [];
this.notificationItems = [];
this.notificationUnreadCount = 0;
this.notificationPage = 1;
this.notificationPageSize = 20;
this.notificationFilter = 'all';
this.notificationSourceFilter = '';
this.notificationPagination = { page: 1, pageSize: 20, total: 0, totalPages: 1 };
this.notificationLoading = false;
this.notificationPollTimer = undefined;
this.accountPage = 1;
this.accountPageSize = 9;
this.appPage = 1;
@@ -263,6 +273,7 @@ class AccountManager {
await this.fetchAssetDepartments();
await this.fetchAssetProjects();
await this.fetchDocuments();
await this.fetchNotificationPreview();
if (this.canCurrentUserManageAssets()) {
await this.fetchUsers();
@@ -279,6 +290,8 @@ class AccountManager {
}
this.setupEventListeners();
this.setupNotificationShell();
this.startNotificationPolling();
this.setupResponsiveShell();
this.loadModals(); // Load modals từ file riêng
// Single-page navigation based on hash
@@ -345,6 +358,10 @@ class AccountManager {
} else if (page === 'documents') {
mainContent.innerHTML = this.getDocumentsContent();
this.setupDocumentListeners();
} else if (page === 'notifications') {
mainContent.innerHTML = this.getNotificationsContent();
this.setupNotificationsPageListeners();
this.refreshNotificationsPage();
} else if (page === 'users') {
// Check if user is admin
if (!this.isCurrentUserAdmin()) {
@@ -507,6 +524,435 @@ class AccountManager {
}
}
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');
}
this.notificationPreviewItems = Array.isArray(data.data) ? data.data : [];
this.notificationUnreadCount = Number(data.unreadCount) || 0;
this.renderNotificationShell();
} catch (err) {
console.error('Fetch notification preview error:', err);
}
}
startNotificationPolling() {
if (this.notificationPollTimer) window.clearInterval(this.notificationPollTimer);
this.notificationPollTimer = window.setInterval(() => this.fetchNotificationPreview(), 60000);
}
setupNotificationShell() {
const shell = document.getElementById('notificationCenterShell');
const bell = document.getElementById('notificationsBellBtn');
const markAll = document.getElementById('notificationMarkAllBtn');
const viewAll = document.getElementById('notificationViewAllLink');
if (bell && !bell.dataset.boundClick) {
bell.addEventListener('click', async event => {
event.stopPropagation();
const popover = document.getElementById('notificationPopover');
const willOpen = popover?.classList.contains('hidden');
if (willOpen) {
await this.fetchNotificationPreview();
popover?.classList.remove('hidden');
bell.setAttribute('aria-expanded', 'true');
} else {
this.closeNotificationPopover();
}
});
bell.dataset.boundClick = 'true';
}
if (markAll && !markAll.dataset.boundClick) {
markAll.addEventListener('click', event => {
event.stopPropagation();
this.markAllNotificationsRead();
});
markAll.dataset.boundClick = 'true';
}
if (viewAll && !viewAll.dataset.boundClick) {
viewAll.addEventListener('click', () => this.closeNotificationPopover());
viewAll.dataset.boundClick = 'true';
}
if (shell && !shell.dataset.boundOutsideClick) {
document.addEventListener('click', event => {
if (!shell.contains(event.target)) this.closeNotificationPopover();
});
shell.dataset.boundOutsideClick = 'true';
}
this.renderNotificationShell();
}
closeNotificationPopover() {
document.getElementById('notificationPopover')?.classList.add('hidden');
document.getElementById('notificationsBellBtn')?.setAttribute('aria-expanded', 'false');
}
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' }
};
const source = String(item.Source || 'system').toLowerCase();
return {
...(severityMap[severity] || severityMap.info),
sourceLabel: source === 'admin' ? 'Quản trị viên' : 'Hệ thống',
sourceIcon: source === 'admin' ? 'campaign' : 'settings_suggest'
};
}
formatNotificationTime(value) {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return this.formatDateTime(value);
const diffMinutes = Math.round((date.getTime() - Date.now()) / 60000);
const absMinutes = Math.abs(diffMinutes);
if (absMinutes < 1) return 'Vừa xong';
if (absMinutes < 60) return `${absMinutes} phút trước`;
const hours = Math.round(absMinutes / 60);
if (hours < 24) return `${hours} giờ trước`;
const days = Math.round(hours / 24);
if (days < 7) return `${days} ngày trước`;
return this.formatDateTime(value);
}
renderNotificationShell() {
const unread = Math.max(0, Number(this.notificationUnreadCount) || 0);
const badges = [document.getElementById('notificationBadge'), document.getElementById('notificationNavBadge')];
badges.forEach(badge => {
if (!badge) return;
badge.textContent = unread > 99 ? '99+' : String(unread);
badge.classList.toggle('hidden', unread === 0);
});
const summary = document.getElementById('notificationPopoverSummary');
if (summary) summary.textContent = unread ? `${unread} thông báo chưa đọc` : 'Bạn đã xem hết thông báo';
const markAll = document.getElementById('notificationMarkAllBtn');
if (markAll) markAll.classList.toggle('invisible', unread === 0);
const list = document.getElementById('notificationPopoverList');
if (!list) return;
if (!this.notificationPreviewItems.length) {
list.innerHTML = `
<div class="flex flex-col items-center px-6 py-10 text-center">
<span class="material-symbols-outlined text-4xl text-slate-300">notifications_off</span>
<p class="mt-2 text-sm font-semibold text-slate-700 dark:text-slate-200">Chưa có thông báo</p>
<p class="mt-1 text-xs text-slate-500">Thông báo mới sẽ xuất hiện tại đây.</p>
</div>`;
return;
}
list.innerHTML = this.notificationPreviewItems.map(item => {
const meta = this.getNotificationMeta(item);
const isRead = item.IsRead === true || item.IsRead === 1;
return `
<button type="button" class="notification-preview-item w-full flex gap-3 px-4 py-3 text-left border-b border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors ${isRead ? '' : 'bg-blue-50/60 dark:bg-blue-950/20'}" data-notification-id="${item.NotificationId}">
<span class="shrink-0 inline-flex items-center justify-center w-9 h-9 rounded-xl ${meta.iconClass}">
<span class="material-symbols-outlined text-lg">${meta.icon}</span>
</span>
<span class="min-w-0 flex-1">
<span class="flex items-start gap-2">
<span class="flex-1 text-sm font-bold text-slate-900 dark:text-slate-50 line-clamp-1">${this.escapeHtml(item.Title)}</span>
${isRead ? '' : '<span class="mt-1.5 w-2 h-2 rounded-full bg-blue-600 shrink-0"></span>'}
</span>
<span class="mt-0.5 block text-xs text-slate-600 dark:text-slate-400 line-clamp-2">${this.escapeHtml(item.Message)}</span>
<span class="mt-1 block text-[10px] text-slate-400">${meta.sourceLabel} · ${this.formatNotificationTime(item.CreatedDate)}</span>
</span>
</button>`;
}).join('');
list.querySelectorAll('.notification-preview-item').forEach(button => {
button.addEventListener('click', () => this.openNotification(Number(button.dataset.notificationId)));
});
}
async fetchNotifications() {
const params = new URLSearchParams({
page: String(this.notificationPage),
pageSize: String(this.notificationPageSize),
filter: this.notificationFilter
});
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');
this.notificationItems = Array.isArray(data.data) ? data.data : [];
this.notificationPagination = data.pagination || this.notificationPagination;
}
async refreshNotificationsPage() {
this.notificationLoading = true;
this.renderNotificationsPage();
try {
await this.fetchNotifications();
} catch (err) {
console.error('Fetch notifications error:', err);
this.notifyFailure(err.message || 'Không thể tải thông báo');
} finally {
this.notificationLoading = false;
this.renderNotificationsPage();
}
}
renderNotificationsPage() {
if (this.currentPage !== 'notifications') return;
const mainContent = document.getElementById('mainContent');
if (!mainContent) return;
mainContent.innerHTML = this.getNotificationsContent();
this.setupNotificationsPageListeners();
}
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 author = String(item.Source).toLowerCase() === 'admin'
? (item.CreatedByName || 'Quản trị viên')
: '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' : ''}">
<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>
</span>
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-start justify-between gap-2">
<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>'}
</div>
<p class="mt-1 text-[11px] text-slate-500">${this.escapeHtml(author)} · ${this.formatNotificationTime(item.CreatedDate)}</p>
</div>
<span class="inline-flex items-center gap-1 rounded-full bg-slate-100 dark:bg-slate-800 px-2.5 py-1 text-[10px] font-bold text-slate-600 dark:text-slate-300">
<span class="material-symbols-outlined text-sm">${meta.sourceIcon}</span>${meta.sourceLabel}
</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>
<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>` : ''}
${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>
</div>
</article>`;
}
getNotificationsContent() {
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.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>`;
return `
<div class="notifications-page h-full overflow-y-auto bg-slate-50/60 dark:bg-slate-950 p-4 md:p-6">
<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>
${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>` : ''}
</header>
<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>
<section class="mt-4 flex flex-col gap-3 rounded-2xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-3 sm:flex-row sm:items-center sm:justify-between">
<div class="flex flex-wrap gap-2">
<button type="button" data-notification-filter="all" class="notification-filter-btn rounded-lg px-3 py-2 text-xs font-bold ${this.notificationFilter === 'all' ? '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'}">Tất cả</button>
<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>
</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>
<div class="mt-4 space-y-3">${listHtml}</div>
${!this.notificationLoading && totalPages > 1 ? `<nav class="mt-5 flex items-center justify-between rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 px-4 py-3"><span class="text-xs text-slate-500">Trang ${currentPage}/${totalPages}</span><div class="flex gap-2"><button class="notification-page-btn rounded-lg border border-slate-200 dark:border-slate-700 px-3 py-1.5 text-xs font-bold disabled:opacity-40" data-page="${currentPage - 1}" ${currentPage <= 1 ? 'disabled' : ''}>Trước</button><button class="notification-page-btn rounded-lg border border-slate-200 dark:border-slate-700 px-3 py-1.5 text-xs font-bold disabled:opacity-40" data-page="${currentPage + 1}" ${currentPage >= totalPages ? 'disabled' : ''}>Sau</button></div></nav>` : ''}
</div>
</div>`;
}
setupNotificationsPageListeners() {
document.querySelectorAll('.notification-filter-btn').forEach(button => {
button.addEventListener('click', () => {
this.notificationFilter = button.dataset.notificationFilter || 'all';
this.notificationPage = 1;
this.refreshNotificationsPage();
});
});
const sourceFilter = document.getElementById('notificationSourceFilter');
if (sourceFilter) sourceFilter.addEventListener('change', () => {
this.notificationSourceFilter = sourceFilter.value;
this.notificationPage = 1;
this.refreshNotificationsPage();
});
document.querySelectorAll('.notification-page-btn').forEach(button => {
button.addEventListener('click', () => {
const page = Number(button.dataset.page);
if (page > 0) {
this.notificationPage = page;
this.refreshNotificationsPage();
}
});
});
document.querySelectorAll('.notification-read-btn').forEach(button => button.addEventListener('click', () => this.markNotificationRead(Number(button.dataset.notificationId))));
document.querySelectorAll('.notification-action-btn').forEach(button => button.addEventListener('click', () => this.openNotification(Number(button.dataset.notificationId))));
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());
}
findNotification(notificationId) {
return this.notificationItems.find(item => Number(item.NotificationId) === Number(notificationId))
|| this.notificationPreviewItems.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 => {
if (Number(entry.NotificationId) === Number(notificationId)) entry.IsRead = true;
});
this.notificationUnreadCount = Math.max(0, this.notificationUnreadCount - 1);
this.renderNotificationShell();
if (refreshPage) this.renderNotificationsPage();
return true;
} catch (err) {
this.notifyFailure(err.message || 'Không thể đánh dấu đã đọc');
return false;
}
}
async openNotification(notificationId) {
const item = this.findNotification(notificationId);
if (!item) return;
await this.markNotificationRead(notificationId, { refreshPage: true });
this.closeNotificationPopover();
const actionUrl = String(item.ActionUrl || '').trim();
if (actionUrl.startsWith('#')) window.location.hash = actionUrl;
else if (/^\/(?!\/)[^\\\r\n]*$/.test(actionUrl)) window.location.assign(actionUrl);
}
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');
this.notificationItems.forEach(item => { item.IsRead = true; });
this.notificationPreviewItems.forEach(item => { item.IsRead = true; });
this.notificationUnreadCount = 0;
this.renderNotificationShell();
if (this.notificationFilter === 'unread') await this.refreshNotificationsPage();
else this.renderNotificationsPage();
} catch (err) {
this.notifyFailure(err.message || 'Không thể đánh dấu tất cả đã đọc');
}
}
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;
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');
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');
}
}
openNotificationComposer() {
if (!this.isCurrentUserAdmin()) return;
document.getElementById('notificationComposerModal')?.remove();
const container = document.createElement('div');
container.id = 'notificationComposerModal';
container.className = 'fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/60 p-4 modal-backdrop open';
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>
<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 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 close = () => container.remove();
document.getElementById('closeNotificationComposerBtn')?.addEventListener('click', close);
document.getElementById('cancelNotificationComposerBtn')?.addEventListener('click', close);
container.addEventListener('click', event => { if (event.target === container) close(); });
const messageInput = document.getElementById('notificationMessageInput');
messageInput?.addEventListener('input', () => { document.getElementById('notificationMessageCounter').textContent = `${messageInput.value.length}/2000`; });
document.getElementById('notificationComposerForm')?.addEventListener('submit', event => this.submitNotification(event, close));
document.getElementById('notificationTitleInput')?.focus();
}
async submitNotification(event, closeComposer) {
event.preventDefault();
const expiryValue = document.getElementById('notificationExpiryInput')?.value || '';
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
};
const sendButton = document.getElementById('sendNotificationBtn');
if (sendButton) sendButton.disabled = true;
try {
const response = await fetch(`${this.apiBase}/notifications`, {
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;
await Promise.all([this.fetchNotificationPreview(), this.refreshNotificationsPage()]);
} catch (err) {
this.notifyFailure(err.message || 'Không thể gửi thông báo');
} finally {
if (sendButton?.isConnected) sendButton.disabled = false;
}
}
async fetchAccountSecret(accountId) {
const response = await fetch(`${this.apiBase}/accounts/${accountId}/secret`, { cache: 'no-store' });
const data = await response.json();
@@ -1746,6 +2192,7 @@ class AccountManager {
if (e.key === 'Escape') {
this.closeMobileNav();
this.closeModals();
this.closeNotificationPopover();
}
});
@@ -10390,6 +10837,7 @@ class AccountManager {
document.querySelectorAll('.modal-backdrop').forEach(modal => {
modal.classList.remove('open');
});
document.getElementById('notificationComposerModal')?.remove();
this.pendingConsumableRequestRejectId = undefined;
}

View File

@@ -268,7 +268,7 @@
}
</style>
<link rel="stylesheet" href="../css/responsive.css?v=20260717-2" />
<link rel="stylesheet" href="../css/responsive.css?v=20260807-1" />
</head>
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
<!-- SideNavBar -->
@@ -297,6 +297,11 @@
<span class="material-symbols-outlined">manage_accounts</span>
<span>Tài khoản</span>
</a>
<a href="#notifications" data-nav="notifications" class="relative flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">notifications</span>
<span>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>
</div>
</div>
@@ -376,6 +381,26 @@
</button>
</div>
<div class="topbar-actions flex items-center gap-4">
<div id="notificationCenterShell" class="relative">
<button id="notificationsBellBtn" type="button" class="relative inline-flex items-center justify-center w-10 h-10 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors" title="Thông báo" aria-label="Mở thông báo" aria-haspopup="true" aria-expanded="false">
<span class="material-symbols-outlined">notifications</span>
<span id="notificationBadge" class="hidden absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full bg-red-600 text-white text-[10px] font-extrabold leading-5 text-center ring-2 ring-slate-50 dark:ring-slate-950">0</span>
</button>
<div id="notificationPopover" class="hidden absolute right-0 top-12 z-50 w-[min(390px,calc(100vw-24px))] overflow-hidden rounded-2xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 shadow-2xl" role="dialog" aria-label="Thông báo gần đây">
<div class="flex items-center justify-between gap-3 px-4 py-3 border-b border-slate-100 dark:border-slate-800">
<div>
<h2 class="text-sm font-bold text-slate-900 dark:text-slate-50">Thông báo</h2>
<p id="notificationPopoverSummary" class="text-[11px] text-slate-500">Không có thông báo mới</p>
</div>
<button id="notificationMarkAllBtn" type="button" class="text-xs font-semibold text-primary hover:underline">Đánh dấu đã đọc</button>
</div>
<div id="notificationPopoverList" class="max-h-[420px] overflow-y-auto"></div>
<a href="#notifications" id="notificationViewAllLink" class="flex items-center justify-center gap-1 px-4 py-3 border-t border-slate-100 dark:border-slate-800 text-xs font-bold text-primary hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
Xem tất cả
<span class="material-symbols-outlined text-base">arrow_forward</span>
</a>
</div>
</div>
<button id="pendingAssetRequestsBtn" type="button" class="hidden relative flex items-center gap-2 px-3 py-2 rounded-lg border border-amber-200 bg-amber-50 hover:bg-amber-100 text-amber-800 transition-colors" title="Đơn chờ xử lý">
<span class="material-symbols-outlined text-base">notifications_active</span>
<span class="text-xs font-bold">Đơn chờ</span>
@@ -400,6 +425,6 @@
</div>
</main>
<script src="../js/app.js?v=20260806-4"></script>
<script src="../js/app.js?v=20260806-5"></script>
</body>
</html>

View File

@@ -12,7 +12,10 @@ const {
normalizeOptionalHttpUrl,
isPdfBuffer,
sanitizeDocumentFileName,
getDocumentContentDisposition
getDocumentContentDisposition,
normalizeNotificationActionUrl,
normalizeNotificationAudiences,
normalizeNotificationSeverity
} = require('../backend/server');
async function withTestServer(run) {
@@ -58,6 +61,31 @@ test('application URLs accept only HTTP and HTTPS protocols', () => {
assert.match(normalizeOptionalHttpUrl('https://example.com/path'), /^https:\/\/example\.com\/path/);
});
test('notification links stay inside the application', () => {
assert.equal(normalizeNotificationActionUrl('#asset-borrows'), '#asset-borrows');
assert.equal(normalizeNotificationActionUrl('/pages/index.html#notifications'), '/pages/index.html#notifications');
assert.equal(normalizeNotificationActionUrl('https://attacker.example'), null);
assert.equal(normalizeNotificationActionUrl('//attacker.example/path'), null);
assert.equal(normalizeNotificationActionUrl('/\\attacker.example/path'), null);
assert.equal(normalizeNotificationActionUrl('javascript:alert(1)'), null);
});
test('notification audiences are normalized and deduplicated', () => {
assert.deepEqual(normalizeNotificationAudiences([]), []);
assert.deepEqual(normalizeNotificationAudiences([{ type: 'all' }]), [{ type: 'all', value: null }]);
assert.deepEqual(normalizeNotificationAudiences([
{ type: 'role', value: 'Admin' },
{ type: 'role', value: 'admin' },
{ type: 'user', value: '5' },
{ type: 'user', value: 'invalid' }
]), [
{ type: 'role', value: 'admin' },
{ type: 'user', value: '5' }
]);
assert.equal(normalizeNotificationSeverity('WARNING'), 'warning');
assert.equal(normalizeNotificationSeverity('unknown'), 'info');
});
test('PDF uploads require a PDF header and end-of-file marker', () => {
assert.equal(isPdfBuffer(Buffer.from('%PDF-1.7\nbody\n%%EOF')), true);
assert.equal(isPdfBuffer(Buffer.from('%PDF-1.7\nbody without trailer')), false);