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

100% Statements 141/141
82.75% Branches 24/29
100% Functions 1/1
100% Lines 141/141

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 1421x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 7x 8x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 10x 10x 9x 6x 6x 6x 6x 6x 6x 6x 6x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 8x 8x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 8x 8x 18x 18x 18x 18x 18x 18x 8x 8x 6x 6x 6x 8x 8x 1x 1x 1x 1x 8x 8x 8x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import { Session } from "next-auth";
import { prisma } from "@/lib/prisma";
import {
  withAuth,
  withErrorHandling,
  successResponse,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
 
/**
 * GET /api/user/loyalty
 * Get current user's loyalty information
 */
async function handleGet(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const userId = session.user.id;
 
  // Get active loyalty program
  const program = await prisma.loyaltyProgram.findFirst({
    where: { isActive: true },
    include: {
      tiers: {
        orderBy: { minPoints: "asc" }},
      bonusRules: {
        where: { isActive: true }}}});
 
  if (!program) {
    return successResponse({
      enrolled: false,
      message: "No active loyalty program"});
  }
 
  // Get or create customer loyalty record
  let customerLoyalty = await prisma.customerLoyalty.findUnique({
    where: { userId },
    include: {
      transactions: {
        orderBy: { createdAt: "desc" },
        take: 10}}});
 
  // Auto-enroll if not exists
  if (!customerLoyalty) {
    customerLoyalty = await prisma.customerLoyalty.create({
      data: {
        userId,
        totalPoints: 0,
        lifetimePoints: 0},
      include: {
        transactions: {
          orderBy: { createdAt: "desc" },
          take: 10}}});
  }
 
  // Calculate current tier
  const currentTier = program.tiers.find((tier, index) => {
    const nextTier = program.tiers[index + 1];
    if (!nextTier) return true; // Last tier
    return customerLoyalty!.lifetimePoints < nextTier.minPoints;
  });
 
  // Calculate next tier
  const currentTierIndex = program.tiers.findIndex(
    (t) => t.id === currentTier?.id
  );
  const nextTier = program.tiers[currentTierIndex + 1];
  const pointsToNextTier = nextTier
    ? nextTier.minPoints - customerLoyalty.lifetimePoints
    : null;
 
  // Calculate points value
  const pointsValue = customerLoyalty.totalPoints * program.redemptionRate;
 
  // Get user's referral code if exists
  const referral = await prisma.referral.findFirst({
    where: { referrerId: userId },
    select: { referralCode: true }});
 
  return successResponse({
    enrolled: true,
    program: {
      id: program.id,
      name: program.name,
      pointsPerDollar: program.pointsPerDollar,
      redemptionRate: program.redemptionRate},
    points: {
      current: customerLoyalty.totalPoints,
      lifetime: customerLoyalty.lifetimePoints,
      value: pointsValue},
    tier: currentTier
      ? {
          id: currentTier.id,
          name: currentTier.name,
          minPoints: currentTier.minPoints,
          pointsMultiplier: currentTier.pointsMultiplier,
          perks: currentTier.perks}
      : null,
    nextTier: nextTier
      ? {
          id: nextTier.id,
          name: nextTier.name,
          minPoints: nextTier.minPoints,
          pointsToReach: pointsToNextTier,
          progressPercent: Math.min(
            100,
            Math.round(
              ((customerLoyalty.lifetimePoints - (currentTier?.minPoints || 0)) /
                (nextTier.minPoints - (currentTier?.minPoints || 0))) *
                100
            )
          )}
      : null,
    allTiers: program.tiers.map((tier) => ({
      id: tier.id,
      name: tier.name,
      minPoints: tier.minPoints,
      pointsMultiplier: tier.pointsMultiplier,
      perks: tier.perks,
      isCurrentTier: tier.id === currentTier?.id,
      isAchieved: customerLoyalty!.lifetimePoints >= tier.minPoints})),
    bonusRules: program.bonusRules.map((rule) => ({
      id: rule.id,
      name: rule.name,
      triggerType: rule.triggerType,
      bonusPoints: rule.bonusPoints})),
    transactions: customerLoyalty.transactions.map((tx) => ({
      id: tx.id,
      type: tx.type,
      points: tx.points,
      description: tx.description,
      createdAt: tx.createdAt})),
    referralCode: referral?.referralCode || null});
}
 
export const GET = withErrorHandling(withAuth(handleGet));