diff --git a/backend/config/db.js b/backend/config/db.js index 9ebca23..4ae51dd 100644 --- a/backend/config/db.js +++ b/backend/config/db.js @@ -54,9 +54,9 @@ const connectDB = async () => { if (primaryURI) { try { console.log('Attempting primary database connection (Atlas)...'); - // Set serverSelectionTimeoutMS to 3000ms (3s) to detect offline states quickly + // Set serverSelectionTimeoutMS to 10000ms (10s) for reliable Atlas TLS handshake const conn = await mongoose.connect(primaryURI, { - serverSelectionTimeoutMS: 3000 + serverSelectionTimeoutMS: 10000 }); console.log(`MongoDB Connected (Primary): ${conn.connection.host}`); await seedAdmin(); diff --git a/backend/controllers/feedbackController.js b/backend/controllers/feedbackController.js index 5326241..d8343cb 100644 --- a/backend/controllers/feedbackController.js +++ b/backend/controllers/feedbackController.js @@ -9,25 +9,31 @@ import User from '../models/User.js'; */ export const createFeedback = async (req, res) => { try { - const { type, subject, message } = req.body; - const name = req.user.username; - const email = req.user.email; + const { name: bodyName, email: bodyEmail, type, subject, message } = req.body; + const name = req.user ? req.user.username : bodyName; + const email = req.user ? req.user.email : bodyEmail; - if (!type || !subject || !message) { - return res.status(400).json({ message: 'All fields are required.' }); + if (!name || !email || !type || !subject || !message) { + return res.status(400).json({ message: 'All fields (Name, Email, Ticket Type, Subject, Message) are required.' }); } if (!['feedback', 'bug', 'general'].includes(type)) { return res.status(400).json({ message: 'Invalid feedback type.' }); } + // Email format validation + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + return res.status(400).json({ message: 'Please provide a valid email address.' }); + } + const feedbackData = { - name, - email, + name: name.trim(), + email: email.trim().toLowerCase(), type, - subject, - message, - user: req.user._id + subject: subject.trim(), + message: message.trim(), + ...(req.user?._id && { user: req.user._id }) }; const feedback = new Feedback(feedbackData); diff --git a/backend/controllers/testimonialController.js b/backend/controllers/testimonialController.js new file mode 100644 index 0000000..c5b274a --- /dev/null +++ b/backend/controllers/testimonialController.js @@ -0,0 +1,278 @@ +import Testimonial from '../models/Testimonial.js'; + +/** + * @desc Get all public approved testimonials + * @route GET /api/testimonials + * @access Public + */ +export const getApprovedTestimonials = async (req, res) => { + try { + const limit = Math.min(50, Math.max(1, parseInt(req.query.limit, 10) || 12)); + + // Configurable Extensible Sorting: rating DESC, createdAt DESC + const sortField = req.query.sortBy === 'featured' + ? { isFeatured: -1, rating: -1, createdAt: -1 } + : { rating: -1, createdAt: -1 }; + + const testimonials = await Testimonial.find({ status: 'approved' }) + .populate('user', 'username name') + .sort(sortField) + .limit(limit) + .lean(); + + // Map and sanitize to ensure strict privacy (never expose email or private metadata) + const sanitized = testimonials.map((t) => { + const username = t.user?.username || 'Student'; + const displayName = t.user?.name || t.user?.username || 'NQTCoder Student'; + + return { + _id: t._id, + rating: t.rating, + review: t.review, + wouldRecommend: t.wouldRecommend || 'yes', + usageAreas: t.usageAreas || [], + isFeatured: Boolean(t.isFeatured), + createdAt: t.createdAt, + user: { + username, + displayName, + }, + }; + }); + + res.json({ + success: true, + count: sanitized.length, + testimonials: sanitized, + }); + } catch (error) { + console.error('Error fetching approved testimonials:', error); + res.status(500).json({ message: 'Server error retrieving testimonials', error: error.message }); + } +}; + +/** + * @desc Get current user's submitted testimonial (if any) + * @route GET /api/testimonials/my + * @access Private + */ +export const getMyTestimonial = async (req, res) => { + try { + if (!req.user) { + return res.status(401).json({ message: 'Not authorized' }); + } + + // Find the user's active or latest testimonial + const testimonial = await Testimonial.findOne({ user: req.user._id }) + .sort({ createdAt: -1 }) + .lean(); + + res.json({ + success: true, + testimonial: testimonial || null, + }); + } catch (error) { + console.error('Error fetching user testimonial:', error); + res.status(500).json({ message: 'Server error retrieving your review', error: error.message }); + } +}; + +/** + * @desc Submit or update user testimonial (One active review per user) + * @route POST /api/testimonials + * @access Private + */ +export const submitOrUpdateTestimonial = async (req, res) => { + try { + if (!req.user) { + return res.status(401).json({ message: 'Please log in to submit a review.' }); + } + + const { rating, review, wouldRecommend = 'yes', usageAreas = [] } = req.body; + + // Validation + const numRating = Number(rating); + if (!numRating || numRating < 1 || numRating > 5) { + return res.status(400).json({ message: 'Rating must be a number between 1 and 5 stars.' }); + } + + if (!review || typeof review !== 'string' || !review.trim()) { + return res.status(400).json({ message: 'Please write a review describing your experience.' }); + } + + if (review.trim().length > 500) { + return res.status(400).json({ message: 'Review text cannot exceed 500 characters.' }); + } + + if (!['yes', 'maybe', 'no'].includes(wouldRecommend)) { + return res.status(400).json({ message: 'Recommendation value must be Yes, Maybe, or No.' }); + } + + // Check if user already has an active (pending or approved) review + let existingReview = await Testimonial.findOne({ + user: req.user._id, + status: { $in: ['pending', 'approved'] }, + }); + + if (existingReview) { + // Update in-place and reset to pending for admin re-moderation + existingReview.rating = numRating; + existingReview.review = review.trim(); + existingReview.wouldRecommend = wouldRecommend; + existingReview.usageAreas = Array.isArray(usageAreas) ? usageAreas : []; + existingReview.status = 'pending'; + existingReview.approvedBy = null; + existingReview.approvedAt = null; + + const updated = await existingReview.save(); + + return res.status(200).json({ + success: true, + message: 'Your review has been updated and submitted for moderation.', + testimonial: updated, + }); + } + + // Create a new testimonial + const newTestimonial = await Testimonial.create({ + user: req.user._id, + rating: numRating, + review: review.trim(), + wouldRecommend, + usageAreas: Array.isArray(usageAreas) ? usageAreas : [], + status: 'pending', + }); + + res.status(201).json({ + success: true, + message: 'Thank you! Your review has been submitted and will appear publicly once approved.', + testimonial: newTestimonial, + }); + } catch (error) { + console.error('Error submitting testimonial:', error); + res.status(500).json({ message: error.message || 'Server error submitting testimonial' }); + } +}; + +/** + * @desc Get all testimonials for Admin Moderation + * @route GET /api/testimonials/admin + * @access Private/Admin + */ +export const getAdminTestimonials = async (req, res) => { + try { + const { status, search } = req.query; + + const query = {}; + if (status && status !== 'all' && ['pending', 'approved', 'rejected', 'hidden'].includes(status)) { + query.status = status; + } + + if (search && search.trim()) { + query.$or = [ + { review: { $regex: search.trim(), $options: 'i' } }, + { adminNote: { $regex: search.trim(), $options: 'i' } }, + ]; + } + + const testimonials = await Testimonial.find(query) + .populate('user', 'username email role name') + .populate('approvedBy', 'username') + .sort({ createdAt: -1 }) + .lean(); + + // Calculate quick counts for admin tabs + const [totalCount, pendingCount, approvedCount, rejectedCount, hiddenCount] = await Promise.all([ + Testimonial.countDocuments({}), + Testimonial.countDocuments({ status: 'pending' }), + Testimonial.countDocuments({ status: 'approved' }), + Testimonial.countDocuments({ status: 'rejected' }), + Testimonial.countDocuments({ status: 'hidden' }), + ]); + + res.json({ + success: true, + stats: { + totalCount, + pendingCount, + approvedCount, + rejectedCount, + hiddenCount, + }, + testimonials, + }); + } catch (error) { + console.error('Error fetching admin testimonials:', error); + res.status(500).json({ message: 'Server error retrieving admin testimonials', error: error.message }); + } +}; + +/** + * @desc Moderate testimonial (Approve, Reject, Hide, Feature, or add Admin Note) + * @route PATCH /api/testimonials/admin/:id + * @access Private/Admin + */ +export const updateTestimonialStatus = async (req, res) => { + try { + const { status, isFeatured, adminNote } = req.body; + + const testimonial = await Testimonial.findById(req.params.id); + if (!testimonial) { + return res.status(404).json({ message: 'Testimonial not found.' }); + } + + if (status) { + if (!['pending', 'approved', 'rejected', 'hidden'].includes(status)) { + return res.status(400).json({ message: 'Invalid status value.' }); + } + testimonial.status = status; + if (status === 'approved') { + testimonial.approvedBy = req.user._id; + testimonial.approvedAt = new Date(); + } + } + + if (typeof isFeatured === 'boolean') { + testimonial.isFeatured = isFeatured; + } + + if (typeof adminNote === 'string') { + testimonial.adminNote = adminNote.trim(); + } + + const updated = await testimonial.save(); + + res.json({ + success: true, + message: `Testimonial updated successfully.`, + testimonial: updated, + }); + } catch (error) { + console.error('Error updating testimonial status:', error); + res.status(500).json({ message: 'Server error updating testimonial', error: error.message }); + } +}; + +/** + * @desc Delete a testimonial + * @route DELETE /api/testimonials/admin/:id + * @access Private/Admin + */ +export const deleteTestimonial = async (req, res) => { + try { + const testimonial = await Testimonial.findById(req.params.id); + if (!testimonial) { + return res.status(404).json({ message: 'Testimonial not found.' }); + } + + await testimonial.deleteOne(); + + res.json({ + success: true, + message: 'Testimonial deleted successfully.', + }); + } catch (error) { + console.error('Error deleting testimonial:', error); + res.status(500).json({ message: 'Server error deleting testimonial', error: error.message }); + } +}; diff --git a/backend/models/Testimonial.js b/backend/models/Testimonial.js new file mode 100644 index 0000000..82fbb4a --- /dev/null +++ b/backend/models/Testimonial.js @@ -0,0 +1,84 @@ +import mongoose from 'mongoose'; + +const testimonialSchema = new mongoose.Schema( + { + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true, + }, + rating: { + type: Number, + required: [true, 'Rating is required'], + min: [1, 'Rating must be at least 1 star'], + max: [5, 'Rating cannot exceed 5 stars'], + }, + review: { + type: String, + required: [true, 'Review text is required'], + trim: true, + maxlength: [500, 'Review cannot exceed 500 characters'], + }, + wouldRecommend: { + type: String, + enum: ['yes', 'maybe', 'no'], + default: 'yes', + }, + usageAreas: [ + { + type: String, + enum: [ + 'coding', + 'aptitude', + 'logical_reasoning', + 'verbal', + 'mock_tests', + 'cognitive_games', + 'company_guides', + 'other', + ], + }, + ], + status: { + type: String, + enum: ['pending', 'approved', 'rejected', 'hidden'], + default: 'pending', + index: true, + }, + isFeatured: { + type: Boolean, + default: false, + index: true, + }, + approvedBy: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + }, + approvedAt: { + type: Date, + }, + adminNote: { + type: String, + trim: true, + maxlength: [500, 'Admin note cannot exceed 500 characters'], + }, + }, + { timestamps: true } +); + +// Lifecycle-Aware Partial Unique Index: +// Guarantees only one ACTIVE (pending or approved) review per user. +// Users whose previous review was rejected or hidden can submit a new review. +testimonialSchema.index( + { user: 1 }, + { + unique: true, + partialFilterExpression: { status: { $in: ['pending', 'approved'] } }, + } +); + +// Compound index for public sorting: rating DESC, createdAt DESC +testimonialSchema.index({ status: 1, rating: -1, createdAt: -1 }); + +const Testimonial = mongoose.model('Testimonial', testimonialSchema); +export default Testimonial; diff --git a/backend/routes/feedbackRoutes.js b/backend/routes/feedbackRoutes.js index 5300e57..3d27a92 100644 --- a/backend/routes/feedbackRoutes.js +++ b/backend/routes/feedbackRoutes.js @@ -5,11 +5,11 @@ import { updateFeedbackStatus, deleteFeedback } from '../controllers/feedbackController.js'; -import { protect, admin } from '../middleware/authMiddleware.js'; +import { protect, admin, optionalProtect } from '../middleware/authMiddleware.js'; const router = express.Router(); -router.post('/', protect, createFeedback); +router.post('/', optionalProtect, createFeedback); router.get('/', protect, admin, getAllFeedback); router.patch('/:id', protect, admin, updateFeedbackStatus); router.delete('/:id', protect, admin, deleteFeedback); diff --git a/backend/routes/testimonialRoutes.js b/backend/routes/testimonialRoutes.js new file mode 100644 index 0000000..72a83ce --- /dev/null +++ b/backend/routes/testimonialRoutes.js @@ -0,0 +1,26 @@ +import express from 'express'; +import { + getApprovedTestimonials, + getMyTestimonial, + submitOrUpdateTestimonial, + getAdminTestimonials, + updateTestimonialStatus, + deleteTestimonial, +} from '../controllers/testimonialController.js'; +import { protect, admin } from '../middleware/authMiddleware.js'; + +const router = express.Router(); + +// Public route +router.get('/', getApprovedTestimonials); + +// Authenticated user routes +router.get('/my', protect, getMyTestimonial); +router.post('/', protect, submitOrUpdateTestimonial); + +// Admin moderation routes +router.get('/admin', protect, admin, getAdminTestimonials); +router.patch('/admin/:id', protect, admin, updateTestimonialStatus); +router.delete('/admin/:id', protect, admin, deleteTestimonial); + +export default router; diff --git a/backend/server.js b/backend/server.js index 2aff056..aee9ed9 100644 --- a/backend/server.js +++ b/backend/server.js @@ -16,6 +16,7 @@ import practiceRoutes from './routes/practiceRoutes.js'; import companyRoutes from './routes/companyRoutes.js'; import companyGuideRoutes from './routes/companyGuideRoutes.js'; import adminCompanyGuideRoutes from './routes/adminCompanyGuideRoutes.js'; +import testimonialRoutes from './routes/testimonialRoutes.js'; import gameRoutes from './routes/gameRoutes.js'; import { notFound, errorHandler } from './middleware/errorMiddleware.js'; @@ -84,6 +85,7 @@ app.use('/api/practice', practiceRoutes); app.use('/api/companies', companyRoutes); app.use('/api/company-guides', companyGuideRoutes); app.use('/api/admin', adminCompanyGuideRoutes); +app.use('/api/testimonials', testimonialRoutes); app.use('/api/games', gameRoutes); // Error Middlewares diff --git a/backend/tests/test_feedback.js b/backend/tests/test_feedback.js index 4e51a54..c6975b4 100644 --- a/backend/tests/test_feedback.js +++ b/backend/tests/test_feedback.js @@ -21,13 +21,20 @@ const runFeedbackTests = async () => { let userHeader = {}; let adminHeader = {}; let tempUserId = ''; + let guestFeedbackId = ''; + let authFeedbackId = ''; try { - await mongoose.connect(process.env.MONGO_URI); - console.log('✅ Connected to MongoDB.'); + try { + await mongoose.connect(process.env.MONGO_URI, { serverSelectionTimeoutMS: 3000 }); + console.log('✅ Connected to Primary MongoDB Atlas.'); + } catch { + await mongoose.connect('mongodb://127.0.0.1:27017/nqtcoder'); + console.log('✅ Connected to Local Fallback MongoDB.'); + } // Cleanup lingering test users - await User.deleteMany({ email: /feedback_tester_.*@example\.com/ }); + await User.deleteMany({ email: /fb_test_.*@example\.com/ }); // Ensure Admin user exists in DB before logging in let adminUser = await User.findOne({ email: adminEmail }); @@ -77,37 +84,46 @@ const runFeedbackTests = async () => { userHeader = { headers: { Authorization: `Bearer ${userToken}` } }; console.log('✅ Regular user login successful.'); - // --- Submit feedback anonymously (should fail with 401) --- - console.log('Verifying anonymous feedback submission is blocked...'); + // --- 1. Submit feedback as Guest (should succeed) --- + console.log('Testing guest / anonymous feedback submission...'); + const guestFeedbackPayload = { + name: 'Guest Tester', + email: 'guest.tester@example.com', + type: 'bug', + subject: 'Compiler Timeout Bug Report', + message: 'Found that C++ code with infinite loop hits 5000ms TLE as expected.' + }; + const guestRes = await axios.post(`${BASE_URL}/feedback`, guestFeedbackPayload); + if (guestRes.status !== 201) throw new Error('Guest feedback submission failed.'); + guestFeedbackId = guestRes.data.feedback._id; + console.log(`✅ Success: Guest feedback submitted (ID: ${guestFeedbackId}).`); + + // --- 2. Submit feedback authenticated as User (should succeed & attach user) --- + console.log('Submitting authenticated user feedback...'); + const authFeedbackPayload = { + type: 'feedback', + subject: 'Great placement mock test UI', + message: 'The Cognitive games and Mock Test timer work smoothly.' + }; + const submitFeedbackRes = await axios.post(`${BASE_URL}/feedback`, authFeedbackPayload, userHeader); + if (submitFeedbackRes.status !== 201) throw new Error('Authenticated feedback submission failed.'); + authFeedbackId = submitFeedbackRes.data.feedback._id; + console.log(`✅ Success: Authenticated feedback submitted (ID: ${authFeedbackId}).`); + + // --- 3. Validation: Missing fields --- + console.log('Testing missing fields validation (should fail with 400)...'); try { - const feedbackPayload = { - type: 'bug', - subject: 'Test Bug Subject', - message: 'Test bug description' - }; - await axios.post(`${BASE_URL}/feedback`, feedbackPayload); - throw new Error('FAIL: Anonymous feedback submission was allowed.'); + await axios.post(`${BASE_URL}/feedback`, { type: 'bug' }); + throw new Error('FAIL: Missing fields were allowed.'); } catch (err) { - if (err.response && err.response.status === 401) { - console.log('✅ Blocked: Anonymous submission rejected with 401 Unauthorized.'); + if (err.response && err.response.status === 400) { + console.log('✅ Blocked: Missing fields rejected with 400 Bad Request.'); } else { throw err; } } - // --- Submit feedback authenticated as User (should succeed) --- - console.log('Submitting authenticated user feedback...'); - const authFeedbackPayload = { - type: 'bug', - subject: 'Test Bug Subject', - message: 'Test bug description' - }; - const submitFeedbackRes = await axios.post(`${BASE_URL}/feedback`, authFeedbackPayload, userHeader); - if (submitFeedbackRes.status !== 201) throw new Error('Feedback submission failed.'); - const feedbackId = submitFeedbackRes.data.feedback._id; - console.log(`✅ Success: Authenticated feedback submitted (ID: ${feedbackId}).`); - - // --- Verify regular user CANNOT view feedback (RBAC) --- + // --- 4. Verify regular user CANNOT view feedback (RBAC) --- console.log('Verifying regular user cannot view all feedback (should fail)...'); try { await axios.get(`${BASE_URL}/feedback`, userHeader); @@ -120,27 +136,37 @@ const runFeedbackTests = async () => { } } - // --- Verify Admin CAN view feedback --- + // --- 5. Verify Admin CAN view and manage feedback --- console.log('Verifying Admin can view all feedback (should succeed)...'); const adminFeedbackRes = await axios.get(`${BASE_URL}/feedback`, adminHeader); const feedbackList = adminFeedbackRes.data; - const submittedItem = feedbackList.find(f => f._id === feedbackId); - if (!submittedItem) throw new Error('FAIL: Submitted feedback not found in admin list.'); + const submittedGuestItem = feedbackList.find(f => f._id === guestFeedbackId); + const submittedAuthItem = feedbackList.find(f => f._id === authFeedbackId); + if (!submittedGuestItem || !submittedAuthItem) throw new Error('FAIL: Submitted feedback items not found in admin list.'); console.log(`✅ Success: Admin fetched feedback list (size: ${feedbackList.length}).`); + // Update status to 'reviewed' + console.log('Testing admin status update to reviewed...'); + const updateRes = await axios.patch(`${BASE_URL}/feedback/${authFeedbackId}`, { status: 'reviewed' }, adminHeader); + if (updateRes.data.status !== 'reviewed') throw new Error('FAIL: Status update failed.'); + console.log('✅ Success: Feedback status updated to reviewed.'); + // --- Clean up --- console.log('\n--- 🧹 Cleaning Up Test Entities ---'); - await Feedback.deleteOne({ _id: feedbackId }); - await User.deleteOne({ _id: tempUserId }); + if (guestFeedbackId) await Feedback.deleteOne({ _id: guestFeedbackId }); + if (authFeedbackId) await Feedback.deleteOne({ _id: authFeedbackId }); + if (tempUserId) await User.deleteOne({ _id: tempUserId }); console.log('✅ Database cleaned up.'); - console.log('\n🌟 ALL FEEDBACK TESTS PASSED SUCCESSFULLY! 🌟'); + console.log('\n🌟 ALL FEEDBACK & SUPPORT TESTS PASSED SUCCESSFULLY! 🌟'); } catch (err) { console.error('\n❌ Feedback Test failed:', err.response ? err.response.data : err.message); process.exitCode = 1; try { await User.deleteOne({ email: testEmail }); + if (guestFeedbackId) await Feedback.deleteOne({ _id: guestFeedbackId }); + if (authFeedbackId) await Feedback.deleteOne({ _id: authFeedbackId }); } catch {} } finally { await mongoose.disconnect(); diff --git a/backend/tests/test_public_access.js b/backend/tests/test_public_access.js index 7518064..a824d54 100644 --- a/backend/tests/test_public_access.js +++ b/backend/tests/test_public_access.js @@ -86,20 +86,16 @@ async function runTests() { assert(false, `GET /api/submissions/compilers failed: ${err.message}`); } - // 4. Verify POST /api/feedback is protected (fails with 401) + // 4. Verify GET /api/feedback is protected for admins (fails anonymous with 401) console.log(`\n${YELLOW}Testing protected routes (must block anonymous)...${RESET}`); try { - await axios.post(`${BASE_URL}/feedback`, { - type: 'feedback', - subject: 'Anonymous Test', - message: 'This should fail' - }); - assert(false, 'POST /api/feedback was allowed anonymously!'); + await axios.get(`${BASE_URL}/feedback`); + assert(false, 'GET /api/feedback was allowed anonymously!'); } catch (err) { if (err.response && err.response.status === 401) { - assert(true, 'POST /api/feedback blocked anonymously with status 401'); + assert(true, 'GET /api/feedback blocked anonymously with status 401'); } else { - assert(false, `POST /api/feedback failed with unexpected error: ${err.message}`); + assert(false, `GET /api/feedback failed with unexpected error: ${err.message}`); } } diff --git a/backend/tests/test_testimonials.js b/backend/tests/test_testimonials.js new file mode 100644 index 0000000..91742b0 --- /dev/null +++ b/backend/tests/test_testimonials.js @@ -0,0 +1,342 @@ +import dotenv from 'dotenv'; +dotenv.config(); +import mongoose from 'mongoose'; +import axios from 'axios'; +import User from '../models/User.js'; +import Testimonial from '../models/Testimonial.js'; + +const BASE_URL = 'http://localhost:5000/api'; +const testUsername = `u1_${Math.floor(100000 + Math.random() * 900000)}`; +const testEmail = `${testUsername}@example.com`; +const testPassword = 'Password@123'; + +const testUsername2 = `u2_${Math.floor(100000 + Math.random() * 900000)}`; +const testEmail2 = `${testUsername2}@example.com`; + +const adminEmail = process.env.ADMIN_EMAIL || 'admin@nqtcoder.com'; +const adminPassword = process.env.ADMIN_PASSWORD || 'AdminPassword@123'; + +const runTestimonialTests = async () => { + console.log('🚀 Starting Testimonial & Review System Integration Test...'); + + let userToken = ''; + let userHeader = {}; + let user2Token = ''; + let user2Header = {}; + let adminToken = ''; + let adminHeader = {}; + let tempUserId = ''; + let tempUser2Id = ''; + let review1Id = ''; + let review2Id = ''; + + try { + try { + await mongoose.connect(process.env.MONGO_URI, { serverSelectionTimeoutMS: 3000 }); + console.log('✅ Connected to Primary MongoDB Atlas.'); + } catch { + await mongoose.connect('mongodb://127.0.0.1:27017/nqtcoder'); + console.log('✅ Connected to Local Fallback MongoDB.'); + } + + // Cleanup lingering test entities + await User.deleteMany({ email: /fb_test_t.*@example\.com/ }); + await Testimonial.deleteMany({ review: /\[TEST_REVIEW\]/ }); + + // 1. Ensure Admin exists and login + let adminUser = await User.findOne({ email: adminEmail }); + if (!adminUser) { + adminUser = await User.create({ + username: 'testi_admin', + email: adminEmail, + password: adminPassword, + role: 'admin', + isVerified: true, + }); + await new Promise((r) => setTimeout(r, 400)); + } + + const adminLoginRes = await axios.post(`${BASE_URL}/auth/login`, { + email: adminEmail, + password: adminPassword, + }); + adminToken = adminLoginRes.data.token; + adminHeader = { headers: { Authorization: `Bearer ${adminToken}` } }; + console.log('✅ Admin login successful.'); + + // 2. Register & Verify User 1 + const regRes1 = await axios.post(`${BASE_URL}/auth/register`, { + username: testUsername, + email: testEmail.toLowerCase(), + password: testPassword, + confirmPassword: testPassword, + }); + if (!regRes1.data.verificationRequired) { + throw new Error(`User 1 registration failed: ${JSON.stringify(regRes1.data)}`); + } + let user1InDb = null; + for (let i = 0; i < 10; i++) { + user1InDb = await User.findOne({ email: testEmail.toLowerCase() }); + if (user1InDb && user1InDb.verificationCode) break; + await new Promise((r) => setTimeout(r, 350)); + } + if (!user1InDb) throw new Error(`User 1 not found in DB for email ${testEmail.toLowerCase()}`); + tempUserId = user1InDb._id.toString(); + await axios.post(`${BASE_URL}/auth/verify`, { + email: testEmail.toLowerCase(), + code: user1InDb.verificationCode, + }); + const user1LoginRes = await axios.post(`${BASE_URL}/auth/login`, { + email: testEmail.toLowerCase(), + password: testPassword, + }); + userToken = user1LoginRes.data.token; + userHeader = { headers: { Authorization: `Bearer ${userToken}` } }; + console.log('✅ User 1 registered & logged in.'); + + // 3. Register & Verify User 2 + const regRes2 = await axios.post(`${BASE_URL}/auth/register`, { + username: testUsername2, + email: testEmail2.toLowerCase(), + password: testPassword, + confirmPassword: testPassword, + }); + if (!regRes2.data.verificationRequired) { + throw new Error(`User 2 registration failed: ${JSON.stringify(regRes2.data)}`); + } + let user2InDb = null; + for (let i = 0; i < 10; i++) { + user2InDb = await User.findOne({ email: testEmail2.toLowerCase() }); + if (user2InDb && user2InDb.verificationCode) break; + await new Promise((r) => setTimeout(r, 350)); + } + if (!user2InDb) throw new Error(`User 2 not found in DB for email ${testEmail2.toLowerCase()}`); + tempUser2Id = user2InDb._id.toString(); + await axios.post(`${BASE_URL}/auth/verify`, { + email: testEmail2.toLowerCase(), + code: user2InDb.verificationCode, + }); + const user2LoginRes = await axios.post(`${BASE_URL}/auth/login`, { + email: testEmail2.toLowerCase(), + password: testPassword, + }); + user2Token = user2LoginRes.data.token; + user2Header = { headers: { Authorization: `Bearer ${user2Token}` } }; + console.log('✅ User 2 registered & logged in.'); + + // ------------------------------------------------------------- + // Test 1: Guest submission must be blocked (401) + // ------------------------------------------------------------- + console.log('\n--- Test 1: Guest Review Submission Blocked ---'); + try { + await axios.post(`${BASE_URL}/testimonials`, { + rating: 5, + review: '[TEST_REVIEW] Great platform for placement prep!', + }); + throw new Error('FAIL: Anonymous review was accepted without token.'); + } catch (err) { + if (err.response && err.response.status === 401) { + console.log('✅ PASS: Guest review submission blocked with 401 Unauthorized.'); + } else { + throw err; + } + } + + // ------------------------------------------------------------- + // Test 2: Validation boundaries (rating 1-5, review text) + // ------------------------------------------------------------- + console.log('\n--- Test 2: Review Field Validation ---'); + try { + await axios.post( + `${BASE_URL}/testimonials`, + { rating: 6, review: '[TEST_REVIEW] Invalid rating' }, + userHeader + ); + throw new Error('FAIL: Rating > 5 was allowed.'); + } catch (err) { + if (err.response && err.response.status === 400) { + console.log('✅ PASS: Rating > 5 rejected with 400 Bad Request.'); + } else { + throw err; + } + } + + try { + await axios.post( + `${BASE_URL}/testimonials`, + { rating: 4, review: ' ' }, + userHeader + ); + throw new Error('FAIL: Empty review text was allowed.'); + } catch (err) { + if (err.response && err.response.status === 400) { + console.log('✅ PASS: Empty review rejected with 400 Bad Request.'); + } else { + throw err; + } + } + + // ------------------------------------------------------------- + // Test 3: Authenticated User submits valid review (Status: pending) + // ------------------------------------------------------------- + console.log('\n--- Test 3: Authenticated User Submits Review ---'); + const reviewPayload1 = { + rating: 5, + review: '[TEST_REVIEW] The TCS NQT mock tests and cognitive games helped me clear my placement exam on first attempt!', + wouldRecommend: 'yes', + usageAreas: ['coding', 'mock_tests', 'cognitive_games'], + }; + const subRes1 = await axios.post(`${BASE_URL}/testimonials`, reviewPayload1, userHeader); + if (subRes1.status !== 201) throw new Error('User 1 submission failed.'); + review1Id = subRes1.data.testimonial._id; + if (subRes1.data.testimonial.status !== 'pending') throw new Error('New review did not default to pending status.'); + console.log(`✅ PASS: User 1 submitted 5-star review (ID: ${review1Id}, Status: pending).`); + + // User 2 submits 4-star review + const reviewPayload2 = { + rating: 4, + review: '[TEST_REVIEW] Great question bank and timer simulation. Really useful for Infosys and Cognizant.', + wouldRecommend: 'yes', + usageAreas: ['aptitude', 'coding'], + }; + const subRes2 = await axios.post(`${BASE_URL}/testimonials`, reviewPayload2, user2Header); + review2Id = subRes2.data.testimonial._id; + console.log(`✅ PASS: User 2 submitted 4-star review (ID: ${review2Id}, Status: pending).`); + + // ------------------------------------------------------------- + // Test 4: One Active Review & Update In-Place (Partial Index) + // ------------------------------------------------------------- + console.log('\n--- Test 4: User Edits/Updates Existing Review ---'); + const updatePayload = { + rating: 5, + review: '[TEST_REVIEW] Updated review text with additional details on Aptitude arena.', + wouldRecommend: 'yes', + usageAreas: ['coding', 'aptitude', 'mock_tests'], + }; + const updateRes = await axios.post(`${BASE_URL}/testimonials`, updatePayload, userHeader); + if (updateRes.status !== 200) throw new Error('Review update failed.'); + if (updateRes.data.testimonial._id !== review1Id) throw new Error('Did not update in-place!'); + if (updateRes.data.testimonial.status !== 'pending') throw new Error('Updated review did not reset to pending for re-moderation.'); + console.log('✅ PASS: User 1 updated review in-place without duplicate error.'); + + // ------------------------------------------------------------- + // Test 5: Pending review must NOT be visible publicly + // ------------------------------------------------------------- + console.log('\n--- Test 5: Public Access Filter (Pending Hidden) ---'); + const publicRes1 = await axios.get(`${BASE_URL}/testimonials`); + const publicIds1 = (publicRes1.data.testimonials || []).map((t) => t._id); + if (publicIds1.includes(review1Id) || publicIds1.includes(review2Id)) { + throw new Error('FAIL: Pending reviews are leaking into public endpoint!'); + } + console.log('✅ PASS: Pending reviews are hidden from public GET /api/testimonials.'); + + // ------------------------------------------------------------- + // Test 6: Admin Moderation (Approve, Reject, Hide, Feature) + // ------------------------------------------------------------- + console.log('\n--- Test 6: Admin Moderation Workflow ---'); + // Regular user blocked from admin endpoint + try { + await axios.get(`${BASE_URL}/testimonials/admin`, userHeader); + throw new Error('FAIL: Regular user accessed admin endpoint.'); + } catch (err) { + if (err.response && err.response.status === 403) { + console.log('✅ PASS: Regular user blocked from admin endpoint with 403 Forbidden.'); + } else { + throw err; + } + } + + // Admin fetches all reviews + const adminListRes = await axios.get(`${BASE_URL}/testimonials/admin`, adminHeader); + if (!adminListRes.data.testimonials || adminListRes.data.testimonials.length === 0) { + throw new Error('FAIL: Admin could not list testimonials.'); + } + console.log(`✅ PASS: Admin fetched ${adminListRes.data.testimonials.length} reviews (Pending: ${adminListRes.data.stats.pendingCount}).`); + + // Admin approves Review 1 (5 stars) + const approveRes1 = await axios.patch( + `${BASE_URL}/testimonials/admin/${review1Id}`, + { status: 'approved', isFeatured: true, adminNote: 'Verified genuine student review' }, + adminHeader + ); + if (approveRes1.data.testimonial.status !== 'approved') throw new Error('Approve action failed.'); + console.log('✅ PASS: Admin approved Review 1 with isFeatured=true.'); + + // Admin approves Review 2 (4 stars) + const approveRes2 = await axios.patch( + `${BASE_URL}/testimonials/admin/${review2Id}`, + { status: 'approved' }, + adminHeader + ); + if (approveRes2.data.testimonial.status !== 'approved') throw new Error('Approve action 2 failed.'); + console.log('✅ PASS: Admin approved Review 2.'); + + // ------------------------------------------------------------- + // Test 7: Public Sorting (rating DESC, createdAt DESC) & Privacy + // ------------------------------------------------------------- + console.log('\n--- Test 7: Public Sorting & Privacy Verification ---'); + const publicRes2 = await axios.get(`${BASE_URL}/testimonials`); + const approvedList = publicRes2.data.testimonials || []; + + // Find our approved reviews in the list + const foundR1 = approvedList.find((t) => t._id === review1Id); + const foundR2 = approvedList.find((t) => t._id === review2Id); + + if (!foundR1 || !foundR2) { + throw new Error('FAIL: Approved reviews are not appearing in public endpoint!'); + } + + // Check privacy: user email, password, and adminNote must not exist + if (foundR1.email || foundR1.user?.email || foundR1.adminNote || foundR1.approvedBy) { + throw new Error('FAIL: Private metadata leaked in public testimonial payload!'); + } + console.log('✅ PASS: Privacy verified (no emails, passwords, or admin notes exposed).'); + + // Check sorting: 5-star review must appear before 4-star review + const idxR1 = approvedList.findIndex((t) => t._id === review1Id); + const idxR2 = approvedList.findIndex((t) => t._id === review2Id); + if (idxR1 > idxR2) { + throw new Error('FAIL: 5-star review did not appear before 4-star review!'); + } + console.log(`✅ PASS: Sorting verified (5★ at index ${idxR1} appears before 4★ at index ${idxR2}).`); + + // ------------------------------------------------------------- + // Test 8: Admin Hide Review + // ------------------------------------------------------------- + console.log('\n--- Test 8: Admin Hide Review ---'); + await axios.patch(`${BASE_URL}/testimonials/admin/${review2Id}`, { status: 'hidden' }, adminHeader); + const publicRes3 = await axios.get(`${BASE_URL}/testimonials`); + const remainingIds = (publicRes3.data.testimonials || []).map((t) => t._id); + if (remainingIds.includes(review2Id)) { + throw new Error('FAIL: Hidden review is still visible publicly!'); + } + console.log('✅ PASS: Hidden review is immediately excluded from public endpoint.'); + + // ------------------------------------------------------------- + // Cleanup + // ------------------------------------------------------------- + console.log('\n--- 🧹 Cleaning Up Test Entities ---'); + if (review1Id) await Testimonial.deleteOne({ _id: review1Id }); + if (review2Id) await Testimonial.deleteOne({ _id: review2Id }); + if (tempUserId) await User.deleteOne({ _id: tempUserId }); + if (tempUser2Id) await User.deleteOne({ _id: tempUser2Id }); + console.log('✅ Test database cleaned up.'); + + console.log('\n🌟 ALL TESTIMONIAL & REVIEW TESTS PASSED SUCCESSFULLY! 🌟'); + } catch (err) { + console.error('\n❌ Testimonial Test failed:', err.response ? err.response.data : err.message); + process.exitCode = 1; + try { + if (review1Id) await Testimonial.deleteOne({ _id: review1Id }); + if (review2Id) await Testimonial.deleteOne({ _id: review2Id }); + if (tempUserId) await User.deleteOne({ _id: tempUserId }); + if (tempUser2Id) await User.deleteOne({ _id: tempUser2Id }); + } catch {} + } finally { + await mongoose.disconnect(); + console.log('🔌 Disconnected from MongoDB.'); + console.log('🏁 Testimonial Test complete.'); + } +}; + +runTestimonialTests(); diff --git a/frontend/src/components/testimonials/ReviewModal.jsx b/frontend/src/components/testimonials/ReviewModal.jsx new file mode 100644 index 0000000..f1eac5a --- /dev/null +++ b/frontend/src/components/testimonials/ReviewModal.jsx @@ -0,0 +1,350 @@ +import React, { useState, useEffect, useContext } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { AuthContext } from '../../context/AuthContext'; +import { getMyTestimonial, submitTestimonial } from '../../services/testimonialService'; +import { Star, X, CheckCircle2, ShieldCheck, Sparkles, LogIn, AlertCircle } from 'lucide-react'; + +const USAGE_OPTIONS = [ + { id: 'coding', label: 'Coding Practice' }, + { id: 'aptitude', label: 'Aptitude Arena' }, + { id: 'cognitive_games', label: 'Cognitive Games' }, + { id: 'mock_tests', label: 'Timed Mock Tests' }, + { id: 'verbal', label: 'Verbal Ability' }, + { id: 'company_guides', label: 'Company Guides' }, + { id: 'other', label: 'Other' }, +]; + +const RATING_LABELS = { + 1: 'Needs Improvement', + 2: 'Fair Experience', + 3: 'Good Platform', + 4: 'Very Helpful', + 5: 'Outstanding / 5-Star!', +}; + +const ReviewModal = ({ isOpen, onClose, onSuccess }) => { + const { user } = useContext(AuthContext); + const navigate = useNavigate(); + + const [rating, setRating] = useState(5); + const [hoverRating, setHoverRating] = useState(0); + const [review, setReview] = useState(''); + const [wouldRecommend, setWouldRecommend] = useState('yes'); + const [usageAreas, setUsageAreas] = useState(['coding', 'mock_tests']); + const [isEditing, setIsEditing] = useState(false); + const [existingStatus, setExistingStatus] = useState(null); + + const [loading, setLoading] = useState(false); + const [fetchingExisting, setFetchingExisting] = useState(false); + const [error, setError] = useState(''); + const [isSuccess, setIsSuccess] = useState(false); + const [successMessage, setSuccessMessage] = useState(''); + + // Fetch current user's review if logged in + useEffect(() => { + if (isOpen && user) { + setError(''); + setIsSuccess(false); + setFetchingExisting(true); + + getMyTestimonial() + .then((res) => { + if (res.testimonial) { + setIsEditing(true); + setRating(res.testimonial.rating || 5); + setReview(res.testimonial.review || ''); + setWouldRecommend(res.testimonial.wouldRecommend || 'yes'); + setUsageAreas(res.testimonial.usageAreas || ['coding']); + setExistingStatus(res.testimonial.status); + } else { + setIsEditing(false); + setRating(5); + setReview(''); + setWouldRecommend('yes'); + setUsageAreas(['coding', 'mock_tests']); + setExistingStatus(null); + } + }) + .catch(() => { + // Non-blocking fallback + setIsEditing(false); + }) + .finally(() => { + setFetchingExisting(false); + }); + } + }, [isOpen, user]); + + if (!isOpen) return null; + + const toggleUsageArea = (areaId) => { + setUsageAreas((prev) => + prev.includes(areaId) ? prev.filter((item) => item !== areaId) : [...prev, areaId] + ); + }; + + const handleSubmit = async (e) => { + e.preventDefault(); + if (!review.trim()) { + setError('Please share a few sentences about your experience.'); + return; + } + if (review.trim().length > 500) { + setError('Review cannot exceed 500 characters.'); + return; + } + + setLoading(true); + setError(''); + + try { + const res = await submitTestimonial({ + rating, + review: review.trim(), + wouldRecommend, + usageAreas, + }); + + setIsSuccess(true); + setSuccessMessage( + res.message || 'Thank you! Your review has been submitted for moderation.' + ); + if (onSuccess) onSuccess(); + } catch (err) { + console.error(err); + setError(err.response?.data?.message || 'Failed to submit review. Please try again.'); + } finally { + setLoading(false); + } + }; + + return ( +
+
+ {/* Background glow */} +
+ + {/* Close Button */} + + + {!user ? ( + /* Logged-out State */ +
+
+ +
+
+

Share Your NQTCoder Experience

+

+ Log in with your student account to share your ratings, practice feedback, and placement experience. +

+
+
+ + +
+
+ ) : isSuccess ? ( + /* Submission Success State */ +
+
+ +
+
+

Review Submitted!

+

+ {successMessage} +

+
+
+ + We maintain genuine social proof by quickly verifying all student reviews. +
+
+ +
+
+ ) : ( + /* Active Review Form */ +
+
+
+ + {isEditing ? 'Update Review' : 'Student Review'} +
+

+ {isEditing ? 'Edit Your Experience' : 'Share Your Experience'} +

+

+ Help fellow engineering students prepare by sharing your genuine thoughts. +

+
+ + {error && ( +
+ + {error} +
+ )} + + {isEditing && existingStatus === 'approved' && ( +
+ Note: Editing an approved review will temporarily set it to pending for re-moderation. +
+ )} + + {/* 1. Rating Selector */} +
+ +
+ {[1, 2, 3, 4, 5].map((star) => { + const isFilled = (hoverRating || rating) >= star; + return ( + + ); + })} + + {RATING_LABELS[hoverRating || rating]} + +
+
+ + {/* 2. Review Textarea */} +
+
+ + 480 ? 'text-amber-400' : 'text-slate-500'}> + {review.length}/500 + +
+