noti
This commit is contained in:
73
web-server/database/04_notifications.sql
Normal file
73
web-server/database/04_notifications.sql
Normal file
@@ -0,0 +1,73 @@
|
||||
USE [RobotInstaller];
|
||||
GO
|
||||
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
-- Additive/idempotent migration. Safe to run more than once.
|
||||
IF OBJECT_ID(N'dbo.Notifications', N'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.Notifications
|
||||
(
|
||||
Id UNIQUEIDENTIFIER NOT NULL
|
||||
CONSTRAINT PK_Notifications PRIMARY KEY CLUSTERED
|
||||
CONSTRAINT DF_Notifications_Id DEFAULT NEWSEQUENTIALID(),
|
||||
RecipientUserId UNIQUEIDENTIFIER NOT NULL,
|
||||
ActorUserId UNIQUEIDENTIFIER NULL,
|
||||
ActorName NVARCHAR(200) NULL,
|
||||
BroadcastId UNIQUEIDENTIFIER NULL,
|
||||
EventType NVARCHAR(100) NOT NULL,
|
||||
Severity NVARCHAR(20) NOT NULL
|
||||
CONSTRAINT DF_Notifications_Severity DEFAULT N'info',
|
||||
Title NVARCHAR(200) NOT NULL,
|
||||
Message NVARCHAR(1000) NOT NULL,
|
||||
EntityType NVARCHAR(50) NULL,
|
||||
EntityId NVARCHAR(100) NULL,
|
||||
ActionUrl NVARCHAR(1000) NULL,
|
||||
ReadAt DATETIME2(3) NULL,
|
||||
CreatedAt DATETIME2(3) NOT NULL
|
||||
CONSTRAINT DF_Notifications_CreatedAt DEFAULT SYSUTCDATETIME(),
|
||||
ExpiresAt DATETIME2(3) NULL,
|
||||
CONSTRAINT FK_Notifications_RecipientUser
|
||||
FOREIGN KEY (RecipientUserId) REFERENCES dbo.Users(Id) ON DELETE CASCADE,
|
||||
CONSTRAINT CK_Notifications_Severity
|
||||
CHECK (Severity IN (N'info', N'success', N'warning', N'error')),
|
||||
CONSTRAINT CK_Notifications_EventType_NotBlank
|
||||
CHECK (LEN(LTRIM(RTRIM(EventType))) > 0),
|
||||
CONSTRAINT CK_Notifications_Title_NotBlank
|
||||
CHECK (LEN(LTRIM(RTRIM(Title))) > 0),
|
||||
CONSTRAINT CK_Notifications_Message_NotBlank
|
||||
CHECK (LEN(LTRIM(RTRIM(Message))) > 0)
|
||||
);
|
||||
END;
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys.indexes
|
||||
WHERE object_id = OBJECT_ID(N'dbo.Notifications')
|
||||
AND name = N'IX_Notifications_Recipient_Read_Created'
|
||||
)
|
||||
BEGIN
|
||||
CREATE INDEX IX_Notifications_Recipient_Read_Created
|
||||
ON dbo.Notifications(RecipientUserId, ReadAt, CreatedAt DESC)
|
||||
INCLUDE (Severity, Title, ActionUrl, ExpiresAt);
|
||||
END;
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys.indexes
|
||||
WHERE object_id = OBJECT_ID(N'dbo.Notifications')
|
||||
AND name = N'IX_Notifications_BroadcastId'
|
||||
)
|
||||
BEGIN
|
||||
CREATE INDEX IX_Notifications_BroadcastId
|
||||
ON dbo.Notifications(BroadcastId)
|
||||
WHERE BroadcastId IS NOT NULL;
|
||||
END;
|
||||
GO
|
||||
|
||||
PRINT N'RobotInstaller notification schema is ready.';
|
||||
GO
|
||||
@@ -28,6 +28,7 @@ Không lưu mật khẩu thật vào file cấu hình. Khi chạy local, tạo f
|
||||
| `dbo.PackageVersions` | Các version của từng package |
|
||||
| `dbo.Applications` | App được đóng gói từ nhiều package |
|
||||
| `dbo.ApplicationPackages` | Liên kết app-package, có thể chọn version cụ thể |
|
||||
| `dbo.Notifications` | Thông báo riêng cho từng user và thông báo hệ thống do Admin đăng |
|
||||
|
||||
## Ràng buộc quan trọng
|
||||
|
||||
@@ -63,12 +64,15 @@ $env:SQLCMDPASSWORD = '<mat-khau-sa>'
|
||||
sqlcmd -S 172.20.235.176 -U sa -b -i .\database\01_create_database.sql
|
||||
sqlcmd -S 172.20.235.176 -U sa -d RobotInstaller -b -i .\database\02_schema.sql
|
||||
sqlcmd -S 172.20.235.176 -U sa -d RobotInstaller -b -i .\database\03_views.sql
|
||||
sqlcmd -S 172.20.235.176 -U sa -d RobotInstaller -b -i .\database\04_notifications.sql
|
||||
```
|
||||
|
||||
Chạy các lệnh trên từ thư mục `web-server`.
|
||||
|
||||
Khi dùng `sqlcmd` để seed/test dữ liệu, thêm `-I` hoặc bật `SET QUOTED_IDENTIFIER ON` vì schema có filtered index cho ràng buộc một latest version trên mỗi package.
|
||||
|
||||
`04_notifications.sql` là migration chỉ bổ sung bảng/index và có thể chạy lặp lại. Với database đang hoạt động, chỉ chạy file này; không chạy lại `02_schema.sql` vì script schema gốc chủ động dừng khi phát hiện bảng đã tồn tại.
|
||||
|
||||
## Luồng dữ liệu đề xuất
|
||||
|
||||
1. Upload package mới:
|
||||
|
||||
@@ -225,6 +225,8 @@ button:disabled {
|
||||
height: 56px;
|
||||
justify-content: space-between;
|
||||
padding: 0 24px;
|
||||
position: relative;
|
||||
z-index: 60;
|
||||
}
|
||||
|
||||
.topbar-left,
|
||||
@@ -240,6 +242,256 @@ button:disabled {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.notification-center {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.notification-button {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.notification-badge {
|
||||
align-items: center;
|
||||
background: #d92d20;
|
||||
border: 2px solid #f8fafc;
|
||||
border-radius: 999px;
|
||||
color: #ffffff;
|
||||
display: inline-flex;
|
||||
font-size: 9px;
|
||||
font-weight: 800;
|
||||
height: 18px;
|
||||
justify-content: center;
|
||||
line-height: 1;
|
||||
min-width: 18px;
|
||||
padding: 0 4px;
|
||||
position: absolute;
|
||||
right: -7px;
|
||||
top: -7px;
|
||||
}
|
||||
|
||||
.notification-panel {
|
||||
background: #ffffff;
|
||||
border: 1px solid #dbe3ea;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-lg);
|
||||
overflow: hidden;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: calc(100% + 10px);
|
||||
width: min(400px, calc(100vw - 28px));
|
||||
z-index: 120;
|
||||
}
|
||||
|
||||
.notification-panel[hidden],
|
||||
.notification-badge[hidden],
|
||||
.notification-empty[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.notification-panel-header {
|
||||
align-items: center;
|
||||
border-bottom: 1px solid #eef2f7;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 14px 16px 10px;
|
||||
}
|
||||
|
||||
.notification-panel-header > div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.notification-panel-header strong {
|
||||
color: #111827;
|
||||
font-family: "Manrope", Arial, sans-serif;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.notification-panel-header span {
|
||||
color: #64748b;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.text-button {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: var(--primary);
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.text-button:hover,
|
||||
.text-button:focus-visible {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.notification-tabs {
|
||||
border-bottom: 1px solid #eef2f7;
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
padding: 0 16px;
|
||||
}
|
||||
|
||||
.notification-tabs button {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: #64748b;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
padding: 9px 0 7px;
|
||||
}
|
||||
|
||||
.notification-tabs button.active {
|
||||
border-bottom-color: var(--primary);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.notification-list {
|
||||
max-height: min(440px, calc(100vh - 190px));
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.notification-item {
|
||||
align-items: flex-start;
|
||||
background: #ffffff;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #f0f3f7;
|
||||
color: inherit;
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
grid-template-columns: 34px minmax(0, 1fr) 7px;
|
||||
padding: 12px 14px;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.notification-item:hover,
|
||||
.notification-item:focus-visible {
|
||||
background: #f8fafc;
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
.notification-item.unread {
|
||||
background: #f7f8ff;
|
||||
}
|
||||
|
||||
.notification-item.unread:hover,
|
||||
.notification-item.unread:focus-visible {
|
||||
background: #eef1ff;
|
||||
}
|
||||
|
||||
.notification-item-icon {
|
||||
align-items: center;
|
||||
background: var(--info-bg);
|
||||
border-radius: 50%;
|
||||
color: var(--info);
|
||||
display: inline-flex;
|
||||
height: 34px;
|
||||
justify-content: center;
|
||||
width: 34px;
|
||||
}
|
||||
|
||||
.notification-item-icon .material-symbols-outlined {
|
||||
font-size: 19px;
|
||||
}
|
||||
|
||||
.notification-item.tone-success .notification-item-icon {
|
||||
background: var(--success-bg);
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.notification-item.tone-warning .notification-item-icon {
|
||||
background: var(--warning-bg);
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.notification-item.tone-error .notification-item-icon {
|
||||
background: var(--danger-bg);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.notification-item-copy {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.notification-item-copy strong,
|
||||
.notification-item-copy span,
|
||||
.notification-item-copy time {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.notification-item-copy strong {
|
||||
color: #172033;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.notification-item-copy span {
|
||||
color: #52606d;
|
||||
font-size: 11px;
|
||||
line-height: 1.45;
|
||||
margin-top: 3px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.notification-item-copy time {
|
||||
color: #84909a;
|
||||
font-size: 10px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.notification-unread-dot {
|
||||
align-self: center;
|
||||
background: var(--primary);
|
||||
border-radius: 50%;
|
||||
height: 7px;
|
||||
opacity: 0;
|
||||
width: 7px;
|
||||
}
|
||||
|
||||
.notification-item.unread .notification-unread-dot {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.notification-empty {
|
||||
align-items: center;
|
||||
color: #64748b;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
min-height: 180px;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.notification-empty .material-symbols-outlined {
|
||||
color: #94a3b8;
|
||||
font-size: 32px;
|
||||
}
|
||||
|
||||
.notification-empty strong {
|
||||
color: #334155;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.notification-empty span:last-child {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.notification-panel-footer {
|
||||
background: #f8fafc;
|
||||
border-top: 1px solid #eef2f7;
|
||||
padding: 10px 14px;
|
||||
}
|
||||
|
||||
.notification-panel-footer .btn {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.profile-chip {
|
||||
align-items: center;
|
||||
background: transparent;
|
||||
@@ -419,6 +671,7 @@ button:disabled {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
|
||||
.dashboard-stats {
|
||||
display: grid;
|
||||
flex-shrink: 0;
|
||||
@@ -1060,6 +1313,13 @@ tbody tr:hover td.action-col {
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.modal-header p {
|
||||
color: #64748b;
|
||||
font-size: 11px;
|
||||
line-height: 1.45;
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.modal-form {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -1464,6 +1724,15 @@ tbody tr:hover td.action-col {
|
||||
padding: 0 14px;
|
||||
}
|
||||
|
||||
.notification-panel {
|
||||
left: 8px;
|
||||
max-height: calc(100dvh - 72px);
|
||||
position: fixed;
|
||||
right: 8px;
|
||||
top: 64px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.profile-meta {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -596,11 +596,343 @@
|
||||
});
|
||||
}
|
||||
|
||||
function formatNotificationTime(value) {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
|
||||
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1000));
|
||||
if (elapsedSeconds < 60) return 'Vừa xong';
|
||||
if (elapsedSeconds < 3600) return `${Math.floor(elapsedSeconds / 60)} phút trước`;
|
||||
if (elapsedSeconds < 86400) return `${Math.floor(elapsedSeconds / 3600)} giờ trước`;
|
||||
if (elapsedSeconds < 604800) return `${Math.floor(elapsedSeconds / 86400)} ngày trước`;
|
||||
|
||||
return new Intl.DateTimeFormat('vi-VN', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function getNotificationIcon(notification) {
|
||||
if (notification.isSystem) return 'campaign';
|
||||
if (notification.severity === 'success') return 'check_circle';
|
||||
if (notification.severity === 'warning') return 'warning';
|
||||
if (notification.severity === 'error') return 'error';
|
||||
if (notification.entityType === 'package') return 'inventory_2';
|
||||
if (notification.entityType === 'application') return 'apps';
|
||||
return 'notifications';
|
||||
}
|
||||
|
||||
async function notificationRequest(url, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
cache: 'no-store',
|
||||
credentials: 'same-origin',
|
||||
...options,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(options.body ? { 'Content-Type': 'application/json' } : {}),
|
||||
...(options.headers || {})
|
||||
}
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || 'Không thể xử lý thông báo.');
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function initNotificationCenter() {
|
||||
const center = document.querySelector('[data-notification-center]');
|
||||
if (!center) return;
|
||||
|
||||
const toggle = center.querySelector('[data-notification-toggle]');
|
||||
const panel = center.querySelector('[data-notification-panel]');
|
||||
const badge = center.querySelector('[data-notification-badge]');
|
||||
const summary = center.querySelector('[data-notification-summary]');
|
||||
const list = center.querySelector('[data-notification-list]');
|
||||
const empty = center.querySelector('[data-notification-empty]');
|
||||
const readAllButton = center.querySelector('[data-notification-read-all]');
|
||||
const filterButtons = center.querySelectorAll('[data-notification-filter]');
|
||||
const knownNotificationIds = new Set();
|
||||
let currentFilter = 'all';
|
||||
let initialized = false;
|
||||
let loading = false;
|
||||
let reloadPending = false;
|
||||
|
||||
function setPanelOpen(open) {
|
||||
panel.hidden = !open;
|
||||
toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||||
}
|
||||
|
||||
function setEmptyState(title, message, visible) {
|
||||
const titleElement = empty.querySelector('strong');
|
||||
const messageElement = empty.querySelector('span:last-child');
|
||||
if (titleElement) titleElement.textContent = title;
|
||||
if (messageElement) messageElement.textContent = message;
|
||||
empty.hidden = !visible;
|
||||
}
|
||||
|
||||
function updateUnreadCount(count) {
|
||||
const unreadCount = Math.max(0, Number(count) || 0);
|
||||
badge.textContent = unreadCount > 99 ? '99+' : String(unreadCount);
|
||||
badge.hidden = unreadCount === 0;
|
||||
summary.textContent = unreadCount > 0 ? `${unreadCount} thông báo chưa đọc` : 'Không có thông báo chưa đọc';
|
||||
readAllButton.disabled = unreadCount === 0;
|
||||
}
|
||||
|
||||
function renderNotifications(notifications) {
|
||||
list.replaceChildren();
|
||||
setEmptyState(
|
||||
currentFilter === 'unread' ? 'Không có thông báo chưa đọc' : 'Chưa có thông báo',
|
||||
'Các cập nhật quan trọng sẽ xuất hiện tại đây.',
|
||||
notifications.length === 0
|
||||
);
|
||||
|
||||
notifications.forEach((notification) => {
|
||||
const item = document.createElement('button');
|
||||
item.type = 'button';
|
||||
item.className = `notification-item tone-${notification.severity || 'info'}${notification.isRead ? '' : ' unread'}`;
|
||||
item.dataset.notificationId = notification.id;
|
||||
|
||||
const icon = document.createElement('span');
|
||||
icon.className = 'notification-item-icon';
|
||||
const iconGlyph = document.createElement('span');
|
||||
iconGlyph.className = 'material-symbols-outlined';
|
||||
iconGlyph.setAttribute('aria-hidden', 'true');
|
||||
iconGlyph.textContent = getNotificationIcon(notification);
|
||||
icon.appendChild(iconGlyph);
|
||||
|
||||
const copy = document.createElement('span');
|
||||
copy.className = 'notification-item-copy';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = notification.title;
|
||||
const message = document.createElement('span');
|
||||
message.textContent = notification.message;
|
||||
const time = document.createElement('time');
|
||||
time.dateTime = notification.createdAt || '';
|
||||
time.textContent = formatNotificationTime(notification.createdAt);
|
||||
copy.append(title, message, time);
|
||||
|
||||
const unreadDot = document.createElement('span');
|
||||
unreadDot.className = 'notification-unread-dot';
|
||||
unreadDot.setAttribute('aria-label', notification.isRead ? 'Đã đọc' : 'Chưa đọc');
|
||||
|
||||
item.append(icon, copy, unreadDot);
|
||||
item.addEventListener('click', async () => {
|
||||
try {
|
||||
if (!notification.isRead) {
|
||||
await notificationRequest(`/api/notifications/${encodeURIComponent(notification.id)}/read`, {
|
||||
method: 'POST'
|
||||
});
|
||||
notification.isRead = true;
|
||||
item.classList.remove('unread');
|
||||
await loadNotifications(false);
|
||||
}
|
||||
} catch (error) {
|
||||
notify('warning', error.message);
|
||||
}
|
||||
|
||||
if (
|
||||
notification.actionUrl
|
||||
&& notification.actionUrl.startsWith('/')
|
||||
&& !notification.actionUrl.startsWith('//')
|
||||
) {
|
||||
window.location.assign(notification.actionUrl);
|
||||
}
|
||||
});
|
||||
|
||||
list.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadNotifications(announceNew = true) {
|
||||
if (loading) {
|
||||
reloadPending = true;
|
||||
return;
|
||||
}
|
||||
loading = true;
|
||||
|
||||
try {
|
||||
const data = await notificationRequest(
|
||||
`/api/notifications?limit=20&unreadOnly=${currentFilter === 'unread' ? 'true' : 'false'}`
|
||||
);
|
||||
|
||||
if (!data.available) {
|
||||
badge.hidden = true;
|
||||
summary.textContent = 'Chưa kích hoạt trong database';
|
||||
readAllButton.disabled = true;
|
||||
list.replaceChildren();
|
||||
setEmptyState(
|
||||
'Thông báo chưa khả dụng',
|
||||
'Admin cần chạy migration 04_notifications.sql.',
|
||||
true
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const notifications = Array.isArray(data.notifications) ? data.notifications : [];
|
||||
if (initialized && announceNew) {
|
||||
const importantNotification = notifications.find((notification) => (
|
||||
!knownNotificationIds.has(notification.id)
|
||||
&& !notification.isRead
|
||||
&& ['warning', 'error'].includes(notification.severity)
|
||||
));
|
||||
|
||||
if (importantNotification) {
|
||||
notify(
|
||||
importantNotification.severity === 'error' ? 'failure' : 'warning',
|
||||
importantNotification.title
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
notifications.forEach((notification) => knownNotificationIds.add(notification.id));
|
||||
initialized = true;
|
||||
updateUnreadCount(data.unreadCount);
|
||||
renderNotifications(notifications);
|
||||
} catch (error) {
|
||||
summary.textContent = 'Không thể tải thông báo';
|
||||
setEmptyState('Không thể tải thông báo', 'Vui lòng thử lại sau.', true);
|
||||
} finally {
|
||||
loading = false;
|
||||
if (reloadPending) {
|
||||
reloadPending = false;
|
||||
loadNotifications(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshUnreadCount() {
|
||||
try {
|
||||
const data = await notificationRequest('/api/notifications?countOnly=true');
|
||||
if (!data.available) {
|
||||
badge.hidden = true;
|
||||
summary.textContent = 'Chưa kích hoạt trong database';
|
||||
readAllButton.disabled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
updateUnreadCount(data.unreadCount);
|
||||
} catch (error) {
|
||||
console.info('Cannot refresh notification count:', error);
|
||||
}
|
||||
}
|
||||
|
||||
toggle.addEventListener('click', () => {
|
||||
const open = panel.hidden;
|
||||
setPanelOpen(open);
|
||||
if (open) loadNotifications(false);
|
||||
});
|
||||
|
||||
readAllButton.addEventListener('click', async () => {
|
||||
readAllButton.disabled = true;
|
||||
try {
|
||||
await notificationRequest('/api/notifications/read-all', { method: 'POST' });
|
||||
await loadNotifications(false);
|
||||
} catch (error) {
|
||||
notify('failure', error.message);
|
||||
}
|
||||
});
|
||||
|
||||
filterButtons.forEach((button) => {
|
||||
button.addEventListener('click', () => {
|
||||
currentFilter = button.dataset.notificationFilter;
|
||||
filterButtons.forEach((candidate) => {
|
||||
const active = candidate === button;
|
||||
candidate.classList.toggle('active', active);
|
||||
candidate.setAttribute('aria-selected', active ? 'true' : 'false');
|
||||
});
|
||||
loadNotifications(false);
|
||||
});
|
||||
});
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
if (!panel.hidden && !center.contains(event.target)) {
|
||||
setPanelOpen(false);
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape' && !panel.hidden) {
|
||||
setPanelOpen(false);
|
||||
toggle.focus();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
if (panel.hidden) refreshUnreadCount();
|
||||
else loadNotifications(true);
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('notifications:refresh', () => {
|
||||
if (panel.hidden) refreshUnreadCount();
|
||||
else loadNotifications(false);
|
||||
});
|
||||
|
||||
const broadcastButton = center.querySelector('[data-modal-open="systemNotificationModal"]');
|
||||
if (broadcastButton) {
|
||||
broadcastButton.addEventListener('click', () => setPanelOpen(false));
|
||||
}
|
||||
|
||||
window.setInterval(() => {
|
||||
if (document.visibilityState !== 'visible') return;
|
||||
if (panel.hidden) refreshUnreadCount();
|
||||
else loadNotifications(true);
|
||||
}, 30000);
|
||||
|
||||
refreshUnreadCount();
|
||||
}
|
||||
|
||||
function initSystemNotificationForm() {
|
||||
const form = document.querySelector('[data-system-notification-form]');
|
||||
if (!form) return;
|
||||
|
||||
form.addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
if (!form.reportValidity()) return;
|
||||
|
||||
confirmAction('Gửi thông báo này tới tất cả tài khoản đang hoạt động?', async () => {
|
||||
const submitButton = form.querySelector('[data-system-notification-submit]');
|
||||
const formData = new FormData(form);
|
||||
submitButton.disabled = true;
|
||||
|
||||
try {
|
||||
const result = await notificationRequest('/api/notifications/broadcasts', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
title: formData.get('title'),
|
||||
severity: formData.get('severity'),
|
||||
message: formData.get('message'),
|
||||
actionUrl: formData.get('actionUrl')
|
||||
})
|
||||
});
|
||||
|
||||
closeModal(form.closest('.modal-backdrop'));
|
||||
form.reset();
|
||||
notify('success', `Đã gửi thông báo tới ${result.recipientCount || 0} người dùng.`);
|
||||
document.dispatchEvent(new CustomEvent('notifications:refresh'));
|
||||
} catch (error) {
|
||||
notify('failure', error.message);
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
initNotiflix();
|
||||
initFileDropzones();
|
||||
initRegistrationUniqueChecks();
|
||||
initProfileForms();
|
||||
initEditAppForms();
|
||||
initNotificationCenter();
|
||||
initSystemNotificationForm();
|
||||
|
||||
if (body.dataset.notice) {
|
||||
notify(body.dataset.noticeType || 'info', body.dataset.notice);
|
||||
|
||||
@@ -8,6 +8,7 @@ const path = require('path');
|
||||
const express = require('express');
|
||||
const multer = require('multer');
|
||||
const repository = require('./src/repository');
|
||||
const notificationRepository = require('./src/notification-repository');
|
||||
const mailer = require('./src/mailer');
|
||||
const { closePool, getPool } = require('./src/db');
|
||||
const notiflixVersion = require('notiflix/package.json').version;
|
||||
@@ -123,6 +124,7 @@ app.set('view engine', 'ejs');
|
||||
app.set('views', path.join(__dirname, 'views'));
|
||||
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.json({ limit: '32kb' }));
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
app.use('/vendor/notiflix', express.static(path.join(__dirname, 'node_modules/notiflix/dist')));
|
||||
app.use(applyPublicApiCors);
|
||||
@@ -524,6 +526,55 @@ function sanitizeReturnTo(value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
function sanitizeNotificationActionUrl(value) {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return '';
|
||||
if (
|
||||
text.length > 1000
|
||||
|| !text.startsWith('/')
|
||||
|| text.startsWith('//')
|
||||
|| text.includes('\\')
|
||||
|| /[\u0000-\u001F\u007F]/.test(text)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
function normalizeNotificationSeverity(value) {
|
||||
const severity = String(value || 'info').trim().toLowerCase();
|
||||
return ['info', 'success', 'warning', 'error'].includes(severity) ? severity : null;
|
||||
}
|
||||
|
||||
function isUuid(value) {
|
||||
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
||||
String(value || '').trim()
|
||||
);
|
||||
}
|
||||
|
||||
function getNotificationActorName(user) {
|
||||
return String(user?.name || user?.username || '').trim();
|
||||
}
|
||||
|
||||
async function safelyCreateNotification(label, callback) {
|
||||
try {
|
||||
return await callback();
|
||||
} catch (error) {
|
||||
console.error(`Cannot create notification (${label}):`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function safelyLoadNotificationContext(label, callback) {
|
||||
try {
|
||||
return await callback();
|
||||
} catch (error) {
|
||||
console.error(`Cannot load notification context (${label}):`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getBaseUrl(req) {
|
||||
const requestBaseUrl = getRequestBaseUrl(req);
|
||||
if (process.env.APP_BASE_URL) {
|
||||
@@ -851,6 +902,15 @@ function requireAdmin(req, res, next) {
|
||||
redirectWithNotice(res, '/', 'failure', 'Bạn cần quyền Admin để quản lý user.');
|
||||
}
|
||||
|
||||
function requireAdminApi(req, res, next) {
|
||||
if (req.currentUser && req.currentUser.role === 'Admin') {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(403).json({ error: 'Bạn cần quyền Admin để thực hiện thao tác này.' });
|
||||
}
|
||||
|
||||
function normalizePackageType(value) {
|
||||
const packageType = String(value || 'deb').toLowerCase();
|
||||
return ['deb', 'apt', 'docker'].includes(packageType) ? packageType : 'deb';
|
||||
@@ -1497,6 +1557,92 @@ exit 1
|
||||
app.use(requireAuthenticated);
|
||||
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
|
||||
|
||||
app.get('/api/notifications', asyncRoute(async (req, res) => {
|
||||
const countOnly = String(req.query.countOnly || '').toLowerCase() === 'true';
|
||||
const result = countOnly
|
||||
? await notificationRepository.getUnreadCount(req.currentUser.id)
|
||||
: await notificationRepository.listNotifications(req.currentUser.id, {
|
||||
limit: req.query.limit,
|
||||
unreadOnly: String(req.query.unreadOnly || '').toLowerCase() === 'true'
|
||||
});
|
||||
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.post('/api/notifications/read-all', asyncRoute(async (req, res) => {
|
||||
const result = await notificationRepository.markAllNotificationsRead(req.currentUser.id);
|
||||
if (!result.available) {
|
||||
res.status(503).json({ error: 'Tính năng thông báo chưa được kích hoạt trong database.' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.post('/api/notifications/:id/read', asyncRoute(async (req, res) => {
|
||||
if (!isUuid(req.params.id)) {
|
||||
res.status(400).json({ error: 'Notification id không hợp lệ.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await notificationRepository.markNotificationRead(req.currentUser.id, req.params.id);
|
||||
if (!result.available) {
|
||||
res.status(503).json({ error: 'Tính năng thông báo chưa được kích hoạt trong database.' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!result.updated) {
|
||||
res.status(404).json({ error: 'Không tìm thấy thông báo.' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.post('/api/notifications/broadcasts', requireAdminApi, asyncRoute(async (req, res) => {
|
||||
const title = String(req.body.title || '').trim();
|
||||
const message = String(req.body.message || '').trim();
|
||||
const severity = normalizeNotificationSeverity(req.body.severity);
|
||||
const actionUrl = sanitizeNotificationActionUrl(req.body.actionUrl);
|
||||
|
||||
if (!title || title.length > 200) {
|
||||
res.status(400).json({ error: 'Tiêu đề bắt buộc và không được vượt quá 200 ký tự.' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!message || message.length > 1000) {
|
||||
res.status(400).json({ error: 'Nội dung bắt buộc và không được vượt quá 1000 ký tự.' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!severity) {
|
||||
res.status(400).json({ error: 'Mức độ thông báo không hợp lệ.' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (actionUrl === null) {
|
||||
res.status(400).json({ error: 'Đường dẫn phải là đường dẫn nội bộ bắt đầu bằng /.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await notificationRepository.createSystemBroadcast({
|
||||
actorUserId: req.currentUser.id,
|
||||
actorName: getNotificationActorName(req.currentUser),
|
||||
severity,
|
||||
title,
|
||||
message,
|
||||
actionUrl
|
||||
});
|
||||
|
||||
if (!result.available) {
|
||||
res.status(503).json({ error: 'Chưa có bảng dbo.Notifications. Hãy chạy migration 04_notifications.sql trước.' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(201).json(result);
|
||||
}));
|
||||
|
||||
app.get('/agent', requireAdmin, asyncRoute(async (req, res) => {
|
||||
const pageData = await repository.getPageData(req.currentUser);
|
||||
const agentPackages = await listAgentPackages();
|
||||
@@ -1824,6 +1970,14 @@ app.post('/package-versions', upload.single('packageFile'), asyncRoute(async (re
|
||||
};
|
||||
|
||||
await repository.addPackageVersion(versionInput);
|
||||
await safelyCreateNotification('package version available', () => (
|
||||
notificationRepository.notifyPackageVersionAvailable({
|
||||
packageId: versionInput.packageId,
|
||||
version: versionInput.version,
|
||||
actorUserId: req.currentUser.id,
|
||||
actorName: getNotificationActorName(req.currentUser)
|
||||
})
|
||||
));
|
||||
|
||||
redirectWithNotice(res, `/packages/${req.body.packageId}`, 'success', 'Đã cập nhật version mới và đặt làm latest.');
|
||||
} catch (error) {
|
||||
@@ -1833,6 +1987,15 @@ app.post('/package-versions', upload.single('packageFile'), asyncRoute(async (re
|
||||
const replacedVersionId = await repository.replacePackageVersionArtifact(versionInput);
|
||||
|
||||
if (replacedVersionId) {
|
||||
await safelyCreateNotification('package version artifact updated', () => (
|
||||
notificationRepository.notifyPackageVersionAvailable({
|
||||
packageId: versionInput.packageId,
|
||||
version: versionInput.version,
|
||||
isArtifactUpdate: true,
|
||||
actorUserId: req.currentUser.id,
|
||||
actorName: getNotificationActorName(req.currentUser)
|
||||
})
|
||||
));
|
||||
redirectWithNotice(
|
||||
res,
|
||||
`/packages/${versionInput.packageId}`,
|
||||
@@ -1857,8 +2020,28 @@ app.post('/package-versions', upload.single('packageFile'), asyncRoute(async (re
|
||||
}));
|
||||
|
||||
app.post('/packages/:id/delete', asyncRoute(async (req, res) => {
|
||||
const notificationImpact = await safelyLoadNotificationContext('package delete', () => (
|
||||
notificationRepository.getPackageImpact(req.params.id)
|
||||
));
|
||||
const deleted = await repository.deletePackage(req.params.id);
|
||||
|
||||
if (deleted && notificationImpact) {
|
||||
await safelyCreateNotification('package deleted', () => (
|
||||
notificationRepository.createNotificationsForUsers({
|
||||
recipientUserIds: notificationImpact.recipientUserIds,
|
||||
actorUserId: req.currentUser.id,
|
||||
actorName: getNotificationActorName(req.currentUser),
|
||||
eventType: 'package.deleted',
|
||||
severity: 'error',
|
||||
title: `Package ${notificationImpact.packageCode} đã bị xóa`,
|
||||
message: 'Các liên kết application sử dụng package này đã bị gỡ. Hãy kiểm tra lại cấu hình application liên quan.',
|
||||
actionUrl: '/applications',
|
||||
entityType: 'package',
|
||||
entityId: notificationImpact.packageId
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
redirectWithNotice(
|
||||
res,
|
||||
'/packages',
|
||||
@@ -1876,8 +2059,28 @@ app.post('/package-versions/:id/latest', asyncRoute(async (req, res) => {
|
||||
|
||||
app.post('/package-versions/:id/delete', asyncRoute(async (req, res) => {
|
||||
const returnTo = sanitizeReturnTo(req.body.returnTo || '/packages');
|
||||
const notificationImpact = await safelyLoadNotificationContext('package version delete', () => (
|
||||
notificationRepository.getPackageVersionImpact(req.params.id)
|
||||
));
|
||||
const result = await repository.deletePackageVersion(req.params.id);
|
||||
|
||||
if (result.deleted && notificationImpact) {
|
||||
await safelyCreateNotification('package version deleted', () => (
|
||||
notificationRepository.createNotificationsForUsers({
|
||||
recipientUserIds: notificationImpact.recipientUserIds,
|
||||
actorUserId: req.currentUser.id,
|
||||
actorName: getNotificationActorName(req.currentUser),
|
||||
eventType: 'package.version_deleted',
|
||||
severity: 'warning',
|
||||
title: `Version ${notificationImpact.version} của ${notificationImpact.packageCode} đã bị xóa`,
|
||||
message: 'Các liên kết application sử dụng chính version này đã bị gỡ. Hãy kiểm tra lại application liên quan.',
|
||||
actionUrl: '/applications',
|
||||
entityType: 'package',
|
||||
entityId: notificationImpact.packageId
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
redirectWithNotice(
|
||||
res,
|
||||
result.packageId ? `/packages/${result.packageId}` : returnTo,
|
||||
@@ -2037,6 +2240,16 @@ app.post('/applications/:id/release', asyncRoute(async (req, res) => {
|
||||
const returnTo = sanitizeReturnTo(req.body.returnTo || `/applications/${applicationId}`);
|
||||
const updated = await repository.updateApplicationStatus(applicationId, 'Released');
|
||||
|
||||
if (updated) {
|
||||
await safelyCreateNotification('application released', () => (
|
||||
notificationRepository.notifyApplicationReleased({
|
||||
applicationId,
|
||||
actorUserId: req.currentUser.id,
|
||||
actorName: getNotificationActorName(req.currentUser)
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
redirectWithNotice(
|
||||
res,
|
||||
returnTo,
|
||||
@@ -2237,6 +2450,13 @@ app.get('/builder', asyncRoute(async (req, res) => {
|
||||
app.use(async (error, req, res, next) => {
|
||||
console.error(error);
|
||||
|
||||
if (req.path.startsWith('/api/notifications')) {
|
||||
res.status(500).json({
|
||||
error: 'Không thể xử lý thông báo lúc này. Vui lòng thử lại sau.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const pageData = await repository.getPageData(req.currentUser).catch(() => ({
|
||||
currentUser: req.currentUser || { name: 'Guest', role: 'Guest', email: '' },
|
||||
stats: {
|
||||
|
||||
458
web-server/src/notification-repository.js
Normal file
458
web-server/src/notification-repository.js
Normal file
@@ -0,0 +1,458 @@
|
||||
const crypto = require('crypto');
|
||||
const { sql, getPool } = require('./db');
|
||||
|
||||
const SCHEMA_CHECK_TTL_MS = 30 * 1000;
|
||||
const ALLOWED_SEVERITIES = new Set(['info', 'success', 'warning', 'error']);
|
||||
let notificationSchemaState = {
|
||||
available: false,
|
||||
checkedAt: 0
|
||||
};
|
||||
|
||||
function normalizeSeverity(value) {
|
||||
const severity = String(value || '').trim().toLowerCase();
|
||||
return ALLOWED_SEVERITIES.has(severity) ? severity : 'info';
|
||||
}
|
||||
|
||||
function toIsoString(value) {
|
||||
if (!value) return null;
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
||||
}
|
||||
|
||||
function mapNotificationRow(row) {
|
||||
return {
|
||||
id: String(row.Id),
|
||||
eventType: row.EventType,
|
||||
isSystem: row.EventType === 'system.announcement',
|
||||
severity: normalizeSeverity(row.Severity),
|
||||
title: row.Title,
|
||||
message: row.Message,
|
||||
entityType: row.EntityType || '',
|
||||
entityId: row.EntityId || '',
|
||||
actionUrl: row.ActionUrl || '',
|
||||
actorName: row.ActorName || '',
|
||||
isRead: Boolean(row.ReadAt),
|
||||
readAt: toIsoString(row.ReadAt),
|
||||
createdAt: toIsoString(row.CreatedAt)
|
||||
};
|
||||
}
|
||||
|
||||
async function checkNotificationSchema(force = false) {
|
||||
const now = Date.now();
|
||||
if (!force && now - notificationSchemaState.checkedAt < SCHEMA_CHECK_TTL_MS) {
|
||||
return notificationSchemaState.available;
|
||||
}
|
||||
|
||||
const pool = await getPool();
|
||||
const result = await pool.request().query(`
|
||||
SELECT CASE WHEN OBJECT_ID(N'dbo.Notifications', N'U') IS NULL THEN 0 ELSE 1 END AS IsAvailable;
|
||||
`);
|
||||
|
||||
notificationSchemaState = {
|
||||
available: Boolean(result.recordset[0] && result.recordset[0].IsAvailable),
|
||||
checkedAt: now
|
||||
};
|
||||
return notificationSchemaState.available;
|
||||
}
|
||||
|
||||
async function listNotifications(userId, options = {}) {
|
||||
const available = await checkNotificationSchema();
|
||||
if (!available) {
|
||||
return {
|
||||
available: false,
|
||||
notifications: [],
|
||||
unreadCount: 0
|
||||
};
|
||||
}
|
||||
|
||||
const limit = Math.min(Math.max(Math.trunc(Number(options.limit)) || 20, 1), 50);
|
||||
const unreadOnly = Boolean(options.unreadOnly);
|
||||
const pool = await getPool();
|
||||
const result = await pool.request()
|
||||
.input('RecipientUserId', sql.UniqueIdentifier, userId)
|
||||
.input('Limit', sql.Int, limit)
|
||||
.input('UnreadOnly', sql.Bit, unreadOnly ? 1 : 0)
|
||||
.query(`
|
||||
SELECT COUNT_BIG(*) AS UnreadCount
|
||||
FROM dbo.Notifications
|
||||
WHERE RecipientUserId = @RecipientUserId
|
||||
AND ReadAt IS NULL
|
||||
AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME());
|
||||
|
||||
SELECT TOP (@Limit)
|
||||
Id, EventType, Severity, Title, Message, EntityType, EntityId,
|
||||
ActionUrl, ActorName, ReadAt, CreatedAt
|
||||
FROM dbo.Notifications
|
||||
WHERE RecipientUserId = @RecipientUserId
|
||||
AND (@UnreadOnly = 0 OR ReadAt IS NULL)
|
||||
AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME())
|
||||
ORDER BY CreatedAt DESC, Id DESC;
|
||||
`);
|
||||
|
||||
return {
|
||||
available: true,
|
||||
unreadCount: Number(result.recordsets[0][0].UnreadCount || 0),
|
||||
notifications: result.recordsets[1].map(mapNotificationRow)
|
||||
};
|
||||
}
|
||||
|
||||
async function getUnreadCount(userId) {
|
||||
const available = await checkNotificationSchema();
|
||||
if (!available) {
|
||||
return { available: false, unreadCount: 0 };
|
||||
}
|
||||
|
||||
const pool = await getPool();
|
||||
const result = await pool.request()
|
||||
.input('RecipientUserId', sql.UniqueIdentifier, userId)
|
||||
.query(`
|
||||
SELECT COUNT_BIG(*) AS UnreadCount
|
||||
FROM dbo.Notifications
|
||||
WHERE RecipientUserId = @RecipientUserId
|
||||
AND ReadAt IS NULL
|
||||
AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME());
|
||||
`);
|
||||
|
||||
return {
|
||||
available: true,
|
||||
unreadCount: Number(result.recordset[0].UnreadCount || 0)
|
||||
};
|
||||
}
|
||||
|
||||
async function markNotificationRead(notificationId, userId) {
|
||||
if (!await checkNotificationSchema()) {
|
||||
return { available: false, updated: false };
|
||||
}
|
||||
|
||||
const pool = await getPool();
|
||||
const result = await pool.request()
|
||||
.input('Id', sql.UniqueIdentifier, notificationId)
|
||||
.input('RecipientUserId', sql.UniqueIdentifier, userId)
|
||||
.query(`
|
||||
UPDATE dbo.Notifications
|
||||
SET ReadAt = COALESCE(ReadAt, SYSUTCDATETIME())
|
||||
OUTPUT inserted.Id
|
||||
WHERE Id = @Id
|
||||
AND RecipientUserId = @RecipientUserId;
|
||||
`);
|
||||
|
||||
return {
|
||||
available: true,
|
||||
updated: result.recordset.length > 0
|
||||
};
|
||||
}
|
||||
|
||||
async function markAllNotificationsRead(userId) {
|
||||
if (!await checkNotificationSchema()) {
|
||||
return { available: false, updatedCount: 0 };
|
||||
}
|
||||
|
||||
const pool = await getPool();
|
||||
const result = await pool.request()
|
||||
.input('RecipientUserId', sql.UniqueIdentifier, userId)
|
||||
.query(`
|
||||
UPDATE dbo.Notifications
|
||||
SET ReadAt = SYSUTCDATETIME()
|
||||
OUTPUT inserted.Id
|
||||
WHERE RecipientUserId = @RecipientUserId
|
||||
AND ReadAt IS NULL
|
||||
AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME());
|
||||
`);
|
||||
|
||||
return {
|
||||
available: true,
|
||||
updatedCount: result.recordset.length
|
||||
};
|
||||
}
|
||||
|
||||
async function createSystemBroadcast(input) {
|
||||
if (!await checkNotificationSchema()) {
|
||||
return { available: false, broadcastId: null, recipientCount: 0 };
|
||||
}
|
||||
|
||||
const pool = await getPool();
|
||||
const broadcastId = crypto.randomUUID();
|
||||
const result = await pool.request()
|
||||
.input('ActorUserId', sql.UniqueIdentifier, input.actorUserId)
|
||||
.input('ActorName', sql.NVarChar(200), input.actorName || null)
|
||||
.input('BroadcastId', sql.UniqueIdentifier, broadcastId)
|
||||
.input('Severity', sql.NVarChar(20), normalizeSeverity(input.severity))
|
||||
.input('Title', sql.NVarChar(200), input.title)
|
||||
.input('Message', sql.NVarChar(1000), input.message)
|
||||
.input('ActionUrl', sql.NVarChar(1000), input.actionUrl || null)
|
||||
.query(`
|
||||
INSERT dbo.Notifications (
|
||||
RecipientUserId, ActorUserId, ActorName, BroadcastId, EventType,
|
||||
Severity, Title, Message, EntityType, ActionUrl
|
||||
)
|
||||
SELECT
|
||||
u.Id, @ActorUserId, @ActorName, @BroadcastId, N'system.announcement',
|
||||
@Severity, @Title, @Message, N'system', @ActionUrl
|
||||
FROM dbo.Users AS u
|
||||
WHERE u.IsActive = 1;
|
||||
|
||||
DECLARE @RecipientCount INT = @@ROWCOUNT;
|
||||
SELECT @RecipientCount AS RecipientCount;
|
||||
`);
|
||||
|
||||
return {
|
||||
available: true,
|
||||
broadcastId,
|
||||
recipientCount: Number(result.recordset[0].RecipientCount || 0)
|
||||
};
|
||||
}
|
||||
|
||||
async function createNotificationsForUsers(input) {
|
||||
if (!await checkNotificationSchema()) {
|
||||
return { available: false, recipientCount: 0 };
|
||||
}
|
||||
|
||||
const uniqueRecipientIds = Array.from(new Set((input.recipientUserIds || []).filter(Boolean))).slice(0, 1000);
|
||||
if (uniqueRecipientIds.length === 0) {
|
||||
return { available: true, recipientCount: 0 };
|
||||
}
|
||||
|
||||
const pool = await getPool();
|
||||
const request = pool.request()
|
||||
.input('ActorUserId', sql.UniqueIdentifier, input.actorUserId || null)
|
||||
.input('ActorName', sql.NVarChar(200), input.actorName || null)
|
||||
.input('EventType', sql.NVarChar(100), input.eventType)
|
||||
.input('Severity', sql.NVarChar(20), normalizeSeverity(input.severity))
|
||||
.input('Title', sql.NVarChar(200), input.title)
|
||||
.input('Message', sql.NVarChar(1000), input.message)
|
||||
.input('EntityType', sql.NVarChar(50), input.entityType || null)
|
||||
.input('EntityId', sql.NVarChar(100), input.entityId || null)
|
||||
.input('ActionUrl', sql.NVarChar(1000), input.actionUrl || null);
|
||||
const recipientRows = uniqueRecipientIds.map((userId, index) => {
|
||||
const parameterName = `RecipientUserId${index}`;
|
||||
request.input(parameterName, sql.UniqueIdentifier, userId);
|
||||
return `SELECT @${parameterName} AS Id`;
|
||||
}).join('\nUNION ALL\n');
|
||||
|
||||
const result = await request.query(`
|
||||
WITH RequestedRecipients AS (
|
||||
${recipientRows}
|
||||
)
|
||||
INSERT dbo.Notifications (
|
||||
RecipientUserId, ActorUserId, ActorName, EventType, Severity,
|
||||
Title, Message, EntityType, EntityId, ActionUrl
|
||||
)
|
||||
SELECT DISTINCT
|
||||
u.Id, @ActorUserId, @ActorName, @EventType, @Severity,
|
||||
@Title, @Message, @EntityType, @EntityId, @ActionUrl
|
||||
FROM dbo.Users AS u
|
||||
INNER JOIN RequestedRecipients AS requested ON requested.Id = u.Id
|
||||
WHERE u.IsActive = 1
|
||||
AND (@ActorUserId IS NULL OR u.Id <> @ActorUserId);
|
||||
|
||||
DECLARE @RecipientCount INT = @@ROWCOUNT;
|
||||
SELECT @RecipientCount AS RecipientCount;
|
||||
`);
|
||||
|
||||
return {
|
||||
available: true,
|
||||
recipientCount: Number(result.recordset[0].RecipientCount || 0)
|
||||
};
|
||||
}
|
||||
|
||||
async function getPackageVersionAudience(packageId) {
|
||||
if (!await checkNotificationSchema()) return [];
|
||||
|
||||
const pool = await getPool();
|
||||
const result = await pool.request()
|
||||
.input('PackageId', sql.UniqueIdentifier, packageId)
|
||||
.query(`
|
||||
SELECT DISTINCT a.CreatedByUserId AS UserId
|
||||
FROM dbo.ApplicationPackages AS ap
|
||||
INNER JOIN dbo.Applications AS a ON a.Id = ap.ApplicationId
|
||||
WHERE ap.PackageId = @PackageId;
|
||||
`);
|
||||
|
||||
return result.recordset.map((row) => String(row.UserId));
|
||||
}
|
||||
|
||||
async function notifyPackageVersionAvailable(input) {
|
||||
if (!await checkNotificationSchema()) {
|
||||
return { available: false, recipientCount: 0 };
|
||||
}
|
||||
|
||||
const pool = await getPool();
|
||||
const packageResult = await pool.request()
|
||||
.input('PackageId', sql.UniqueIdentifier, input.packageId)
|
||||
.query(`
|
||||
SELECT TOP (1) Id, PackageCode, PackageName
|
||||
FROM dbo.Packages
|
||||
WHERE Id = @PackageId;
|
||||
`);
|
||||
const packageRow = packageResult.recordset[0];
|
||||
if (!packageRow) {
|
||||
return { available: true, recipientCount: 0 };
|
||||
}
|
||||
|
||||
const recipientUserIds = await getPackageVersionAudience(input.packageId);
|
||||
const isArtifactUpdate = Boolean(input.isArtifactUpdate);
|
||||
return createNotificationsForUsers({
|
||||
recipientUserIds,
|
||||
actorUserId: input.actorUserId,
|
||||
actorName: input.actorName,
|
||||
eventType: isArtifactUpdate ? 'package.version_artifact_updated' : 'package.version_available',
|
||||
severity: 'info',
|
||||
title: isArtifactUpdate
|
||||
? `Artifact ${packageRow.PackageCode} ${input.version} đã được cập nhật`
|
||||
: `Package ${packageRow.PackageCode} có version ${input.version} mới`,
|
||||
message: isArtifactUpdate
|
||||
? 'Artifact của version hiện tại đã được upload lại. Hãy kiểm tra trước khi triển khai tiếp.'
|
||||
: 'Application của bạn đang sử dụng package này. Hãy kiểm tra và chọn version mới khi phù hợp.',
|
||||
entityType: 'package',
|
||||
entityId: String(packageRow.Id),
|
||||
actionUrl: `/packages/${packageRow.Id}`
|
||||
});
|
||||
}
|
||||
|
||||
async function getPackageDeletionContext(packageId) {
|
||||
if (!await checkNotificationSchema()) return null;
|
||||
|
||||
const pool = await getPool();
|
||||
const result = await pool.request()
|
||||
.input('PackageId', sql.UniqueIdentifier, packageId)
|
||||
.query(`
|
||||
SELECT TOP (1) Id, PackageCode, PackageName, CreatedByUserId
|
||||
FROM dbo.Packages
|
||||
WHERE Id = @PackageId;
|
||||
|
||||
SELECT DISTINCT recipients.UserId
|
||||
FROM (
|
||||
SELECT a.CreatedByUserId AS UserId
|
||||
FROM dbo.ApplicationPackages AS ap
|
||||
INNER JOIN dbo.Applications AS a ON a.Id = ap.ApplicationId
|
||||
WHERE ap.PackageId = @PackageId
|
||||
UNION
|
||||
SELECT CreatedByUserId FROM dbo.Packages WHERE Id = @PackageId
|
||||
UNION
|
||||
SELECT Id FROM dbo.Users WHERE Role = N'Admin'
|
||||
) AS recipients;
|
||||
`);
|
||||
const packageRow = result.recordsets[0][0];
|
||||
if (!packageRow) return null;
|
||||
|
||||
return {
|
||||
packageId: String(packageRow.Id),
|
||||
packageCode: packageRow.PackageCode,
|
||||
packageName: packageRow.PackageName,
|
||||
recipientUserIds: result.recordsets[1].map((row) => String(row.UserId))
|
||||
};
|
||||
}
|
||||
|
||||
async function getPackageVersionDeletionContext(packageVersionId) {
|
||||
if (!await checkNotificationSchema()) return null;
|
||||
|
||||
const pool = await getPool();
|
||||
const result = await pool.request()
|
||||
.input('PackageVersionId', sql.UniqueIdentifier, packageVersionId)
|
||||
.query(`
|
||||
SELECT TOP (1)
|
||||
pv.Id, pv.PackageId, pv.Version, p.PackageCode, p.PackageName, p.CreatedByUserId
|
||||
FROM dbo.PackageVersions AS pv
|
||||
INNER JOIN dbo.Packages AS p ON p.Id = pv.PackageId
|
||||
WHERE pv.Id = @PackageVersionId;
|
||||
|
||||
SELECT DISTINCT recipients.UserId
|
||||
FROM (
|
||||
SELECT a.CreatedByUserId AS UserId
|
||||
FROM dbo.ApplicationPackages AS ap
|
||||
INNER JOIN dbo.Applications AS a ON a.Id = ap.ApplicationId
|
||||
WHERE ap.SelectedVersionId = @PackageVersionId
|
||||
UNION
|
||||
SELECT p.CreatedByUserId
|
||||
FROM dbo.PackageVersions AS pv
|
||||
INNER JOIN dbo.Packages AS p ON p.Id = pv.PackageId
|
||||
WHERE pv.Id = @PackageVersionId
|
||||
UNION
|
||||
SELECT Id FROM dbo.Users WHERE Role = N'Admin'
|
||||
) AS recipients;
|
||||
`);
|
||||
const versionRow = result.recordsets[0][0];
|
||||
if (!versionRow) return null;
|
||||
|
||||
return {
|
||||
packageVersionId: String(versionRow.Id),
|
||||
packageId: String(versionRow.PackageId),
|
||||
packageCode: versionRow.PackageCode,
|
||||
packageName: versionRow.PackageName,
|
||||
version: versionRow.Version,
|
||||
recipientUserIds: result.recordsets[1].map((row) => String(row.UserId))
|
||||
};
|
||||
}
|
||||
|
||||
async function getApplicationReleaseContext(applicationId) {
|
||||
if (!await checkNotificationSchema()) return null;
|
||||
|
||||
const pool = await getPool();
|
||||
const result = await pool.request()
|
||||
.input('ApplicationId', sql.UniqueIdentifier, applicationId)
|
||||
.query(`
|
||||
SELECT TOP (1) Id, AppCode, AppName, AppVersion, CreatedByUserId
|
||||
FROM dbo.Applications
|
||||
WHERE Id = @ApplicationId;
|
||||
|
||||
SELECT DISTINCT recipients.UserId
|
||||
FROM (
|
||||
SELECT CreatedByUserId AS UserId
|
||||
FROM dbo.Applications
|
||||
WHERE Id = @ApplicationId
|
||||
UNION
|
||||
SELECT Id FROM dbo.Users WHERE Role = N'Admin'
|
||||
) AS recipients;
|
||||
`);
|
||||
const applicationRow = result.recordsets[0][0];
|
||||
if (!applicationRow) return null;
|
||||
|
||||
return {
|
||||
applicationId: String(applicationRow.Id),
|
||||
appCode: applicationRow.AppCode,
|
||||
appName: applicationRow.AppName,
|
||||
appVersion: applicationRow.AppVersion,
|
||||
recipientUserIds: result.recordsets[1].map((row) => String(row.UserId))
|
||||
};
|
||||
}
|
||||
|
||||
async function notifyApplicationReleased(input) {
|
||||
const context = await getApplicationReleaseContext(input.applicationId);
|
||||
if (!context) {
|
||||
return {
|
||||
available: await checkNotificationSchema(),
|
||||
recipientCount: 0
|
||||
};
|
||||
}
|
||||
|
||||
return createNotificationsForUsers({
|
||||
recipientUserIds: context.recipientUserIds,
|
||||
actorUserId: input.actorUserId,
|
||||
actorName: input.actorName,
|
||||
eventType: 'application.released',
|
||||
severity: 'success',
|
||||
title: `Application ${context.appCode} đã được release`,
|
||||
message: `Version ${context.appVersion} đã chuyển sang trạng thái Released.`,
|
||||
entityType: 'application',
|
||||
entityId: context.applicationId,
|
||||
actionUrl: `/applications/${context.applicationId}`
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
checkNotificationSchema,
|
||||
createNotificationsForUsers,
|
||||
createSystemBroadcast,
|
||||
getApplicationReleaseContext,
|
||||
getPackageImpact: getPackageDeletionContext,
|
||||
getPackageDeletionContext,
|
||||
getPackageVersionAudience,
|
||||
getPackageVersionImpact: getPackageVersionDeletionContext,
|
||||
getPackageVersionDeletionContext,
|
||||
getUnreadCount,
|
||||
listNotifications,
|
||||
markAllNotificationsRead,
|
||||
markNotificationRead: (userId, notificationId) => markNotificationRead(notificationId, userId),
|
||||
notifyApplicationReleased,
|
||||
notifyPackageVersionAvailable
|
||||
};
|
||||
@@ -55,6 +55,56 @@
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<% if (currentUser && currentUser.role === 'Admin') { %>
|
||||
<div id="systemNotificationModal" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="systemNotificationModalTitle">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<div>
|
||||
<h3 id="systemNotificationModalTitle">Đăng thông báo hệ thống</h3>
|
||||
<p>Thông báo sẽ được gửi tới tất cả tài khoản đang hoạt động.</p>
|
||||
</div>
|
||||
<button class="icon-button subtle" type="button" data-modal-close aria-label="Đóng">
|
||||
<span class="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
<form class="modal-form" data-system-notification-form>
|
||||
<div class="form-stack">
|
||||
<label class="form-field">
|
||||
<span>Tiêu đề</span>
|
||||
<input type="text" name="title" maxlength="200" required placeholder="Ví dụ: Hệ thống đã cập nhật phiên bản 1.2.0">
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Mức độ</span>
|
||||
<select name="severity" required>
|
||||
<option value="info">Thông tin</option>
|
||||
<option value="success">Cập nhật thành công</option>
|
||||
<option value="warning">Quan trọng / bảo trì</option>
|
||||
<option value="error">Khẩn cấp / sự cố</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Nội dung</span>
|
||||
<textarea name="message" rows="6" maxlength="1000" required placeholder="Mô tả nội dung cập nhật, ảnh hưởng và việc người dùng cần thực hiện."></textarea>
|
||||
<small>Tối đa 1000 ký tự. Không nhập mật khẩu, token hoặc thông tin nhạy cảm.</small>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Đường dẫn nội bộ (không bắt buộc)</span>
|
||||
<input type="text" name="actionUrl" maxlength="1000" placeholder="Ví dụ: /applications hoặc /agent">
|
||||
<small>Chỉ chấp nhận đường dẫn trong website bắt đầu bằng dấu /.</small>
|
||||
</label>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||
<button class="btn btn-primary" type="submit" data-system-notification-submit>
|
||||
<span class="material-symbols-outlined">send</span>
|
||||
Gửi cho mọi người
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<script src="/vendor/notiflix/notiflix-<%= notiflixVersion %>.min.js"></script>
|
||||
<script src="/js/app.js"></script>
|
||||
</body>
|
||||
|
||||
@@ -52,9 +52,52 @@
|
||||
<button class="icon-button" type="button" title="Đồng bộ dữ liệu" data-refresh-page>
|
||||
<span class="material-symbols-outlined">sync</span>
|
||||
</button>
|
||||
<button class="icon-button" type="button" title="Thông báo" data-toast="Chưa có thông báo mới">
|
||||
<span class="material-symbols-outlined">notifications</span>
|
||||
</button>
|
||||
<div class="notification-center" data-notification-center>
|
||||
<button
|
||||
id="notificationButton"
|
||||
class="icon-button notification-button"
|
||||
type="button"
|
||||
title="Thông báo"
|
||||
aria-label="Mở thông báo"
|
||||
aria-controls="notificationPanel"
|
||||
aria-expanded="false"
|
||||
data-notification-toggle
|
||||
>
|
||||
<span class="material-symbols-outlined">notifications</span>
|
||||
<span class="notification-badge" data-notification-badge hidden>0</span>
|
||||
</button>
|
||||
|
||||
<section id="notificationPanel" class="notification-panel" aria-label="Thông báo" hidden data-notification-panel>
|
||||
<div class="notification-panel-header">
|
||||
<div>
|
||||
<strong>Thông báo</strong>
|
||||
<span data-notification-summary>Đang tải...</span>
|
||||
</div>
|
||||
<button class="text-button" type="button" data-notification-read-all>Đánh dấu đã đọc</button>
|
||||
</div>
|
||||
|
||||
<div class="notification-tabs" role="tablist" aria-label="Lọc thông báo">
|
||||
<button class="active" type="button" role="tab" aria-selected="true" data-notification-filter="all">Tất cả</button>
|
||||
<button type="button" role="tab" aria-selected="false" data-notification-filter="unread">Chưa đọc</button>
|
||||
</div>
|
||||
|
||||
<div class="notification-list" data-notification-list></div>
|
||||
<div class="notification-empty" data-notification-empty hidden>
|
||||
<span class="material-symbols-outlined">notifications_none</span>
|
||||
<strong>Chưa có thông báo</strong>
|
||||
<span>Các cập nhật quan trọng sẽ xuất hiện tại đây.</span>
|
||||
</div>
|
||||
|
||||
<% if (currentUser.role === 'Admin') { %>
|
||||
<div class="notification-panel-footer">
|
||||
<button class="btn btn-primary" type="button" data-modal-open="systemNotificationModal">
|
||||
<span class="material-symbols-outlined">campaign</span>
|
||||
Đăng thông báo hệ thống
|
||||
</button>
|
||||
</div>
|
||||
<% } %>
|
||||
</section>
|
||||
</div>
|
||||
<% if (currentUser.role === 'User') { %>
|
||||
<button class="profile-chip profile-chip-button" type="button" title="Cập nhật thông tin cá nhân" aria-label="Cập nhật thông tin cá nhân" data-modal-open="profileModal">
|
||||
<span class="profile-avatar"><%= currentUser.name.charAt(0) %></span>
|
||||
|
||||
Reference in New Issue
Block a user