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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x | const express = require('express');
const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const pool = require('../config/database');
const { authenticate, authorize } = require('../middleware/auth');
const { sendVerificationEmail } = require('../services/emailService');
const router = express.Router();
// Get all supervisors
router.get('/', authenticate, async (req, res) => {
try {
const { department, search, status } = req.query;
const currentUser = req.user;
let query = `
SELECT
s.id, s.user_id, s.department, s.office, s.office_hours,
s.research_interests, s.capacity,
COALESCE(COUNT(DISTINCT ss.student_id), 0) as current_students,
u.name, u.email, u.phone, u.avatar, u.status as user_status
FROM supervisors s
JOIN users u ON s.user_id = u.id
LEFT JOIN supervisor_student ss ON s.id = ss.supervisor_id
WHERE 1=1
`;
const params = [];
// Filter by status if provided, otherwise only filter by active status for non-admin users
if (status) {
query += ' AND u.status = ?';
params.push(status);
} else if (currentUser.role !== 'administrator') {
query += ' AND u.status = ?';
params.push('active');
}
if (department) {
query += ' AND s.department = ?';
params.push(department);
}
if (search) {
query += ' AND (u.name LIKE ? OR u.email LIKE ? OR s.department LIKE ?)';
const searchTerm = `%${search}%`;
params.push(searchTerm, searchTerm, searchTerm);
}
query += ' GROUP BY s.id, s.user_id, s.department, s.office, s.office_hours, s.research_interests, s.capacity, u.name, u.email, u.phone, u.avatar, u.status';
query += ' ORDER BY u.name ASC';
const [supervisors] = await pool.query(query, params);
res.json({ supervisors });
} catch (error) {
console.error('Get supervisors error:', error);
res.status(500).json({ error: 'Failed to fetch supervisors' });
}
});
// Get supervisor by ID
router.get('/:id', authenticate, async (req, res) => {
try {
const supervisorId = parseInt(req.params.id);
const [supervisors] = await pool.query(
`SELECT
s.*, u.name, u.email, u.phone, u.avatar, u.status as user_status
FROM supervisors s
JOIN users u ON s.user_id = u.id
WHERE s.id = ?`,
[supervisorId]
);
if (supervisors.length === 0) {
return res.status(404).json({ error: 'Supervisor not found' });
}
// Get students (using supervisor_student table for many-to-many relationship)
const [students] = await pool.query(
`SELECT
st.id, st.user_id, st.program, st.progress,
u.name, u.email, u.avatar
FROM students st
JOIN users u ON st.user_id = u.id
JOIN supervisor_student ss ON st.id = ss.student_id
WHERE ss.supervisor_id = ?
ORDER BY u.name ASC`,
[supervisorId]
);
res.json({
supervisor: {
...supervisors[0],
students
}
});
} catch (error) {
console.error('Get supervisor error:', error);
res.status(500).json({ error: 'Failed to fetch supervisor' });
}
});
// Update supervisor
router.put('/:id', authenticate, async (req, res) => {
try {
const supervisorId = parseInt(req.params.id);
const currentUser = req.user;
const { department, office, office_hours, research_interests, capacity, position, qualifications, biography } = req.body;
// Check access
if (currentUser.role === 'supervisor') {
const [supervisor] = await pool.query(
'SELECT id FROM supervisors WHERE user_id = ?',
[currentUser.id]
);
if (supervisor.length === 0 || supervisor[0].id !== supervisorId) {
return res.status(403).json({ error: 'Access denied' });
}
}
const updates = [];
const params = [];
if (department !== undefined) {
updates.push('department = ?');
params.push(department);
}
if (office !== undefined) {
updates.push('office = ?');
params.push(office);
}
if (office_hours !== undefined) {
updates.push('office_hours = ?');
params.push(office_hours);
}
if (research_interests !== undefined) {
updates.push('research_interests = ?');
params.push(research_interests);
}
if (position !== undefined) {
updates.push('position = ?');
params.push(position);
}
if (qualifications !== undefined) {
updates.push('qualifications = ?');
params.push(qualifications);
}
if (biography !== undefined) {
updates.push('biography = ?');
params.push(biography);
}
if (capacity !== undefined && currentUser.role === 'administrator') {
// Check if new capacity is less than current students
const [supervisor] = await pool.query(
'SELECT current_students FROM supervisors WHERE id = ?',
[supervisorId]
);
if (supervisor.length > 0 && capacity < supervisor[0].current_students) {
return res.status(400).json({
error: `Capacity cannot be less than current student count (${supervisor[0].current_students})`
});
}
updates.push('capacity = ?');
params.push(capacity);
}
if (updates.length === 0) {
return res.status(400).json({ error: 'No fields to update' });
}
params.push(supervisorId);
await pool.query(
`UPDATE supervisors SET ${updates.join(', ')} WHERE id = ?`,
params
);
res.json({ message: 'Supervisor updated successfully' });
} catch (error) {
console.error('Update supervisor error:', error);
res.status(500).json({ error: 'Failed to update supervisor' });
}
});
// Add student to supervisor (supervisor can add students under their supervision)
router.post('/add-student', authenticate, async (req, res) => {
try {
const currentUser = req.user;
// Only supervisors can add students
if (currentUser.role !== 'supervisor') {
return res.status(403).json({ error: 'Only supervisors can add students' });
}
const { email, phone } = req.body;
if (!email && !phone) {
return res.status(400).json({ error: 'Email or phone number is required' });
}
// Get supervisor ID
const [supervisor] = await pool.query(
'SELECT id, capacity, current_students FROM supervisors WHERE user_id = ?',
[currentUser.id]
);
if (supervisor.length === 0) {
return res.status(404).json({ error: 'Supervisor record not found' });
}
const supervisorId = supervisor[0].id;
const capacity = supervisor[0].capacity;
const currentStudents = supervisor[0].current_students;
// Check capacity
if (currentStudents >= capacity) {
return res.status(400).json({
error: 'You have reached your maximum student capacity. Please contact admin to increase capacity.'
});
}
// Find student by email or phone
let studentQuery = `
SELECT s.id, s.user_id, u.name, u.email, u.phone
FROM students s
JOIN users u ON s.user_id = u.id
WHERE u.role = 'student' AND u.status = 'active'
`;
const studentParams = [];
if (email) {
studentQuery += ' AND u.email = ?';
studentParams.push(email);
} else if (phone) {
studentQuery += ' AND u.phone = ?';
studentParams.push(phone);
}
const [students] = await pool.query(studentQuery, studentParams);
if (students.length === 0) {
return res.status(404).json({
error: 'Student not found. The user is not registered in the system.'
});
}
const student = students[0];
// Check if relationship already exists
const [existing] = await pool.query(
'SELECT id FROM supervisor_student WHERE supervisor_id = ? AND student_id = ?',
[supervisorId, student.id]
);
if (existing.length > 0) {
return res.status(400).json({
error: 'This student is already under your supervision.'
});
}
// Create relationship in supervisor_student table
await pool.query(
'INSERT INTO supervisor_student (supervisor_id, student_id) VALUES (?, ?)',
[supervisorId, student.id]
);
// Update supervisor's current_students count
await pool.query(
'UPDATE supervisors SET current_students = current_students + 1 WHERE id = ?',
[supervisorId]
);
res.json({
message: 'Student added successfully',
student: {
id: student.id,
name: student.name,
email: student.email,
phone: student.phone
}
});
} catch (error) {
console.error('Add student error:', error);
// Handle duplicate entry error
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({ error: 'This student is already under your supervision.' });
}
res.status(500).json({ error: 'Failed to add student' });
}
});
// Remove student from supervisor (supervisor can remove students from their supervision)
router.delete('/remove-student/:student_id', authenticate, async (req, res) => {
try {
const currentUser = req.user;
// Only supervisors can remove students
if (currentUser.role !== 'supervisor') {
return res.status(403).json({ error: 'Only supervisors can remove students' });
}
const studentId = parseInt(req.params.student_id);
if (!studentId || isNaN(studentId)) {
return res.status(400).json({ error: 'Invalid student ID' });
}
// Get supervisor ID
const [supervisor] = await pool.query(
'SELECT id FROM supervisors WHERE user_id = ?',
[currentUser.id]
);
if (supervisor.length === 0) {
return res.status(404).json({ error: 'Supervisor record not found' });
}
const supervisorId = supervisor[0].id;
// Check if relationship exists
const [existing] = await pool.query(
'SELECT id FROM supervisor_student WHERE supervisor_id = ? AND student_id = ?',
[supervisorId, studentId]
);
if (existing.length === 0) {
return res.status(404).json({ error: 'This student is not under your supervision' });
}
// Remove relationship from supervisor_student table
await pool.query(
'DELETE FROM supervisor_student WHERE supervisor_id = ? AND student_id = ?',
[supervisorId, studentId]
);
// If student's direct supervisor_id matches, set it to NULL
const [student] = await pool.query(
'SELECT supervisor_id FROM students WHERE id = ?',
[studentId]
);
if (student.length > 0 && student[0].supervisor_id === supervisorId) {
await pool.query(
'UPDATE students SET supervisor_id = NULL WHERE id = ?',
[studentId]
);
}
// Update supervisor's current_students count
await pool.query(
'UPDATE supervisors SET current_students = GREATEST(0, current_students - 1) WHERE id = ?',
[supervisorId]
);
res.json({
message: 'Student removed from supervision successfully'
});
} catch (error) {
console.error('Remove student error:', error);
res.status(500).json({ error: 'Failed to remove student' });
}
});
// Create new student account (supervisor can create new student accounts)
router.post('/create-student', authenticate, async (req, res) => {
try {
const currentUser = req.user;
// Only supervisors can create students
if (currentUser.role !== 'supervisor') {
return res.status(403).json({ error: 'Only supervisors can create student accounts' });
}
const { email, password, name, phone, program } = req.body;
// Validation
if (!email || !password || !name) {
return res.status(400).json({ error: 'Email, password, and name are required' });
}
if (password.length < 6) {
return res.status(400).json({ error: 'Password must be at least 6 characters long' });
}
// Get supervisor ID
const [supervisor] = await pool.query(
'SELECT id, capacity, current_students FROM supervisors WHERE user_id = ?',
[currentUser.id]
);
if (supervisor.length === 0) {
return res.status(404).json({ error: 'Supervisor record not found' });
}
const supervisorId = supervisor[0].id;
const capacity = supervisor[0].capacity;
const currentStudents = supervisor[0].current_students;
// Check capacity
if (currentStudents >= capacity) {
return res.status(400).json({
error: 'You have reached your maximum student capacity. Please contact admin to increase capacity.'
});
}
// Check if user already exists
const [existingUsers] = await pool.query(
'SELECT id FROM users WHERE email = ?',
[email]
);
if (existingUsers.length > 0) {
return res.status(400).json({ error: 'User with this email already exists' });
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// Generate verification token
const verificationToken = crypto.randomBytes(32).toString('hex');
const expiresAt = new Date();
expiresAt.setHours(expiresAt.getHours() + 24); // Token expires in 24 hours
// Start transaction
const connection = await pool.getConnection();
await connection.beginTransaction();
try {
// Insert user with email_verified = false and status = 'inactive' (requires email verification)
const [userResult] = await connection.query(
'INSERT INTO users (email, password, name, role, phone, status, email_verified) VALUES (?, ?, ?, ?, ?, ?, ?)',
[email, hashedPassword, name, 'student', phone || null, 'inactive', false]
);
const userId = userResult.insertId;
// Insert student record
await connection.query(
'INSERT INTO students (user_id, program, enrollment_date) VALUES (?, ?, CURDATE())',
[userId, program || null]
);
// Get the student ID
const [studentResult] = await connection.query(
'SELECT id FROM students WHERE user_id = ?',
[userId]
);
const studentId = studentResult[0].id;
// Create relationship in supervisor_student table
await connection.query(
'INSERT INTO supervisor_student (supervisor_id, student_id) VALUES (?, ?)',
[supervisorId, studentId]
);
// Update supervisor's current_students count
await connection.query(
'UPDATE supervisors SET current_students = current_students + 1 WHERE id = ?',
[supervisorId]
);
// Insert verification token
await connection.query(
'INSERT INTO email_verification_tokens (user_id, email, token, expires_at) VALUES (?, ?, ?, ?)',
[userId, email, verificationToken, expiresAt]
);
await connection.commit();
connection.release();
// Send verification email
try {
await sendVerificationEmail(email, name, verificationToken);
} catch (emailError) {
console.error('Failed to send verification email:', emailError);
// Don't fail account creation if email fails, but log it
}
res.json({
message: 'Student account created successfully! A verification email has been sent to the student.',
emailSent: true,
student: {
id: studentId,
user_id: userId,
name,
email,
phone: phone || null,
program: program || null
}
});
} catch (error) {
await connection.rollback();
connection.release();
throw error;
}
} catch (error) {
console.error('Create student error:', error);
// Handle duplicate entry error
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({ error: 'This student is already under your supervision.' });
}
res.status(500).json({ error: 'Failed to create student account' });
}
});
module.exports = router;
|