diff --git a/src/controllers/certificate.controller.ts b/src/controllers/certificate.controller.ts index a7e03ec..fa9dbeb 100644 --- a/src/controllers/certificate.controller.ts +++ b/src/controllers/certificate.controller.ts @@ -78,3 +78,33 @@ export const getCertificateByCourse = async (req: Request, res: Response) => { res.status(500).json({ message: 'Server error', error }); } }; + +export const getCertificatesByInstructor = async (req: Request, res: Response) => { + try { + const instructorId = req.user?._id; + + if (!instructorId) { + return res.status(401).json({ message: 'User not authenticated' }); + } + + // First, find all courses created by this instructor + const Course = mongoose.model('Course'); + const instructorCourses = await Course.find({ authorId: instructorId }).select('_id'); + + if (instructorCourses.length === 0) { + return res.status(200).json([]); + } + + const courseIds = instructorCourses.map(course => course._id); + + // Then, find all certificates for these courses + const certificates = await Certificate.find({ course: { $in: courseIds } }) + .populate('user', 'name email') + .populate('course', 'title authorId') + .sort({ createdAt: -1 }); + + res.status(200).json(certificates); + } catch (error) { + res.status(500).json({ message: 'Server error', error }); + } +}; diff --git a/src/routes/certificate.route.ts b/src/routes/certificate.route.ts index 3121beb..2725fda 100644 --- a/src/routes/certificate.route.ts +++ b/src/routes/certificate.route.ts @@ -1,6 +1,7 @@ import express from 'express'; -import { getCertificateById, getCertificateByCourse, getAllCertificates, getCertificateByUser } from '../controllers/certificate.controller'; +import { getCertificateById, getCertificateByCourse, getAllCertificates, getCertificateByUser, getCertificatesByInstructor } from '../controllers/certificate.controller'; import { isAuthenticated } from '../middlewares/auth/isAuthenticated'; +import { authorizeRoles } from '../middlewares/auth/authorizeRoles'; const router = express.Router(); @@ -22,4 +23,9 @@ router.get('/course/:courseId', isAuthenticated, (req, res, next) => { getCertificateByCourse(req, res).catch(next); }); +// Lấy tất cả certificate của các khóa học do instructor tạo +router.get('/instructor/courses', isAuthenticated, authorizeRoles('instructor'), (req, res, next) => { + getCertificatesByInstructor(req, res).catch(next); +}); + export default router;