All files / src/app/api/admin/referrals/codes route.ts

0% Statements 0/173
100% Branches 0/0
0% Functions 0/1
0% Lines 0/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 174                                                                                                                                                                                                                                                                                                                                                           
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 { randomBytes } from "crypto";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

const GenerateCodesSchema = z.object({
  programId: z.number(),
  userId: z.number().optional(),
  count: z.number().int().min(1).max(100).default(1),
  prefix: z.string().optional()});

function generateReferralCode(prefix?: string): string {
  const code = randomBytes(4).toString("hex").toUpperCase();
  return prefix ? `${prefix}-${code}` : code;
}

/**
 * GET /api/admin/referrals/codes
 * List all referral codes with filters
 */
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 status = searchParams.get("status");
  const userId = searchParams.get("userId");
  const campaignId = searchParams.get("campaignId");

  const skip = (page - 1) * limit;

  // Build where clause
  const where: {
    status?: string;
    referrerId?: number;
    programId?: number;
  } = {};

  if (status) {
    where.status = status;
  }

  if (userId) {
    where.referrerId = parseInt(userId);
  }

  if (campaignId) {
    where.programId = parseInt(campaignId);
  }

  const [codes, total] = await Promise.all([
    prisma.referral.findMany({
      where,
      skip,
      take: limit,
      include: {
        program: {
          select: { id: true, name: true }}},
      orderBy: { createdAt: "desc" }}),
    prisma.referral.count({ where }),
  ]);

  // Get referrer info
  const referrerIds = [...new Set(codes.map((c) => c.referrerId))];
  const referrers = await prisma.user.findMany({
    where: { id: { in: referrerIds } },
    select: { id: true, email: true, name: true }});
  const referrerMap = new Map(referrers.map((r) => [r.id, r]));

  const formattedCodes = codes.map((code) => {
    const referrer = referrerMap.get(code.referrerId);
    return {
      id: code.id,
      code: code.referralCode,
      referrerId: code.referrerId,
      referrer: referrer
        ? {
            id: referrer.id,
            email: referrer.email,
            name: referrer.name || "N/A"}
        : null,
      programId: code.programId,
      program: code.program,
      status: code.status,
      refereeId: code.refereeId,
      referrerRewarded: code.referrerRewarded,
      refereeRewarded: code.refereeRewarded,
      createdAt: code.createdAt};
  });

  return successResponse({
    codes: formattedCodes,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit)}});
}

/**
 * POST /api/admin/referrals/codes
 * Generate referral codes (single or bulk)
 */
async function handlePost(request: NextRequest,
  _context: RouteContext | undefined,
  session: Session): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const result = GenerateCodesSchema.safeParse(body);

  if (!result.success) {
    throw ApiError.validation("Invalid data", result.error.issues);
  }

  const validatedData = result.data;

  // Verify program exists
  const program = await prisma.referralProgram.findUnique({
    where: { id: validatedData.programId }});

  if (!program) {
    throw ApiError.notFound("Program");
  }

  // Verify user exists if provided
  if (validatedData.userId) {
    const user = await prisma.user.findUnique({
      where: { id: validatedData.userId }});
    if (!user) {
      throw ApiError.notFound("User");
    }
  }

  // Generate codes
  const codes = [];
  for (let i = 0; i < validatedData.count; i++) {
    let code = generateReferralCode(validatedData.prefix);

    // Ensure unique code
    let exists = await prisma.referral.findUnique({
      where: { referralCode: code }});
    while (exists) {
      code = generateReferralCode(validatedData.prefix);
      exists = await prisma.referral.findUnique({
        where: { referralCode: code }});
    }

    const referral = await prisma.referral.create({
      data: {
        programId: validatedData.programId,
        referrerId: validatedData.userId || session.user.id,
        referralCode: code,
        status: "pending"}});
    codes.push(referral);
  }

  return createdResponse({
    codes,
    message: `Generated ${codes.length} referral code(s)`});
}

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