File size: 1,733 Bytes
0f8617c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const Review = require('../models/Review');
const User = require('../models/User');

const createReview = async (req, res) => {
    try {
        const { photographerId, bookingId, rating, comment } = req.body;
        const customerId = req.user._id;

        // Check if review already exists for this booking
        const existingReview = await Review.findOne({ bookingId });
        if (existingReview) {
            return res.status(400).json({ message: 'You have already reviewed this booking' });
        }

        const review = await Review.create({
            photographerId,
            customerId,
            bookingId,
            rating,
            comment
        });

        // Update photographer's average rating and reviews count
        const photographer = await User.findById(photographerId);
        if (photographer) {
            const allReviews = await Review.find({ photographerId });
            const totalRating = allReviews.reduce((sum, r) => sum + r.rating, 0);
            photographer.rating = totalRating / allReviews.length;
            photographer.reviewsCount = allReviews.length;
            await photographer.save();
        }

        res.status(201).json(review);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

const getPhotographerReviews = async (req, res) => {
    try {
        const reviews = await Review.find({ photographerId: req.params.id })
            .populate('customerId', 'firstName lastName profilePicture')
            .sort({ createdAt: -1 });
        res.json(reviews);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

module.exports = { createReview, getPhotographerReviews };