All files / src/app/api/referrals/code route.ts

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

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                                                                                                                                                                                 
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { Session } from "next-auth";
import { prisma } from "@/lib/prisma";
import { generateSingleCode } from "@/lib/promotions/utils";
import {
  withAuth,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

/**
 * GET /api/referrals/code
 * Get user's referral code (creates one if doesn't exist)
 */
async function handleGet(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const userId = session.user.id;

  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { id: true, name: true }});

  if (!user) {
    throw ApiError.notFound("User");
  }

  // Get active referral program
  const program = await prisma.referralProgram.findFirst({
    where: { isActive: true }});

  if (!program) {
    throw ApiError.notFound("No active referral program");
  }

  // Check if user already has a referral code
  let referral = await prisma.referral.findFirst({
    where: {
      referrerId: user.id,
      programId: program.id,
      refereeId: null, // Get the template referral code (not used yet)
    }});

  // Create referral code if it doesn't exist
  if (!referral) {
    // Generate unique code with user name prefix if available
    const prefix = user.name?.split(" ")[0]?.toUpperCase().substring(0, 4) || "REF";
    let code = generateSingleCode(prefix, 6);

    // Ensure uniqueness
    let attempts = 0;
    while (attempts < 10) {
      const existing = await prisma.referral.findUnique({
        where: { referralCode: code }});
      if (!existing) break;
      code = generateSingleCode(prefix, 6);
      attempts++;
    }

    referral = await prisma.referral.create({
      data: {
        programId: program.id,
        referrerId: user.id,
        referralCode: code,
        status: "pending"}});
  }

  // Get share URL
  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
  const shareUrl = `${baseUrl}/signup?ref=${referral.referralCode}`;

  return successResponse({
    code: referral.referralCode,
    shareUrl,
    program: {
      name: program.name,
      referrerReward: program.referrerReward,
      refereeReward: program.refereeReward}});
}

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