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

0% Statements 0/204
100% Branches 0/0
0% Functions 0/1
0% Lines 0/204

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                                                                                                                                                                                                                                                                                                                                                                                                                         
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { } from "@/lib/api/middleware";

/**
 * GET /api/admin/promotions/analytics
 * Get overall promotion analytics
 */
async function handleGet(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const searchParams = request.nextUrl.searchParams;
  const startDateParam = searchParams.get("startDate");
  const endDateParam = searchParams.get("endDate");

  // Default to last 30 days if no date range specified
  const endDate = endDateParam ? new Date(endDateParam) : new Date();
  const startDate = startDateParam
    ? new Date(startDateParam)
    : new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000);

  // Get all promotions with their usage data
  const [
    promotions,
    promoCodeUsage,
    ordersWithPromo,
    ordersWithoutPromo,
    loyaltyTransactions,
    referralStats,
  ] = await Promise.all([
    // All promotions
    prisma.promotion.findMany({
      where: {
        OR: [
          { startDate: { gte: startDate, lte: endDate } },
          { endDate: { gte: startDate, lte: endDate } },
          {
            AND: [
              { startDate: { lte: startDate } },
              { endDate: { gte: endDate } },
            ] },
        ] },
      include: {
        _count: {
          select: { usages: true } } } }),

    // Promo code usage in period
    prisma.promotionUsage.findMany({
      where: {
        usedAt: { gte: startDate, lte: endDate } },
      include: {
        promotion: true,
        order: {
          select: { total: true } } } }),

    // Orders with promotions
    prisma.order.findMany({
      where: {
        createdAt: { gte: startDate, lte: endDate },
        promotionUsages: { some: {} } },
      select: {
        total: true,
        promotionUsages: {
          select: {
            discountAmount: true } } } }),

    // Orders without promotions
    prisma.order.findMany({
      where: {
        createdAt: { gte: startDate, lte: endDate },
        promotionUsages: { none: {} } },
      select: { total: true } }),

    // Loyalty transactions
    prisma.loyaltyTransaction.findMany({
      where: {
        createdAt: { gte: startDate, lte: endDate } } }),

    // Referral stats
    prisma.referral.groupBy({
      by: ["status"],
      where: {
        createdAt: { gte: startDate, lte: endDate } },
      _count: true }),
  ]);

  // Calculate metrics
  const totalDiscountGiven = promoCodeUsage.reduce(
    (sum, usage) => sum + (usage.discountAmount || 0),
    0
  );

  const revenueWithPromo = ordersWithPromo.reduce(
    (sum, order) => sum + order.total,
    0
  );
  const revenueWithoutPromo = ordersWithoutPromo.reduce(
    (sum, order) => sum + order.total,
    0
  );

  const avgOrderValueWithPromo =
    ordersWithPromo.length > 0
      ? revenueWithPromo / ordersWithPromo.length
      : 0;
  const avgOrderValueWithoutPromo =
    ordersWithoutPromo.length > 0
      ? revenueWithoutPromo / ordersWithoutPromo.length
      : 0;

  // Loyalty metrics
  const pointsEarned = loyaltyTransactions
    .filter((t) => t.type === "EARN")
    .reduce((sum, t) => sum + t.points, 0);
  const pointsRedeemed = loyaltyTransactions
    .filter((t) => t.type === "REDEEM")
    .reduce((sum, t) => sum + Math.abs(t.points), 0);
  const pointsExpired = loyaltyTransactions
    .filter((t) => t.type === "EXPIRE")
    .reduce((sum, t) => sum + Math.abs(t.points), 0);

  // Referral metrics
  const referralMetrics = {
    total: referralStats.reduce((sum, r) => sum + r._count, 0),
    pending: referralStats.find((r) => r.status === "PENDING")?._count || 0,
    completed:
      referralStats.find((r) => r.status === "COMPLETED")?._count || 0,
    rewarded: referralStats.find((r) => r.status === "REWARDED")?._count || 0 };

  // Top performing promotions
  const topPromotions = promotions
    .map((promo) => ({
      id: promo.id,
      name: promo.name,
      type: promo.type,
      usageCount: promo._count.usages,
      discountValue: promo.discountValue,
      discountType: promo.discountType,
      isActive: promo.isActive }))
    .sort((a, b) => b.usageCount - a.usageCount)
    .slice(0, 10);

  // Daily usage trend
  const dailyUsage: Record<string, number> = {};
  promoCodeUsage.forEach((usage) => {
    const dateKey = usage.usedAt.toISOString().split("T")[0];
    dailyUsage[dateKey] = (dailyUsage[dateKey] || 0) + 1;
  });

  const usageTrend = Object.entries(dailyUsage)
    .map(([date, count]) => ({ date, count }))
    .sort((a, b) => a.date.localeCompare(b.date));

  const analytics = {
    summary: {
      totalPromotions: promotions.length,
      activePromotions: promotions.filter((p) => p.isActive).length,
      totalUsage: promoCodeUsage.length,
      totalDiscountGiven,
      ordersWithPromo: ordersWithPromo.length,
      ordersWithoutPromo: ordersWithoutPromo.length },
    revenue: {
      withPromo: revenueWithPromo,
      withoutPromo: revenueWithoutPromo,
      total: revenueWithPromo + revenueWithoutPromo,
      promoPercentage:
        revenueWithPromo + revenueWithoutPromo > 0
          ? (revenueWithPromo / (revenueWithPromo + revenueWithoutPromo)) * 100
          : 0 },
    averageOrderValue: {
      withPromo: avgOrderValueWithPromo,
      withoutPromo: avgOrderValueWithoutPromo,
      difference: avgOrderValueWithPromo - avgOrderValueWithoutPromo,
      percentageDifference:
        avgOrderValueWithoutPromo > 0
          ? ((avgOrderValueWithPromo - avgOrderValueWithoutPromo) /
              avgOrderValueWithoutPromo) *
            100
          : 0 },
    loyalty: {
      pointsEarned,
      pointsRedeemed,
      pointsExpired,
      netPointsOutstanding: pointsEarned - pointsRedeemed - pointsExpired,
      redemptionRate:
        pointsEarned > 0 ? (pointsRedeemed / pointsEarned) * 100 : 0 },
    referrals: referralMetrics,
    topPromotions,
    usageTrend,
    dateRange: {
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString() } };

  return successResponse(analytics);
}

export const GET = withErrorHandling(withAdmin(handleGet));