All files / src/lib/loyalty rewards.ts

99.21% Statements 252/254
89.47% Branches 34/38
100% Functions 6/6
99.21% Lines 252/254

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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 2551x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 2x 2x 2x 2x 12x 12x 12x 12x 10x 14x 2x 2x 2x 2x 8x 8x 14x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 14x 1x 1x 1x 1x 6x 6x 14x 2x 2x 2x 14x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 2x 2x 2x 6x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 3x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x  
/**
 * Loyalty Rewards Utility Functions
 * Handles points redemption and reward management
 */
 
import { PrismaClient } from "@prisma/client";
import { logger } from "@/lib/logging";
 
const LOG_CATEGORY = "LOYALTY_REWARDS";
 
export interface RedeemPointsParams {
  userId: number;
  points: number;
  description?: string;
}
 
export interface RedeemPointsResult {
  pointsRedeemed: number;
  discountValue: number;
  remainingPoints: number;
  transactionId: number;
}
 
export interface RedemptionValidation {
  valid: boolean;
  error?: string;
  available?: number;
  requested?: number;
}
 
/**
 * Validate if a redemption is possible
 */
export async function validateRedemption(
  prisma: PrismaClient,
  userId: number,
  points: number
): Promise<RedemptionValidation> {
  try {
    // Check if points is positive
    if (points <= 0) {
      return {
        valid: false,
        error: "Points must be greater than zero"};
    }
 
    // Get loyalty record
    const loyalty = await prisma.customerLoyalty.findUnique({
      where: { userId }});
 
    if (!loyalty) {
      return {
        valid: false,
        error: "No loyalty account found"};
    }
 
    // Check if user has enough points
    if (loyalty.totalPoints < points) {
      return {
        valid: false,
        error: "Insufficient points",
        available: loyalty.totalPoints,
        requested: points};
    }
 
    // Check if loyalty program exists
    const program = await prisma.loyaltyProgram.findFirst({
      where: { isActive: true }});
 
    if (!program) {
      return {
        valid: false,
        error: "No active loyalty program"};
    }
 
    return { valid: true };
  } catch (error) {
    logger.error("Error validating redemption", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
    throw error;
  }
}
 
/**
 * Redeem points for discount
 */
export async function redeemPoints(
  prisma: PrismaClient,
  params: RedeemPointsParams
): Promise<RedeemPointsResult> {
  try {
    const { userId, points, description } = params;
 
    // Validate redemption
    const validation = await validateRedemption(prisma, userId, points);
    if (!validation.valid) {
      throw new Error(validation.error);
    }
 
    // Get loyalty record and program
    const [loyalty, program] = await Promise.all([
      prisma.customerLoyalty.findUnique({
        where: { userId }}),
      prisma.loyaltyProgram.findFirst({
        where: { isActive: true }}),
    ]);
 
    if (!loyalty || !program) {
      throw new Error("Loyalty account or program not found");
    }
 
    // Calculate discount value
    const discountValue = Math.round(points * program.redemptionRate * 100) / 100;
 
    // Create redemption transaction and update balance
    const result = await prisma.$transaction(async (tx) => {
      const transaction = await tx.loyaltyTransaction.create({
        data: {
          customerLoyaltyId: loyalty.id,
          type: "redeem",
          points: -points,
          description:
            description ||
            `Redeemed ${points} points for $${discountValue.toFixed(2)} discount`}});
 
      const updatedLoyalty = await tx.customerLoyalty.update({
        where: { id: loyalty.id },
        data: {
          totalPoints: { decrement: points }}});
 
      return {
        transactionId: transaction.id,
        remainingPoints: updatedLoyalty.totalPoints};
    });
 
    logger.info("Points redeemed", {
      category: LOG_CATEGORY,
      userId,
      points,
      discountValue,
      remainingPoints: result.remainingPoints});
 
    return {
      pointsRedeemed: points,
      discountValue,
      remainingPoints: result.remainingPoints,
      transactionId: result.transactionId};
  } catch (error) {
    logger.error("Error redeeming points", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
    throw error;
  }
}
 
/**
 * Calculate minimum points needed for a specific discount amount
 */
export async function calculateMinimumPointsForDiscount(
  prisma: PrismaClient,
  discountAmount: number
): Promise<number> {
  const program = await prisma.loyaltyProgram.findFirst({
    where: { isActive: true }});
 
  if (!program) {
    throw new Error("No active loyalty program");
  }
 
  return Math.ceil(discountAmount / program.redemptionRate);
}
 
/**
 * Calculate maximum discount available with current points
 */
export async function calculateMaximumDiscount(
  prisma: PrismaClient,
  userId: number
): Promise<number> {
  const [loyalty, program] = await Promise.all([
    prisma.customerLoyalty.findUnique({
      where: { userId }}),
    prisma.loyaltyProgram.findFirst({
      where: { isActive: true }}),
  ]);
 
  if (!loyalty || !program) {
    return 0;
  }
 
  return Math.round(loyalty.totalPoints * program.redemptionRate * 100) / 100;
}
 
/**
 * Award bonus points for special actions
 */
export async function awardBonusPoints(
  prisma: PrismaClient,
  userId: number,
  points: number,
  reason: string
): Promise<number> {
  try {
    let loyalty = await prisma.customerLoyalty.findUnique({
      where: { userId }});
 
    if (!loyalty) {
      loyalty = await prisma.customerLoyalty.create({
        data: {
          userId,
          totalPoints: 0,
          lifetimePoints: 0}});
    }
 
    const result = await prisma.$transaction(async (tx) => {
      await tx.loyaltyTransaction.create({
        data: {
          customerLoyaltyId: loyalty!.id,
          type: "bonus",
          points,
          description: reason}});
 
      const updated = await tx.customerLoyalty.update({
        where: { id: loyalty!.id },
        data: {
          totalPoints: { increment: points },
          lifetimePoints: { increment: points }}});
 
      return updated.totalPoints;
    });
 
    logger.info("Bonus points awarded", {
      category: LOG_CATEGORY,
      userId,
      points,
      reason});
 
    return result;
  } catch (error) {
    logger.error("Error awarding bonus points", error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
    throw error;
  }
}
 
/**
 * Check if user qualifies for a specific reward tier
 */
export async function checkRewardEligibility(
  prisma: PrismaClient,
  userId: number,
  requiredPoints: number
): Promise<boolean> {
  const loyalty = await prisma.customerLoyalty.findUnique({
    where: { userId }});
 
  return loyalty ? loyalty.totalPoints >= requiredPoints : false;
}