notification
This commit is contained in:
@@ -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
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user