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 514 515 516 517 518 | 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 2x 1x 1x 3x 3x 3x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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();
// Get all meetings
router.get('/', authenticate, async (req, res) => {
try {
const { student_id, supervisor_id, status, date_from, date_to } = req.query;
const currentUser = req.user;
let query = `
SELECT
m.*,
s.user_id as student_user_id,
u_student.name as student_name,
u_student.email as student_email,
sup.user_id as supervisor_user_id,
u_supervisor.name as supervisor_name,
u_supervisor.email as supervisor_email
FROM meetings m
JOIN students s ON m.student_id = s.id
JOIN users u_student ON s.user_id = u_student.id
JOIN supervisors sup ON m.supervisor_id = sup.id
JOIN users u_supervisor ON sup.user_id = u_supervisor.id
WHERE 1=1
`;
const params = [];
// Filter by role
if (currentUser.role === 'student') {
const [student] = await pool.query(
'SELECT id FROM students WHERE user_id = ?',
[currentUser.id]
);
if (student.length > 0) {
query += ' AND m.student_id = ?';
params.push(student[0].id);
} else E{
return res.json({ meetings: [] });
}
} else Eif (currentUser.role === 'supervisor') {
const [supervisor] = await pool.query(
'SELECT id FROM supervisors WHERE user_id = ?',
[currentUser.id]
);
if (supervisor.length > 0) {
query += ' AND m.supervisor_id = ?';
params.push(supervisor[0].id);
} else {
return res.json({ meetings: [] });
}
}
Iif (student_id) {
query += ' AND m.student_id = ?';
params.push(student_id);
}
Iif (supervisor_id) {
query += ' AND m.supervisor_id = ?';
params.push(supervisor_id);
}
Iif (status) {
query += ' AND m.status = ?';
params.push(status);
}
Iif (date_from) {
query += ' AND m.date >= ?';
params.push(date_from);
}
Iif (date_to) {
query += ' AND m.date <= ?';
params.push(date_to);
}
query += ' ORDER BY m.date DESC, m.time DESC';
const [meetings] = await pool.query(query, params);
// Automatically mark meetings as completed if date/time has passed
const now = new Date()
for (const meeting of meetings) {
if (meeting.status !== 'completed' && meeting.status !== 'cancelled') {
const meetingDateTime = new Date(`${meeting.date} ${meeting.time}`)
// Mark as completed if meeting date/time has passed
if (meetingDateTime < now) {
await pool.query(
'UPDATE meetings SET status = ? WHERE id = ?',
['completed', meeting.id]
)
meeting.status = 'completed'
}
}
}
res.json({ meetings });
} catch (error) {
console.error('Get meetings error:', error);
res.status(500).json({ error: 'Failed to fetch meetings' });
}
});
// Get meeting by ID
router.get('/:id', authenticate, async (req, res) => {
try {
const meetingId = parseInt(req.params.id);
const [meetings] = await pool.query(
`SELECT
m.*,
s.user_id as student_user_id,
u_student.name as student_name,
u_student.email as student_email,
sup.user_id as supervisor_user_id,
u_supervisor.name as supervisor_name,
u_supervisor.email as supervisor_email
FROM meetings m
JOIN students s ON m.student_id = s.id
JOIN users u_student ON s.user_id = u_student.id
JOIN supervisors sup ON m.supervisor_id = sup.id
JOIN users u_supervisor ON sup.user_id = u_supervisor.id
WHERE m.id = ?`,
[meetingId]
);
if (meetings.length === 0) {
return res.status(404).json({ error: 'Meeting not found' });
}
res.json({ meeting: meetings[0] });
} catch (error) {
console.error('Get meeting error:', error);
res.status(500).json({ error: 'Failed to fetch meeting' });
}
});
// Create meeting
router.post('/', authenticate, [
body('student_id').optional().isInt(),
body('title').trim().notEmpty(),
body('date').isISO8601(),
body('time').matches(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/),
body('duration').optional().isInt({ min: 15, max: 480 })
], async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const currentUser = req.user;
const { student_id, supervisor_id, title, date, time, duration, type, location, meeting_link, agenda } = req.body;
let finalSupervisorId = supervisor_id;
let finalStudentId = student_id;
// Determine IDs based on role
if (currentUser.role === 'student') {
const [student] = await pool.query(
'SELECT id FROM students WHERE user_id = ?',
[currentUser.id]
);
Iif (student.length === 0) {
return res.status(404).json({ error: 'Student record not found' });
}
finalStudentId = student[0].id;
Eif (!supervisor_id) {
// Check if student has a supervisor via students.supervisor_id
const [studentData] = await pool.query(
'SELECT supervisor_id FROM students WHERE id = ?',
[finalStudentId]
);
Iif (studentData.length === 0) {
return res.status(404).json({ error: 'Student record not found' });
}
// If student has supervisor_id, use it
if (studentData[0].supervisor_id) {
finalSupervisorId = studentData[0].supervisor_id;
} else E{
// Check supervisor_student table for supervisor relationships
const [supervisorRelations] = await pool.query(
'SELECT supervisor_id FROM supervisor_student WHERE student_id = ? LIMIT 1',
[finalStudentId]
);
if (supervisorRelations.length === 0) {
return res.status(400).json({
error: 'You do not have a supervisor assigned yet. Please wait for a supervisor to add you to their supervision before creating meetings.'
});
}
finalSupervisorId = supervisorRelations[0].supervisor_id;
}
}
} else Eif (currentUser.role === 'supervisor') {
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' });
}
finalSupervisorId = supervisor[0].id;
if (!student_id) {
return res.status(400).json({ error: 'Student ID is required' });
}
}
const [result] = await pool.query(
`INSERT INTO meetings
(student_id, supervisor_id, title, date, time, duration, type, location, meeting_link, agenda, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')`,
[
finalStudentId,
finalSupervisorId,
title,
date,
time,
duration || 60,
type || 'online',
location || null,
meeting_link || null,
agenda || null
]
);
// Create notification
const [student] = await pool.query(
'SELECT user_id FROM students WHERE id = ?',
[finalStudentId]
);
const [supervisor] = await pool.query(
'SELECT user_id FROM supervisors WHERE id = ?',
[finalSupervisorId]
);
if (currentUser.role === 'student' && supervisor.length > 0) {
await pool.query(
'INSERT INTO notifications (user_id, title, message, type, icon, link) VALUES (?, ?, ?, ?, ?, ?)',
[
supervisor[0].user_id,
'New Meeting Request',
`${currentUser.name} has requested a meeting: ${title}`,
'meeting',
'📅',
'/supervisor/meetings'
]
);
} else Eif (currentUser.role === 'supervisor' && student.length > 0) {
await pool.query(
'INSERT INTO notifications (user_id, title, message, type, icon, link) VALUES (?, ?, ?, ?, ?, ?)',
[
student[0].user_id,
'Meeting Scheduled',
`${currentUser.name} has scheduled a meeting: ${title}`,
'meeting',
'📅',
'/student/meetings'
]
);
}
res.status(201).json({
message: 'Meeting created successfully',
meeting: { id: result.insertId }
});
} catch (error) {
console.error('Create meeting error:', error);
res.status(500).json({ error: 'Failed to create meeting' });
}
});
// Update meeting
router.put('/:id', authenticate, async (req, res) => {
try {
const meetingId = parseInt(req.params.id);
const currentUser = req.user;
const { title, date, time, duration, type, location, meeting_link, agenda, status, notes } = req.body;
// Get meeting
const [meetings] = await pool.query(
'SELECT * FROM meetings WHERE id = ?',
[meetingId]
);
Iif (meetings.length === 0) {
return res.status(404).json({ error: 'Meeting not found' });
}
const meeting = meetings[0];
// Check access
if (currentUser.role === 'student') {
const [student] = await pool.query(
'SELECT id FROM students WHERE user_id = ?',
[currentUser.id]
);
Iif (student.length === 0 || student[0].id !== meeting.student_id) {
return res.status(403).json({ error: 'Access denied' });
}
} else Eif (currentUser.role === 'supervisor') {
const [supervisor] = await pool.query(
'SELECT id FROM supervisors WHERE user_id = ?',
[currentUser.id]
);
if (supervisor.length === 0 || supervisor[0].id !== meeting.supervisor_id) {
return res.status(403).json({ error: 'Access denied' });
}
}
const updates = [];
const params = [];
Eif (title !== undefined) {
updates.push('title = ?');
params.push(title);
}
Iif (date !== undefined) {
updates.push('date = ?');
params.push(date);
}
Iif (time !== undefined) {
updates.push('time = ?');
params.push(time);
}
Iif (duration !== undefined) {
updates.push('duration = ?');
params.push(duration);
}
Iif (type !== undefined) {
updates.push('type = ?');
params.push(type);
}
Iif (location !== undefined) {
updates.push('location = ?');
params.push(location);
}
Iif (meeting_link !== undefined) {
updates.push('meeting_link = ?');
params.push(meeting_link);
}
Iif (agenda !== undefined) {
updates.push('agenda = ?');
params.push(agenda);
}
Iif (status !== undefined) {
updates.push('status = ?');
params.push(status);
}
Iif (notes !== undefined) {
updates.push('notes = ?');
params.push(notes);
}
Iif (updates.length === 0) {
return res.status(400).json({ error: 'No fields to update' });
}
params.push(meetingId);
await pool.query(
`UPDATE meetings SET ${updates.join(', ')} WHERE id = ?`,
params
);
// Create notification if status changed or meeting was rescheduled
const wasRescheduled = (date !== undefined && date !== meeting.date) || (time !== undefined && time !== meeting.time);
Iif (status && status !== meeting.status) {
const [student] = await pool.query(
'SELECT user_id FROM students WHERE id = ?',
[meeting.student_id]
);
const [supervisor] = await pool.query(
'SELECT user_id FROM supervisors WHERE id = ?',
[meeting.supervisor_id]
);
const targetUserId = currentUser.role === 'student'
? supervisor[0]?.user_id
: student[0]?.user_id;
const targetRole = currentUser.role === 'student' ? 'supervisor' : 'student'
const link = `/${targetRole}/meetings`
if (targetUserId) {
let statusMessage = `Meeting "${meeting.title}" status changed to ${status}`
if (status === 'approved') {
statusMessage = `Your meeting request "${meeting.title}" has been approved`
} else if (status === 'confirmed') {
statusMessage = `Meeting "${meeting.title}" has been confirmed`
} else if (status === 'completed') {
statusMessage = `Meeting "${meeting.title}" has been marked as completed`
} else if (status === 'cancelled') {
statusMessage = `Meeting "${meeting.title}" has been cancelled`
} else if (status === 'pending' && currentUser.role === 'student') {
// Student rescheduled - meeting back to pending
const newDate = date || meeting.date;
const newTime = time || meeting.time;
statusMessage = `${currentUser.name} has rescheduled the meeting "${meeting.title}" to ${newDate} at ${newTime}. Please review and approve.`
}
await pool.query(
'INSERT INTO notifications (user_id, title, message, type, icon, link) VALUES (?, ?, ?, ?, ?, ?)',
[
targetUserId,
status === 'pending' && currentUser.role === 'student' ? 'Meeting Rescheduled' : 'Meeting Status Updated',
statusMessage,
'meeting',
'📅',
link
]
);
}
} else Iif (wasRescheduled && !status) {
// Meeting was rescheduled without status change (supervisor rescheduling)
const [student] = await pool.query(
'SELECT user_id FROM students WHERE id = ?',
[meeting.student_id]
);
const [supervisor] = await pool.query(
'SELECT user_id FROM supervisors WHERE id = ?',
[meeting.supervisor_id]
);
const targetUserId = currentUser.role === 'supervisor'
? student[0]?.user_id
: supervisor[0]?.user_id;
const targetRole = currentUser.role === 'supervisor' ? 'student' : 'supervisor'
const link = `/${targetRole}/meetings`
if (targetUserId) {
const newDate = date || meeting.date;
const newTime = time || meeting.time;
const rescheduleMessage = currentUser.role === 'supervisor'
? `${currentUser.name} has rescheduled the meeting "${meeting.title}" to ${newDate} at ${newTime}.`
: `${currentUser.name} has rescheduled the meeting "${meeting.title}" to ${newDate} at ${newTime}.`;
await pool.query(
'INSERT INTO notifications (user_id, title, message, type, icon, link) VALUES (?, ?, ?, ?, ?, ?)',
[
targetUserId,
'Meeting Rescheduled',
rescheduleMessage,
'meeting',
'📅',
link
]
);
}
}
res.json({ message: 'Meeting updated successfully' });
} catch (error) {
console.error('Update meeting error:', error);
res.status(500).json({ error: 'Failed to update meeting' });
}
});
// Delete meeting
router.delete('/:id', authenticate, async (req, res) => {
try {
const meetingId = parseInt(req.params.id);
const currentUser = req.user;
// Get meeting
const [meetings] = await pool.query(
'SELECT * FROM meetings WHERE id = ?',
[meetingId]
);
Iif (meetings.length === 0) {
return res.status(404).json({ error: 'Meeting not found' });
}
const meeting = meetings[0];
// Check access
if (currentUser.role === 'student') {
const [student] = await pool.query(
'SELECT id FROM students WHERE user_id = ?',
[currentUser.id]
);
Iif (student.length === 0 || student[0].id !== meeting.student_id) {
return res.status(403).json({ error: 'Access denied' });
}
} else Eif (currentUser.role === 'supervisor') {
const [supervisor] = await pool.query(
'SELECT id FROM supervisors WHERE user_id = ?',
[currentUser.id]
);
if (supervisor.length === 0 || supervisor[0].id !== meeting.supervisor_id) {
return res.status(403).json({ error: 'Access denied' });
}
}
await pool.query('DELETE FROM meetings WHERE id = ?', [meetingId]);
res.json({ message: 'Meeting deleted successfully' });
} catch (error) {
console.error('Delete meeting error:', error);
res.status(500).json({ error: 'Failed to delete meeting' });
}
});
module.exports = router;
|