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

75.46% Statements 203/269
51.16% Branches 22/43
100% Functions 2/2
75.46% Lines 203/269

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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 2701x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 8x 8x 8x 1x 1x 1x 8x   7x 1x 7x     8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 7x 7x 7x 2x 2x 2x   2x   2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 1x 1x 2x 2x 2x           2x 2x 2x               2x 2x 2x                   2x 2x 2x                           2x 2x 2x             2x 2x 2x                           2x 2x 2x                 2x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import { Session } from "next-auth";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { logger } from "@/lib/logging";
import { createPromotionSchema } from "@/lib/promotions/validators";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import type { AuthenticatedUser } from '@/lib/api/middleware/types';
 
/**
 * GET /api/admin/promotions
 * Get all promotions with filters
 */
async function handleGet(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const searchParams = request.nextUrl.searchParams;
  const page = parseInt(searchParams.get("page") || "1");
  const limit = parseInt(searchParams.get("limit") || "20");
  const search = searchParams.get("search") || "";
  const type = searchParams.get("type") || "";
  const status = searchParams.get("status") || "";
 
  const skip = (page - 1) * limit;
 
  const where: Prisma.PromotionWhereInput = {};
 
  if (search) {
    where.OR = [
      { name: { contains: search } },
      { displayName: { contains: search } },
      { description: { contains: search } },
    ];
  }
 
  if (type) {
    where.type = type as Prisma.EnumPromotionTypeFilter;
  }
 
  const now = new Date();
  if (status === "active") {
    where.isActive = true;
    where.startDate = { lte: now };
    where.endDate = { gte: now };
  } else if (status === "inactive") {
    where.isActive = false;
  } else if (status === "expired") {
    where.endDate = { lt: now };
  } else if (status === "scheduled") {
    where.startDate = { gt: now };
  }
 
  const [promotions, total] = await Promise.all([
    prisma.promotion.findMany({
      where,
      include: {
        codes: { select: { id: true, code: true, usageCount: true } },
        targetProducts: {
          include: { product: { select: { id: true, title: true } } }},
        targetCategories: {
          include: { category: { select: { id: true, title: true } } }},
        _count: { select: { usages: true, codes: true } }},
      skip,
      take: limit,
      orderBy: [{ isActive: "desc" }, { priority: "desc" }, { createdAt: "desc" }]}),
    prisma.promotion.count({ where }),
  ]);
 
  // Add computed status to each promotion
  const mapped = promotions.map((p) => {
    let computedStatus: "active" | "inactive" | "expired" | "scheduled" =
      "inactive";
    if (!p.isActive) {
      computedStatus = "inactive";
    } else if (new Date(p.endDate) < now) {
      computedStatus = "expired";
    } else if (new Date(p.startDate) > now) {
      computedStatus = "scheduled";
    } else {
      computedStatus = "active";
    }
 
    return {
      ...p,
      computedStatus,
      usageCount: p._count.usages,
      codesCount: p._count.codes};
  });
 
  return successResponse({
    promotions: mapped,
    pagination: {
      page,
      limit,
      total,
      pages: Math.ceil(total / limit)}});
}
 
/**
 * POST /api/admin/promotions
 * Create a new promotion
 */
async function handlePost(
  request: NextRequest,
  _context: RouteContext | undefined,
  _session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
 
  // Validate input
  const validationResult = createPromotionSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation("Validation failed", validationResult.error.issues);
  }
 
  const data = validationResult.data;
 
  // Create promotion with all related data in a transaction
  const promotion = await prisma.$transaction(async (tx) => {
    // Create the main promotion
    const promo = await tx.promotion.create({
      data: {
        name: data.name,
        displayName: data.displayName,
        description: data.description,
        type: data.type,
        discountType: data.discountType,
        discountValue: data.discountValue,
        startDate: data.startDate,
        endDate: data.endDate,
        isActive: data.isActive ?? true,
        usageLimit: data.usageLimit,
        perCustomerLimit: data.perCustomerLimit,
        minimumPurchase: data.minimumPurchase,
        maximumDiscount: data.maximumDiscount,
        targetType: data.targetType,
        stackable: data.stackable ?? false,
        priority: data.priority ?? 0,
        createdBy: user.id}});
 
    // Create target products
    if (data.targetProductIds && data.targetProductIds.length > 0) {
      await tx.promotionProduct.createMany({
        data: data.targetProductIds.map((productId) => ({
          promotionId: promo.id,
          productId}))});
    }
 
    // Create target categories
    if (data.targetCategoryIds && data.targetCategoryIds.length > 0) {
      await tx.promotionCategory.createMany({
        data: data.targetCategoryIds.map((categoryId) => ({
          promotionId: promo.id,
          categoryId}))});
    }
 
    // Create conditions
    if (data.conditions && data.conditions.length > 0) {
      await tx.promotionCondition.createMany({
        data: data.conditions.map((condition) => ({
          promotionId: promo.id,
          conditionType: condition.conditionType,
          operator: condition.operator,
          value: condition.value}))});
    }
 
    // Create BOGO config
    if (data.bogoConfig && data.type === "BOGO") {
      await tx.bogoPromotion.create({
        data: {
          promotionId: promo.id,
          buyQuantity: data.bogoConfig.buyQuantity,
          getQuantity: data.bogoConfig.getQuantity,
          getProductId: data.bogoConfig.getProductId,
          getCategoryId: data.bogoConfig.getCategoryId,
          discountPercent: data.bogoConfig.discountPercent ?? 100}});
    }
 
    // Create bundle config
    if (data.bundleConfig && data.type === "BUNDLE") {
      const bundle = await tx.bundlePromotion.create({
        data: {
          promotionId: promo.id,
          bundlePrice: data.bundleConfig.bundlePrice}});

      if (data.bundleConfig.products && data.bundleConfig.products.length > 0) {
        await tx.bundleProduct.createMany({
          data: data.bundleConfig.products.map((product) => ({
            bundleId: bundle.id,
            productId: product.productId,
            quantity: product.quantity}))});
      }
    }
 
    // Create free gift config
    if (data.freeGiftConfig && data.type === "FREE_GIFT") {
      await tx.freeGiftPromotion.create({
        data: {
          promotionId: promo.id,
          giftProductId: data.freeGiftConfig.giftProductId,
          giftQuantity: data.freeGiftConfig.giftQuantity ?? 1}});
    }
 
    // Create tiered config
    if (data.tieredConfig && data.type === "TIERED") {
      const tiered = await tx.tieredPromotion.create({
        data: {
          promotionId: promo.id}});

      if (data.tieredConfig.tiers && data.tieredConfig.tiers.length > 0) {
        await tx.promotionTier.createMany({
          data: data.tieredConfig.tiers.map((tier) => ({
            tieredPromotionId: tiered.id,
            minQuantity: tier.minQuantity,
            discountType: tier.discountType,
            discountValue: tier.discountValue}))});
      }
    }
 
    // Create flash sale config
    if (data.flashSaleConfig && data.type === "FLASH_SALE") {
      await tx.flashSale.create({
        data: {
          promotionId: promo.id,
          headline: data.flashSaleConfig.headline,
          subheadline: data.flashSaleConfig.subheadline,
          bannerImage: data.flashSaleConfig.bannerImage,
          countdown: data.flashSaleConfig.countdown ?? true}});
    }
 
    return promo;
  });
 
  // Fetch the complete promotion with all relations
  const completePromotion = await prisma.promotion.findUnique({
    where: { id: promotion.id },
    include: {
      codes: true,
      targetProducts: {
        include: { product: { select: { id: true, title: true } } }},
      targetCategories: {
        include: { category: { select: { id: true, title: true } } }},
      conditions: true,
      bogoConfig: true,
      bundleConfig: {
        include: {
          products: {
            include: { product: { select: { id: true, title: true } } }}}},
      freeGiftConfig: {
        include: { giftProduct: { select: { id: true, title: true } } }},
      tieredConfig: { include: { tiers: true } },
      flashSaleConfig: true}});
 
  logger.info("Promotion created", { category: 'API', promotionId: promotion.id, name: promotion.name });
 
  return createdResponse(completePromotion);
}
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));