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

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

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

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from "@/lib/prisma";
import {
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";

/**
 * POST /api/referrals/validate
 * Validate a referral code (used during signup)
 * Note: This is a public endpoint - no authentication required
 */
async function handlePost(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const { code } = body;

  if (!code || typeof code !== "string") {
    throw ApiError.badRequest("Referral code is required");
  }

  const normalizedCode = code.toUpperCase().trim();

  // Find the referral
  const referral = await prisma.referral.findUnique({
    where: { referralCode: normalizedCode },
    include: {
      program: true,
      referrer: {
        select: { name: true }}}});

  if (!referral) {
    throw ApiError.notFound("Invalid referral code");
  }

  // Check if program is active
  if (!referral.program.isActive) {
    throw ApiError.badRequest("Referral program is no longer active");
  }

  // Get referee reward info
  const refereeReward = referral.program.refereeReward as {
    type: string;
    value: number;
    discountType?: string;
  };

  let rewardMessage = "";
  if (refereeReward.type === "discount") {
    if (refereeReward.discountType === "PERCENTAGE") {
      rewardMessage = `${refereeReward.value}% off your first order`;
    } else {
      rewardMessage = `$${refereeReward.value} off your first order`;
    }
  } else if (refereeReward.type === "points") {
    rewardMessage = `${refereeReward.value} bonus loyalty points`;
  } else if (refereeReward.type === "credit") {
    rewardMessage = `$${refereeReward.value} store credit`;
  }

  return successResponse({
    code: referral.referralCode,
    referrerName: referral.referrer.name?.split(" ")[0] || "A friend",
    reward: refereeReward,
    rewardMessage});
}

export const POST = withErrorHandling(handlePost);