Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x | const express = require('express');
const pool = require('../config/database');
const { authenticate } = require('../middleware/auth');
const { body, validationResult } = require('express-validator');
const router = express.Router();
// Create notification (for supervisors and administrators)
router.post('/', authenticate, [
body('user_id').isInt().withMessage('User ID must be an integer'),
body('title').trim().notEmpty().withMessage('Title is required'),
body('message').trim().notEmpty().withMessage('Message is required'),
body('type').optional().isString(),
body('icon').optional().isString(),
body('link').optional().isString()
], async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { user_id, title, message, type, icon, link } = req.body;
const currentUser = req.user;
// Only supervisors and administrators can create notifications
if (currentUser.role !== 'supervisor' && currentUser.role !== 'administrator') {
return res.status(403).json({ error: 'Only supervisors and administrators can create notifications' });
}
// If supervisor, verify they have access to this student
if (currentUser.role === 'supervisor') {
const [supervisor] = await pool.query(
'SELECT id FROM supervisors WHERE user_id = ?',
[currentUser.id]
);
if (supervisor.length === 0) {
return res.status(403).json({ error: 'Supervisor record not found' });
}
// Check if student is assigned to this supervisor
const [student] = await pool.query(
'SELECT id FROM students WHERE user_id = ?',
[user_id]
);
if (student.length === 0) {
return res.status(404).json({ error: 'Student not found' });
}
// Check supervisor-student relationship
const [relationship] = await pool.query(
'SELECT id FROM supervisor_student WHERE supervisor_id = ? AND student_id = ?',
[supervisor[0].id, student[0].id]
);
// Also check direct supervisor_id in students table
const [directRelation] = await pool.query(
'SELECT id FROM students WHERE id = ? AND supervisor_id = ?',
[student[0].id, supervisor[0].id]
);
if (relationship.length === 0 && directRelation.length === 0) {
return res.status(403).json({ error: 'Access denied. Student is not assigned to you.' });
}
}
// Create notification
const [result] = await pool.query(
`INSERT INTO notifications (user_id, title, message, type, icon, link, unread)
VALUES (?, ?, ?, ?, ?, ?, TRUE)`,
[user_id, title, message, type || 'reminder', icon || '🔔', link || null]
);
res.status(201).json({
message: 'Notification sent successfully',
notification: {
id: result.insertId,
user_id,
title,
message,
type: type || 'reminder',
icon: icon || '🔔'
}
});
} catch (error) {
console.error('Create notification error:', error);
res.status(500).json({ error: 'Failed to create notification' });
}
});
// Get all notifications for current user
router.get('/', authenticate, async (req, res) => {
try {
const { unread_only } = req.query;
const userId = req.user.id;
let query = 'SELECT * FROM notifications WHERE user_id = ?';
const params = [userId];
if (unread_only === 'true') {
query += ' AND unread = TRUE';
}
query += ' ORDER BY created_at DESC LIMIT 100';
const [notifications] = await pool.query(query, params);
// Get unread count
const [unreadCount] = await pool.query(
'SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND unread = TRUE',
[userId]
);
res.json({
notifications,
unreadCount: unreadCount[0].count
});
} catch (error) {
console.error('Get notifications error:', error);
res.status(500).json({ error: 'Failed to fetch notifications' });
}
});
// Mark notification as read
router.put('/:id/read', authenticate, async (req, res) => {
try {
const notificationId = parseInt(req.params.id);
const userId = req.user.id;
const [result] = await pool.query(
'UPDATE notifications SET unread = FALSE WHERE id = ? AND user_id = ?',
[notificationId, userId]
);
if (result.affectedRows === 0) {
return res.status(404).json({ error: 'Notification not found' });
}
res.json({ message: 'Notification marked as read' });
} catch (error) {
console.error('Mark notification as read error:', error);
res.status(500).json({ error: 'Failed to mark notification as read' });
}
});
// Mark all notifications as read
router.put('/read-all', authenticate, async (req, res) => {
try {
const userId = req.user.id;
await pool.query(
'UPDATE notifications SET unread = FALSE WHERE user_id = ?',
[userId]
);
res.json({ message: 'All notifications marked as read' });
} catch (error) {
console.error('Mark all notifications as read error:', error);
res.status(500).json({ error: 'Failed to mark all notifications as read' });
}
});
// Delete notification
router.delete('/:id', authenticate, async (req, res) => {
try {
const notificationId = parseInt(req.params.id);
const userId = req.user.id;
const [result] = await pool.query(
'DELETE FROM notifications WHERE id = ? AND user_id = ?',
[notificationId, userId]
);
if (result.affectedRows === 0) {
return res.status(404).json({ error: 'Notification not found' });
}
res.json({ message: 'Notification deleted successfully' });
} catch (error) {
console.error('Delete notification error:', error);
res.status(500).json({ error: 'Failed to delete notification' });
}
});
// Delete all notifications
router.delete('/', authenticate, async (req, res) => {
try {
const userId = req.user.id;
await pool.query(
'DELETE FROM notifications WHERE user_id = ?',
[userId]
);
res.json({ message: 'All notifications deleted successfully' });
} catch (error) {
console.error('Delete all notifications error:', error);
res.status(500).json({ error: 'Failed to delete all notifications' });
}
});
module.exports = router;
|