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

92.26% Statements 179/194
90.47% Branches 19/21
100% Functions 2/2
92.26% Lines 179/194

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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 1951x 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 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 2x 2x 2x 2x 2x 9x 2x 2x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 9x 9x 9x 5x 5x 9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 9x 9x 9x 9x 9x 9x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from "next/server";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { z } from "zod";
 
// ============================================================================
// VALIDATION SCHEMAS
// ============================================================================
 
const createProductSchema = z.object({
  title: z.string().min(1, "Title is required"),
  description: z.string().optional().nullable(),
  price: z.number().positive("Price must be positive"),
  discountedPrice: z.number().positive().optional().nullable(),
  stock: z.number().int().nonnegative().optional(),
  sku: z.string().optional().nullable(),
  categoryId: z.number().int().positive("Category ID is required"),
  specifications: z.record(z.string(), z.unknown()).optional().nullable(),
  // Accept array of strings, a JSON string that parses to an array, or null
  details: z.union([
    z.array(z.string()),
    z.string().transform((val, ctx) => {
      try {
        const parsed = JSON.parse(val);
        if (Array.isArray(parsed)) {
          return parsed as string[];
        }
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: "Details must be an array of strings" });
        return z.NEVER;
      } catch {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: "Invalid JSON string for details" });
        return z.NEVER;
      }
    }),
    z.null(),
  ]).optional() });
 
// ============================================================================
// TYPES
// ============================================================================
 
interface ProductListItem {
  id: number;
  title: string;
  sku: string | null;
  price: number;
  discountedPrice: number;
  stock: number;
  category: { title: string };
  images: Array<{ id: number; url: string; thumbnailUrl: string | null; order: number }>;
  rating: number;
  reviewCount: number;
  reorderLevel: number;
}
 
// ============================================================================
// HANDLERS
// ============================================================================
 
/**
 * GET /api/admin/products
 * Get all products with filters for admin management
 */
async function handleGet(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<ProductListItem[]> | ApiErrorResponse>> {
  const searchParams = request.nextUrl.searchParams;
  const page = searchParams.get("page") ? parseInt(searchParams.get("page")!) : 1;
  const limit = searchParams.get("limit") ? parseInt(searchParams.get("limit")!) : 20;
  const search = searchParams.get("search") || "";
  const lowStockOnly = searchParams.get("lowStockOnly") === "true";
 
  const skip = (page - 1) * limit;
 
  const where: Prisma.ProductWhereInput = {};
  if (search) {
    where.OR = [
      { title: { contains: search } },
      { sku: { contains: search } },
    ];
  }
  if (lowStockOnly) {
    where.stock = { lte: 10 };
  }
 
  const [products, total] = await Promise.all([
    prisma.product.findMany({
      where,
      select: {
        id: true,
        title: true,
        sku: true,
        price: true,
        discountedPrice: true,
        stock: true,
        category: { select: { title: true } },
        images: { select: { id: true, url: true, thumbnailUrl: true, order: true }, orderBy: { order: 'asc' } },
        reviews: { select: { rating: true } } },
      skip,
      take: limit,
      orderBy: { createdAt: "desc" } }),
    prisma.product.count({ where }),
  ]);
 
  const mapped: ProductListItem[] = products.map((p) => {
    const avgRating =
      p.reviews.length > 0
        ? Math.round(
            (p.reviews.reduce((sum, r) => sum + r.rating, 0) / p.reviews.length) * 10
          ) / 10
        : 0;
 
    return {
      ...p,
      rating: avgRating,
      reviewCount: p.reviews.length,
      reorderLevel: 10, // Default reorder level (inventory system not yet implemented)
    };
  });
 
  // Return response with pagination metadata
  return NextResponse.json({
    success: true,
    data: mapped,
    pagination: {
      page,
      limit,
      total,
      pages: Math.ceil(total / limit) } });
}
 
/**
 * POST /api/admin/products
 * Create new product
 */
async function handlePost(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<Prisma.ProductGetPayload<object>> | ApiErrorResponse>> {
  const body = await request.json();
 
  // Validate request body
  const validationResult = createProductSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation(
      "Invalid product data",
      validationResult.error.issues
    );
  }
 
  const {
    title,
    description,
    price,
    discountedPrice,
    stock,
    sku,
    categoryId,
    specifications,
    details } = validationResult.data;
 
  const product = await prisma.product.create({
    data: {
      title,
      description,
      price,
      discountedPrice: discountedPrice || price,
      stock: stock || 0,
      sku,
      category: { connect: { id: categoryId } },
      ...(specifications !== undefined && { specifications: specifications as Prisma.InputJsonValue }),
      ...(details !== undefined && { details: JSON.stringify(details) }) } });
 
  return successResponse(product);
}
 
// ============================================================================
// EXPORTS
// ============================================================================
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));