first commit
This commit is contained in:
96
app/api/reviews/[id]/helpful/route.ts
Normal file
96
app/api/reviews/[id]/helpful/route.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await auth()
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id: reviewId } = await params
|
||||
|
||||
// Check if review exists
|
||||
const review = await prisma.review.findUnique({
|
||||
where: { id: reviewId }
|
||||
})
|
||||
|
||||
if (!review) {
|
||||
return NextResponse.json({ error: 'Review not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Check if user already voted
|
||||
const existingVote = await prisma.reviewHelpfulVote.findUnique({
|
||||
where: {
|
||||
reviewId_userId: {
|
||||
reviewId,
|
||||
userId: session.user.id
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (existingVote) {
|
||||
// Remove the vote (toggle)
|
||||
await prisma.reviewHelpfulVote.delete({
|
||||
where: { id: existingVote.id }
|
||||
})
|
||||
|
||||
// Update helpful count
|
||||
const updatedReview = await prisma.review.update({
|
||||
where: { id: reviewId },
|
||||
data: {
|
||||
helpfulVotes: {
|
||||
decrement: 1
|
||||
}
|
||||
},
|
||||
select: {
|
||||
helpfulVotes: true
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Helpful vote removed',
|
||||
hasVoted: false,
|
||||
totalVotes: updatedReview.helpfulVotes
|
||||
})
|
||||
} else {
|
||||
// Add the vote
|
||||
await prisma.reviewHelpfulVote.create({
|
||||
data: {
|
||||
reviewId,
|
||||
userId: session.user.id
|
||||
}
|
||||
})
|
||||
|
||||
// Update helpful count
|
||||
const updatedReview = await prisma.review.update({
|
||||
where: { id: reviewId },
|
||||
data: {
|
||||
helpfulVotes: {
|
||||
increment: 1
|
||||
}
|
||||
},
|
||||
select: {
|
||||
helpfulVotes: true
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Review marked as helpful',
|
||||
hasVoted: true,
|
||||
totalVotes: updatedReview.helpfulVotes
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error voting on review:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to vote on review' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
85
app/api/reviews/[id]/report/route.ts
Normal file
85
app/api/reviews/[id]/report/route.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await auth()
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id: reviewId } = await params
|
||||
const body = await request.json()
|
||||
const { reason, comment } = body
|
||||
|
||||
// Validate reason
|
||||
const validReasons = ['SPAM', 'INAPPROPRIATE', 'FAKE', 'OFFENSIVE', 'OTHER']
|
||||
if (!reason || !validReasons.includes(reason)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Valid reason is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Check if review exists
|
||||
const review = await prisma.review.findUnique({
|
||||
where: { id: reviewId }
|
||||
})
|
||||
|
||||
if (!review) {
|
||||
return NextResponse.json({ error: 'Review not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Check if user already reported this review
|
||||
const existingReport = await prisma.reviewReport.findUnique({
|
||||
where: {
|
||||
reviewId_userId: {
|
||||
reviewId,
|
||||
userId: session.user.id
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (existingReport) {
|
||||
return NextResponse.json(
|
||||
{ error: 'You have already reported this review' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Create the report
|
||||
await prisma.reviewReport.create({
|
||||
data: {
|
||||
reviewId,
|
||||
userId: session.user.id,
|
||||
reason,
|
||||
comment
|
||||
}
|
||||
})
|
||||
|
||||
// Update report count
|
||||
await prisma.review.update({
|
||||
where: { id: reviewId },
|
||||
data: {
|
||||
reportCount: {
|
||||
increment: 1
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Review reported successfully. Thank you for helping us maintain quality.'
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error reporting review:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to report review' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
164
app/api/reviews/[id]/route.ts
Normal file
164
app/api/reviews/[id]/route.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params
|
||||
|
||||
const review = await prisma.review.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
image: true,
|
||||
}
|
||||
},
|
||||
product: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
}
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
helpfulVotedBy: true,
|
||||
reportedBy: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (!review) {
|
||||
return NextResponse.json({ error: 'Review not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json(review)
|
||||
} catch (error) {
|
||||
console.error('Error fetching review:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch review' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await auth()
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id } = await params
|
||||
const body = await request.json()
|
||||
const { rating, title, comment, images } = body
|
||||
|
||||
// Find the review and check ownership
|
||||
const existingReview = await prisma.review.findUnique({
|
||||
where: { id }
|
||||
})
|
||||
|
||||
if (!existingReview) {
|
||||
return NextResponse.json({ error: 'Review not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
if (existingReview.userId !== session.user.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
// Validate rating if provided
|
||||
if (rating && (rating < 1 || rating > 5)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Rating must be between 1 and 5' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const updatedReview = await prisma.review.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(rating && { rating }),
|
||||
...(title !== undefined && { title }),
|
||||
...(comment !== undefined && { comment }),
|
||||
...(images && { images }),
|
||||
isApproved: false, // Reset approval status when edited
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
image: true,
|
||||
}
|
||||
},
|
||||
product: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
review: updatedReview,
|
||||
message: 'Review updated successfully. It will be visible after admin approval.'
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error updating review:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to update review' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await auth()
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id } = await params
|
||||
|
||||
// Find the review and check ownership or admin access
|
||||
const existingReview = await prisma.review.findUnique({
|
||||
where: { id }
|
||||
})
|
||||
|
||||
if (!existingReview) {
|
||||
return NextResponse.json({ error: 'Review not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
if (existingReview.userId !== session.user.id && session.user.role !== 'ADMIN') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
await prisma.review.delete({
|
||||
where: { id }
|
||||
})
|
||||
|
||||
return NextResponse.json({ message: 'Review deleted successfully' })
|
||||
} catch (error) {
|
||||
console.error('Error deleting review:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to delete review' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
130
app/api/reviews/route.ts
Normal file
130
app/api/reviews/route.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
// GET /api/reviews - Get reviews with filters
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await auth()
|
||||
const { searchParams } = new URL(request.url)
|
||||
const productId = searchParams.get('productId')
|
||||
const userId = searchParams.get('userId')
|
||||
const rating = searchParams.get('rating')
|
||||
const page = parseInt(searchParams.get('page') || '1')
|
||||
const limit = parseInt(searchParams.get('limit') || '10')
|
||||
const skip = (page - 1) * limit
|
||||
const withStats = searchParams.get('withStats') === 'true'
|
||||
|
||||
const where: any = {
|
||||
isApproved: true, // Only show approved reviews publicly
|
||||
}
|
||||
|
||||
if (productId) where.productId = productId
|
||||
if (userId) where.userId = userId
|
||||
if (rating) where.rating = parseInt(rating)
|
||||
|
||||
const [reviews, total, aggregateStats] = await Promise.all([
|
||||
prisma.review.findMany({
|
||||
where,
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
image: true,
|
||||
// Add user credibility for social proof
|
||||
_count: {
|
||||
select: {
|
||||
reviews: true, // Total reviews by this user
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
product: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
}
|
||||
},
|
||||
helpfulVotedBy: session?.user?.id ? {
|
||||
where: {
|
||||
userId: session.user.id
|
||||
}
|
||||
} : false,
|
||||
_count: {
|
||||
select: {
|
||||
helpfulVotedBy: true,
|
||||
reportedBy: true,
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: [
|
||||
{ helpfulVotedBy: { _count: 'desc' } }, // Most helpful first
|
||||
{ rating: 'desc' }, // Higher ratings next
|
||||
{ createdAt: 'desc' } // Then by recency
|
||||
],
|
||||
skip,
|
||||
take: limit,
|
||||
}),
|
||||
prisma.review.count({ where }),
|
||||
// Get aggregate stats for social proof
|
||||
withStats ? prisma.review.groupBy({
|
||||
by: ['rating'],
|
||||
where: productId ? { productId, isApproved: true } : { isApproved: true },
|
||||
_count: {
|
||||
rating: true,
|
||||
},
|
||||
}) : null,
|
||||
])
|
||||
|
||||
// Calculate enhanced social proof metrics
|
||||
const enhancedReviews = reviews.map(review => ({
|
||||
...review,
|
||||
// Add social proof indicators
|
||||
isVerifiedReviewer: review.user._count.reviews >= 3, // Users with 3+ reviews are "verified"
|
||||
helpfulnessScore: review._count.helpfulVotedBy,
|
||||
// Add time-based freshness
|
||||
isFresh: new Date(review.createdAt) > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // Last 30 days
|
||||
}))
|
||||
|
||||
// Calculate rating distribution for social proof
|
||||
let ratingDistribution = null
|
||||
if (aggregateStats) {
|
||||
const totalReviews = aggregateStats.reduce((sum, stat) => sum + stat._count.rating, 0)
|
||||
ratingDistribution = {
|
||||
1: 0, 2: 0, 3: 0, 4: 0, 5: 0,
|
||||
...aggregateStats.reduce((acc, stat) => ({
|
||||
...acc,
|
||||
[stat.rating]: Math.round((stat._count.rating / totalReviews) * 100)
|
||||
}), {})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
reviews: enhancedReviews,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
// Enhanced social proof data
|
||||
socialProof: {
|
||||
totalReviews: total,
|
||||
averageRating: enhancedReviews.length > 0
|
||||
? enhancedReviews.reduce((sum, review) => sum + review.rating, 0) / enhancedReviews.length
|
||||
: 0,
|
||||
ratingDistribution,
|
||||
verifiedReviewersCount: enhancedReviews.filter(r => r.isVerifiedReviewer).length,
|
||||
recentReviewsCount: enhancedReviews.filter(r => r.isFresh).length,
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error fetching reviews:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch reviews' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user