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

98.26% Statements 170/173
85% Branches 17/20
100% Functions 2/2
98.26% Lines 170/173

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 1741x 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 1x 1x 1x 1x 1x 4x 4x 1x 1x 4x 4x 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 4x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 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 { z } from "zod";
import {
  withAdmin,
  withErrorHandling,
  createdResponse,
  paginatedResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
 
/**
 * GET /api/admin/affiliates
 * List all affiliates with pagination and filtering
 */
async function handleGet(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get("page") || "1");
  const limit = parseInt(searchParams.get("limit") || "20");
  const search = searchParams.get("search") || "";
  const status = searchParams.get("status") || "";
  const tier = searchParams.get("tier") || "";
 
  const skip = (page - 1) * limit;
 
  // Build where clause
  const where: Record<string, unknown> = {};
 
  if (search) {
    where.OR = [
      { code: { contains: search } },
      { website: { contains: search } },
    ];
  }
 
  if (status) {
    where.status = status;
  }
 
  if (tier) {
    where.tier = tier;
  }
 
  const [affiliates, total] = await Promise.all([
    prisma.affiliate.findMany({
      where,
      skip,
      take: limit,
      orderBy: { createdAt: "desc" },
      include: {
        _count: {
          select: {
            clicks: true,
            sales: true,
            payouts: true}}}}),
    prisma.affiliate.count({ where }),
  ]);
 
  // Get user info for each affiliate
  const userIds = affiliates.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]));
 
  const data = affiliates.map((affiliate) => ({
    id: affiliate.id,
    userId: affiliate.userId,
    user: userMap.get(affiliate.userId),
    code: affiliate.code,
    commissionType: affiliate.commissionType,
    commissionRate: affiliate.commissionRate,
    tier: affiliate.tier,
    totalClicks: affiliate.totalClicks,
    totalConversions: affiliate.totalConversions,
    totalSales: affiliate.totalSales,
    totalEarnings: affiliate.totalEarnings,
    pendingEarnings: affiliate.pendingEarnings,
    paidEarnings: affiliate.paidEarnings,
    conversionRate: affiliate.conversionRate,
    status: affiliate.status,
    approvedAt: affiliate.approvedAt,
    payoutMethod: affiliate.payoutMethod,
    minimumPayout: affiliate.minimumPayout,
    website: affiliate.website,
    bio: affiliate.bio,
    clickCount: affiliate._count.clicks,
    saleCount: affiliate._count.sales,
    payoutCount: affiliate._count.payouts,
    createdAt: affiliate.createdAt,
    updatedAt: affiliate.updatedAt}));
 
  return paginatedResponse(data, {
    page,
    limit,
    total});
}
 
// Schema for creating an affiliate
const createAffiliateSchema = z.object({
  userId: z.number().int().positive(),
  commissionType: z
    .enum(["PERCENTAGE", "FIXED_AMOUNT", "TIERED"])
    .default("PERCENTAGE"),
  commissionRate: z.number().min(0).max(100).default(10),
  status: z
    .enum(["PENDING", "ACTIVE", "SUSPENDED", "REJECTED", "INACTIVE"])
    .default("ACTIVE"),
  website: z.string().max(255).optional(),
  bio: z.string().optional()});
 
/**
 * POST /api/admin/affiliates
 * Create a new affiliate (admin can directly create and approve)
 */
async function handlePost(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const result = createAffiliateSchema.safeParse(body);
 
  if (!result.success) {
    throw ApiError.validation("Invalid affiliate data", result.error.issues);
  }
 
  const validatedData = result.data;
 
  // Check if user already has an affiliate account
  const existing = await prisma.affiliate.findUnique({
    where: { userId: validatedData.userId }});
 
  if (existing) {
    throw ApiError.badRequest("User already has an affiliate account");
  }
 
  // Generate unique code
  const { nanoid } = await import("nanoid");
  let code = nanoid(8).toUpperCase();
  let attempts = 0;
  while (attempts < 5) {
    const codeExists = await prisma.affiliate.findUnique({ where: { code } });
    if (!codeExists) break;
    code = nanoid(8).toUpperCase();
    attempts++;
  }
 
  // Create affiliate
  const affiliate = await prisma.affiliate.create({
    data: {
      userId: validatedData.userId,
      code,
      commissionType: validatedData.commissionType,
      commissionRate: validatedData.commissionRate,
      status: validatedData.status,
      website: validatedData.website,
      bio: validatedData.bio,
      approvedAt: validatedData.status === "ACTIVE" ? new Date() : null,
      approvedBy: validatedData.status === "ACTIVE" ? session.user.id : null}});
 
  return createdResponse(affiliate);
}
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));