All files / src/app/api/admin/reviews route.ts

95.29% Statements 162/170
83.33% Branches 25/30
100% Functions 1/1
95.29% Lines 162/170

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 1711x 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 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x     9x 9x 9x 9x 9x 9x 9x 9x     9x 9x     9x 9x 1x 1x 9x 9x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 1x 1x 9x     9x 9x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 8x 8x 8x 8x 8x 8x 8x 8x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 8x 8x 8x 8x 8x 8x 9x 9x 9x 40x 40x 40x 9x 9x 9x 9x 9x 9x 9x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { z } from "zod";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { } from "@/lib/api/middleware";
 
/**
 * Query schema for GET requests
 */
const querySchema = z.object({
  page: z.coerce.number().int().positive().default(1),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  sortBy: z.enum(["recent", "rating_high", "rating_low"]).default("recent"),
  productId: z.coerce.number().int().positive().optional(),
  userId: z.coerce.number().int().positive().optional(),
  rating: z.coerce.number().int().min(1).max(5).optional(),
  search: z.string().optional() });
 
/**
 * GET /api/admin/reviews
 * Get all reviews with filters (admin only)
 */
async function handleGet(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const searchParams = request.nextUrl.searchParams;
 
  // Validate query parameters
  const validationResult = querySchema.safeParse({
    page: searchParams.get("page") || 1,
    limit: searchParams.get("limit") || 20,
    sortBy: searchParams.get("sortBy") || "recent",
    productId: searchParams.get("productId") || undefined,
    userId: searchParams.get("userId") || undefined,
    rating: searchParams.get("rating") || undefined,
    search: searchParams.get("search") || undefined });
 
  if (!validationResult.success) {
    throw ApiError.validation("Invalid query parameters", validationResult.error.issues);
  }
 
  const query = validationResult.data;
  const skip = (query.page - 1) * query.limit;
 
  // Build where clause
  const where: Prisma.ReviewWhereInput = {};
 
  if (query.productId) {
    where.productId = query.productId;
  }
 
  if (query.userId) {
    where.userId = query.userId;
  }
 
  if (query.rating) {
    where.rating = query.rating;
  }
 
  if (query.search) {
    where.OR = [
      { comment: { contains: query.search } },
      { product: { title: { contains: query.search } } },
      { user: { name: { contains: query.search } } },
      { user: { email: { contains: query.search } } },
    ];
  }
 
  // Build sort order
  let orderBy: Record<string, string> = { createdAt: "desc" };
  switch (query.sortBy) {
    case "rating_high":
      orderBy = { rating: "desc" };
      break;
    case "rating_low":
      orderBy = { rating: "asc" };
      break;
    case "recent":
    default:
      orderBy = { createdAt: "desc" };
  }
 
  const [reviews, total, stats] = await Promise.all([
    prisma.review.findMany({
      where,
      include: {
        product: {
          select: {
            id: true,
            title: true,
            images: {
              select: { url: true, thumbnailUrl: true },
              take: 1 } } },
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            image: true } },
        helpful: {
          select: {
            helpful: true } } },
      orderBy,
      skip,
      take: query.limit }),
    prisma.review.count({ where }),
    prisma.review.aggregate({
      _avg: { rating: true },
      _count: { rating: true } }),
  ]);
 
  // Get rating distribution
  const distribution = await prisma.review.groupBy({
    by: ["rating"],
    _count: true });
 
  // Transform reviews with helpful counts
  const transformedReviews = reviews.map((review) => {
    const helpfulCount = review.helpful.filter((h) => h.helpful).length;
    const notHelpfulCount = review.helpful.filter((h) => !h.helpful).length;
 
    return {
      id: review.id,
      rating: review.rating,
      comment: review.comment,
      createdAt: review.createdAt,
      updatedAt: review.updatedAt,
      product: {
        id: review.product.id,
        title: review.product.title,
        image:
          review.product.images[0]?.thumbnailUrl ||
          review.product.images[0]?.url ||
          null },
      user: {
        id: review.user.id,
        name: review.user.name,
        email: review.user.email,
        image: review.user.image },
      helpfulCount,
      notHelpfulCount };
  });
 
  return successResponse({
    reviews: transformedReviews,
    stats: {
      totalReviews: stats._count.rating,
      averageRating: stats._avg.rating || 0,
      distribution: Object.fromEntries(
        [1, 2, 3, 4, 5].map((rating) => [
          rating,
          distribution.find((d) => d.rating === rating)?._count || 0,
        ])
      ) },
    pagination: {
      page: query.page,
      limit: query.limit,
      total,
      pages: Math.ceil(total / query.limit) } });
}
 
export const GET = withErrorHandling(withAdmin(handleGet));