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

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
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";
import type { LoyaltyTransaction } from "@prisma/client";

interface LoyaltyAnalyticsData {
  summary: {
    totalMembers: number;
    newMembers: number;
    activeMembers: number;
    engagementRate: number;
  };
  points: {
    earned: number;
    redeemed: number;
    expired: number;
    adjusted: number;
    netChange: number;
    totalOutstanding: number;
    estimatedLiability: number;
  };
  transactions: {
    total: number;
    earns: number;
    redemptions: number;
    expirations: number;
    adjustments: number;
    avgPointsPerEarn: number;
    avgRedemptionSize: number;
  };
  topEarners: Array<{
    userId: number;
    name: string | null;
    email: string;
    currentPoints: number;
    lifetimePoints: number;
  }>;
  recentRedemptions: Array<{
    id: number;
    userId: number | undefined;
    userName: string | null | undefined;
    points: number;
    description: string | null;
    createdAt: Date;
  }>;
  pointsTrend: Array<{
    date: string;
    earned: number;
    redeemed: number;
    expired: number;
    net: number;
  }>;
  dateRange: {
    startDate: string;
    endDate: string;
  };
}

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

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

  // Get loyalty data
  const [
    totalMembers,
    newMembers,
    transactions,
    topEarners,
    redemptions,
  ] = await Promise.all([
    // Total members with loyalty points
    prisma.customerLoyalty.count(),

    // New members in period (users who made their first transaction)
    prisma.customerLoyalty.count({
      where: {
        transactions: {
          some: {
            createdAt: { gte: startDate, lte: endDate } } } } }),

    // All transactions in period
    prisma.loyaltyTransaction.findMany({
      where: {
        createdAt: { gte: startDate, lte: endDate } },
      include: {
        customerLoyalty: {
          include: {
            user: {
              select: { id: true, name: true, email: true } } } } } }),

    // Top point earners
    prisma.customerLoyalty.findMany({
      take: 10,
      orderBy: { lifetimePoints: "desc" },
      include: {
        user: {
          select: { id: true, name: true, email: true } } } }),

    // Recent redemptions
    prisma.loyaltyTransaction.findMany({
      where: {
        type: "redeem",
        createdAt: { gte: startDate, lte: endDate } },
      take: 20,
      orderBy: { createdAt: "desc" },
      include: {
        customerLoyalty: {
          include: {
            user: {
              select: { id: true, name: true, email: true } } } } } }),
  ]);

  // Calculate metrics from transactions
  const earnTransactions = transactions.filter((t: LoyaltyTransaction) => t.type === "earn");
  const redeemTransactions = transactions.filter((t: LoyaltyTransaction) => t.type === "redeem");
  const expireTransactions = transactions.filter((t: LoyaltyTransaction) => t.type === "expire");
  const adjustTransactions = transactions.filter((t: LoyaltyTransaction) => t.type === "adjust");

  const pointsEarned = earnTransactions.reduce((sum: number, t: LoyaltyTransaction) => sum + t.points, 0);
  const pointsRedeemed = redeemTransactions.reduce(
    (sum: number, t: LoyaltyTransaction) => sum + Math.abs(t.points),
    0
  );
  const pointsExpired = expireTransactions.reduce(
    (sum: number, t: LoyaltyTransaction) => sum + Math.abs(t.points),
    0
  );
  const pointsAdjusted = adjustTransactions.reduce(
    (sum: number, t: LoyaltyTransaction) => sum + t.points,
    0
  );

  // Daily points trend
  const dailyPoints: Record<
    string,
    { earned: number; redeemed: number; expired: number }
  > = {};
  transactions.forEach((t) => {
    const dateKey = t.createdAt.toISOString().split("T")[0];
    if (!dailyPoints[dateKey]) {
      dailyPoints[dateKey] = { earned: 0, redeemed: 0, expired: 0 };
    }
    if (t.type === "earn") {
      dailyPoints[dateKey].earned += t.points;
    } else if (t.type === "redeem") {
      dailyPoints[dateKey].redeemed += Math.abs(t.points);
    } else if (t.type === "expire") {
      dailyPoints[dateKey].expired += Math.abs(t.points);
    }
  });

  const pointsTrend = Object.entries(dailyPoints)
    .map(([date, data]) => ({
      date,
      ...data,
      net: data.earned - data.redeemed - data.expired }))
    .sort((a, b) => a.date.localeCompare(b.date));

  // Get total outstanding points
  const totalPointsResult = await prisma.customerLoyalty.aggregate({
    _sum: {
      totalPoints: true,
      lifetimePoints: true } });

  const totalOutstandingPoints = totalPointsResult._sum.totalPoints || 0;

  // Estimated liability value (assuming $0.01 per point redemption rate)
  const pointValue = 0.01;
  const estimatedLiability = totalOutstandingPoints * pointValue;

  // Engagement metrics
  const activeMembers = new Set(
    transactions.map((t) => t.customerLoyaltyId)
  ).size;
  const engagementRate =
    totalMembers > 0 ? (activeMembers / totalMembers) * 100 : 0;

  // Average points per earn transaction
  const avgPointsPerEarn =
    earnTransactions.length > 0
      ? pointsEarned / earnTransactions.length
      : 0;

  // Average redemption size
  const avgRedemptionSize =
    redeemTransactions.length > 0
      ? pointsRedeemed / redeemTransactions.length
      : 0;

  const analytics: LoyaltyAnalyticsData = {
    summary: {
      totalMembers,
      newMembers,
      activeMembers,
      engagementRate },
    points: {
      earned: pointsEarned,
      redeemed: pointsRedeemed,
      expired: pointsExpired,
      adjusted: pointsAdjusted,
      netChange: pointsEarned - pointsRedeemed - pointsExpired + pointsAdjusted,
      totalOutstanding: totalOutstandingPoints,
      estimatedLiability },
    transactions: {
      total: transactions.length,
      earns: earnTransactions.length,
      redemptions: redeemTransactions.length,
      expirations: expireTransactions.length,
      adjustments: adjustTransactions.length,
      avgPointsPerEarn,
      avgRedemptionSize },
    topEarners: topEarners.map((a) => ({
      userId: a.userId,
      name: a.user.name,
      email: a.user.email,
      currentPoints: a.totalPoints,
      lifetimePoints: a.lifetimePoints })),
    recentRedemptions: redemptions.map((r) => ({
      id: r.id,
      userId: r.customerLoyalty?.user?.id,
      userName: r.customerLoyalty?.user?.name || r.customerLoyalty?.user?.email,
      points: Math.abs(r.points),
      description: r.description,
      createdAt: r.createdAt })),
    pointsTrend,
    dateRange: {
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString() } };

  return successResponse(analytics);
}

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