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

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

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                                                                                                                                                                                                                                                                                                                                                                                         
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/affiliates/analytics
 * Get affiliate program analytics
 */
async function handleGet(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { searchParams } = new URL(request.url);
  const period = searchParams.get("period") || "30d";

  // Calculate date range
  let startDate: Date;
  const endDate = new Date();

  switch (period) {
    case "7d":
      startDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
      break;
    case "30d":
      startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
      break;
    case "90d":
      startDate = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
      break;
    default:
      startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  }

  // Get overall stats
  const [
    totalAffiliates,
    activeAffiliates,
    pendingAffiliates,
    totalClicks,
    totalSales,
    totalCommissions,
    pendingCommissions,
    paidCommissions,
    affiliatesByTier,
    topAffiliates,
  ] = await Promise.all([
    // Total affiliates
    prisma.affiliate.count(),

    // Active affiliates
    prisma.affiliate.count({ where: { status: "ACTIVE" } }),

    // Pending affiliates
    prisma.affiliate.count({ where: { status: "PENDING" } }),

    // Total clicks in period
    prisma.affiliateClick.count({
      where: { clickedAt: { gte: startDate, lte: endDate } } }),

    // Total sales in period
    prisma.affiliateSale.aggregate({
      where: { createdAt: { gte: startDate, lte: endDate } },
      _count: { id: true },
      _sum: { orderTotal: true, commissionAmount: true } }),

    // Total commissions (all time)
    prisma.affiliateSale.aggregate({
      _sum: { commissionAmount: true } }),

    // Pending commissions
    prisma.affiliateSale.aggregate({
      where: { status: { in: ["PENDING", "APPROVED"] } },
      _sum: { commissionAmount: true } }),

    // Paid commissions
    prisma.affiliateSale.aggregate({
      where: { status: "PAID" },
      _sum: { commissionAmount: true } }),

    // Affiliates by tier
    prisma.affiliate.groupBy({
      by: ["tier"],
      _count: { id: true } }),

    // Top affiliates
    prisma.affiliate.findMany({
      where: { status: "ACTIVE" },
      orderBy: { totalSales: "desc" },
      take: 10,
      select: {
        id: true,
        code: true,
        userId: true,
        tier: true,
        totalClicks: true,
        totalConversions: true,
        totalSales: true,
        totalEarnings: true,
        conversionRate: true } }),
  ]);

  // Get user info for top affiliates
  const userIds = topAffiliates.map((a) => a.userId);
  const users = await prisma.user.findMany({
    where: { id: { in: userIds } },
    select: { id: true, name: true, email: true } });
  const userMap = new Map(users.map((u) => [u.id, u]));

  // Calculate daily trends
  const dailyClicks = await prisma.$queryRaw<
    { date: string; count: bigint }[]
  >`
    SELECT
      DATE(clicked_at) as date,
      COUNT(*) as count
    FROM affiliate_clicks
    WHERE clicked_at >= ${startDate} AND clicked_at <= ${endDate}
    GROUP BY DATE(clicked_at)
    ORDER BY date ASC
  `;

  const dailySales = await prisma.$queryRaw<
    { date: string; count: bigint; total: number; commission: number }[]
  >`
    SELECT
      DATE(created_at) as date,
      COUNT(*) as count,
      SUM(order_total) as total,
      SUM(commission_amount) as commission
    FROM affiliate_sales
    WHERE created_at >= ${startDate} AND created_at <= ${endDate}
    GROUP BY DATE(created_at)
    ORDER BY date ASC
  `;

  // Calculate conversion rate
  const conversionRate =
    totalClicks > 0
      ? ((totalSales._count.id || 0) / totalClicks) * 100
      : 0;

  return successResponse({
    overview: {
      totalAffiliates,
      activeAffiliates,
      pendingAffiliates,
      totalClicks,
      totalSalesCount: totalSales._count.id || 0,
      totalSalesAmount: totalSales._sum.orderTotal || 0,
      totalCommissionsInPeriod: totalSales._sum.commissionAmount || 0,
      totalCommissionsAllTime: totalCommissions._sum.commissionAmount || 0,
      pendingCommissions: pendingCommissions._sum.commissionAmount || 0,
      paidCommissions: paidCommissions._sum.commissionAmount || 0,
      conversionRate: Math.round(conversionRate * 100) / 100,
      period },
    affiliatesByTier: affiliatesByTier.map((t) => ({
      tier: t.tier,
      count: t._count.id })),
    topAffiliates: topAffiliates.map((a) => ({
      id: a.id,
      code: a.code,
      user: userMap.get(a.userId),
      tier: a.tier,
      totalClicks: a.totalClicks,
      totalConversions: a.totalConversions,
      totalSales: a.totalSales,
      totalEarnings: a.totalEarnings,
      conversionRate: a.conversionRate })),
    trends: {
      clicks: dailyClicks.map((d) => ({
        date: d.date,
        count: Number(d.count) })),
      sales: dailySales.map((d) => ({
        date: d.date,
        count: Number(d.count),
        total: d.total || 0,
        commission: d.commission || 0 })) } });
}

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