All files / src/app/api/user/affiliate route.ts

97.75% Statements 174/178
80% Branches 12/15
100% Functions 3/3
97.75% Lines 174/178

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 1791x 1x 1x 1x 1x 1x 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 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 2x 2x 2x 3x 1x 1x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 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 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x     1x 1x 1x 1x 1x 1x 1x 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 { logger } from "@/lib/logging";
import { z } from "zod";
import { affiliateSystem } from "@/lib/affiliate-system";
import {
  withUser,
  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/user/affiliate
 * Get current user's affiliate account and dashboard
 */
async function handleGet(
  _request: NextRequest,
  _context: RouteContext | undefined,
  _session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  // Check if user has an affiliate account
  const affiliate = await prisma.affiliate.findUnique({
    where: { userId: user.id },
    include: {
      _count: {
        select: {
          clicks: true,
          sales: true,
          payouts: true}}}});
 
  if (!affiliate) {
    return successResponse({
      affiliate: null,
      message: "No affiliate account found"});
  }
 
  // Get detailed dashboard if affiliate is active
  let dashboard = null;
  if (affiliate.status === "ACTIVE") {
    dashboard = await affiliateSystem.getAffiliateDashboard(affiliate.id);
  }
 
  return successResponse({
    affiliate: {
      id: affiliate.id,
      code: affiliate.code,
      referralUrl: `${process.env.NEXT_PUBLIC_BASE_URL || ""}/ref/${affiliate.code}`,
      commissionType: affiliate.commissionType,
      commissionRate: affiliate.commissionRate,
      tier: affiliate.tier,
      status: affiliate.status,
      totalClicks: affiliate.totalClicks,
      totalConversions: affiliate.totalConversions,
      totalSales: affiliate.totalSales,
      totalEarnings: affiliate.totalEarnings,
      pendingEarnings: affiliate.pendingEarnings,
      paidEarnings: affiliate.paidEarnings,
      conversionRate: affiliate.conversionRate,
      payoutMethod: affiliate.payoutMethod,
      minimumPayout: affiliate.minimumPayout,
      website: affiliate.website,
      bio: affiliate.bio,
      approvedAt: affiliate.approvedAt,
      clickCount: affiliate._count.clicks,
      saleCount: affiliate._count.sales,
      payoutCount: affiliate._count.payouts,
      createdAt: affiliate.createdAt},
    dashboard});
}
 
// Schema for registering as an affiliate
const registerAffiliateSchema = z.object({
  website: z.string().url().max(255).optional(),
  bio: z.string().max(1000).optional(),
  payoutMethod: z.string().max(50).optional()});
 
/**
 * POST /api/user/affiliate
 * Register as an affiliate
 */
async function handlePost(
  request: NextRequest,
  _context: RouteContext | undefined,
  _session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const validationResult = registerAffiliateSchema.safeParse(body);
 
  if (!validationResult.success) {
    throw ApiError.validation("Validation failed", validationResult.error.issues);
  }
 
  const validatedData = validationResult.data;
 
  const result = await affiliateSystem.registerAffiliate(user.id, {
    website: validatedData.website,
    bio: validatedData.bio});
 
  if (!result.success) {
    throw ApiError.badRequest(result.error || "Failed to register as affiliate");
  }
 
  logger.info("User registered as affiliate", { category: "API", userId: user.id });
 
  return createdResponse({
    affiliate: result.affiliate,
    message: "Affiliate registration submitted successfully"});
}
 
// Schema for updating affiliate profile
const updateAffiliateSchema = z.object({
  website: z.string().url().max(255).optional().nullable(),
  bio: z.string().max(1000).optional().nullable(),
  payoutMethod: z.string().max(50).optional().nullable()});
 
/**
 * PUT /api/user/affiliate
 * Update affiliate profile
 */
async function handlePut(
  request: NextRequest,
  _context: RouteContext | undefined,
  _session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const validationResult = updateAffiliateSchema.safeParse(body);
 
  if (!validationResult.success) {
    throw ApiError.validation("Validation failed", validationResult.error.issues);
  }
 
  const validatedData = validationResult.data;
 
  // Check if user has an affiliate account
  const affiliate = await prisma.affiliate.findUnique({
    where: { userId: user.id }});
 
  if (!affiliate) {
    throw ApiError.notFound("Affiliate account");
  }
 
  // Build update data
  const updateData: Record<string, unknown> = {};
 
  if (validatedData.website !== undefined) {
    updateData.website = validatedData.website;
  }
  if (validatedData.bio !== undefined) {
    updateData.bio = validatedData.bio;
  }
  if (validatedData.payoutMethod !== undefined) {
    updateData.payoutMethod = validatedData.payoutMethod;
  }
 
  const updatedAffiliate = await prisma.affiliate.update({
    where: { id: affiliate.id },
    data: updateData});
 
  logger.info("Affiliate profile updated", { category: "API", affiliateId: affiliate.id });
 
  return successResponse(updatedAffiliate);
}
 
export const GET = withErrorHandling(withUser(handleGet));
export const POST = withErrorHandling(withUser(handlePost));
export const PUT = withErrorHandling(withUser(handlePut));