All files / src/app/api/admin/hero/promo-banners route.ts

100% Statements 164/164
90% Branches 18/20
100% Functions 3/3
100% Lines 164/164

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 1651x 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 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 3x 3x 7x 7x 7x 7x 10x 4x 4x 4x 4x 4x 1x 1x 4x 6x 6x 6x 10x 5x 5x 5x 5x 5x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 5x 5x 5x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
/**
 * Admin Promo Banners API
 * CRUD operations for promotional banners below hero section
 */
 
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from "@/lib/prisma";
import { z } from "zod";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse
} from "@/lib/api";
 
// Validation schema for creating promo banner
const createPromoBannerSchema = z.object({
  title: z.string().min(1).max(100),
  headline: z.string().min(1).max(100),
  description: z.string().max(255).optional().nullable(),
  ctaText: z.string().min(1).max(50),
 
  // Link - either productId or ctaLink (at least one required)
  productId: z.number().int().positive().optional().nullable(),
  ctaLink: z.string().max(255).optional().nullable(),
 
  // Styling
  imageUrl: z.string().min(1).max(500),
  backgroundColor: z.string().min(1).max(20),
  textColor: z.string().max(20).default("#000000"),
  darkBgColor: z.string().max(20).optional().nullable(),
  darkTextColor: z.string().max(20).optional().nullable(),
 
  // Layout
  size: z.enum(["large", "small"]),
  imagePosition: z.enum(["left", "right"]).default("right"),
  order: z.number().int().min(0).optional(),
 
  // Status
  isActive: z.boolean().default(true),
  startDate: z.string().datetime().optional().nullable(),
  endDate: z.string().datetime().optional().nullable(),
}).refine(
  (data) => data.productId || data.ctaLink,
  { message: "Either productId or ctaLink is required" }
);
 
/**
 * GET /api/admin/hero/promo-banners
 * List all promo banners
 */
async function handleGet(): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const banners = await prisma.promoBanner.findMany({
    orderBy: { order: "asc" },
    include: {
      product: {
        select: {
          id: true,
          title: true,
          price: true,
          discountedPrice: true,
          images: {
            select: {
              id: true,
              url: true,
              thumbnailUrl: true,
            },
            orderBy: { order: "asc" },
            take: 1,
          },
        },
      },
    },
  });
 
  return successResponse({ banners });
}
 
/**
 * POST /api/admin/hero/promo-banners
 * Create new promo banner
 */
async function handlePost(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
 
  // Validate input
  const validationResult = createPromoBannerSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation("Validation failed", validationResult.error.issues);
  }
 
  const validatedData = validationResult.data;
 
  // Check if product exists (if productId provided)
  if (validatedData.productId) {
    const product = await prisma.product.findUnique({
      where: { id: validatedData.productId },
    });
 
    if (!product) {
      throw ApiError.notFound("Product");
    }
  }
 
  // Get max order if not provided
  let order = validatedData.order;
  if (order === undefined) {
    const maxOrder = await prisma.promoBanner.aggregate({
      _max: { order: true },
    });
    order = (maxOrder._max.order ?? -1) + 1;
  }
 
  const banner = await prisma.promoBanner.create({
    data: {
      title: validatedData.title,
      headline: validatedData.headline,
      description: validatedData.description,
      ctaText: validatedData.ctaText,
      productId: validatedData.productId,
      ctaLink: validatedData.ctaLink,
      imageUrl: validatedData.imageUrl,
      backgroundColor: validatedData.backgroundColor,
      textColor: validatedData.textColor,
      darkBgColor: validatedData.darkBgColor,
      darkTextColor: validatedData.darkTextColor,
      size: validatedData.size,
      imagePosition: validatedData.imagePosition,
      order,
      isActive: validatedData.isActive,
      startDate: validatedData.startDate ? new Date(validatedData.startDate) : null,
      endDate: validatedData.endDate ? new Date(validatedData.endDate) : null,
    },
    include: {
      product: {
        select: {
          id: true,
          title: true,
          price: true,
          discountedPrice: true,
          images: {
            select: {
              id: true,
              url: true,
              thumbnailUrl: true,
            },
            orderBy: { order: "asc" },
            take: 1,
          },
        },
      },
    },
  });
 
  return createdResponse({ banner });
}
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));