All files / src/app/api/cron/cart-abandonment route.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * Cart Abandonment Email Cron Job
 *
 * Processes abandoned carts and sends reminder emails.
 * Should be called by a cron service (e.g., Vercel Cron, external scheduler).
 *
 * Security: Protected by CRON_SECRET environment variable.
 *
 * Schedule: Recommended every 15-30 minutes
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { emailService } from '@/lib/email/emailService';
import { logger } from '@/lib/logging';

// Prevent static generation
export const dynamic = 'force-dynamic';

// Cart is considered abandoned after this duration (in milliseconds)
const ABANDONMENT_THRESHOLD_MS = 60 * 60 * 1000; // 1 hour

// Don't send multiple emails within this window
const EMAIL_COOLDOWN_MS = 24 * 60 * 60 * 1000; // 24 hours

interface AbandonedCartResult {
  success: boolean;
  processed: number;
  errors: string[];
  skipped: number;
}

/**
 * GET /api/cron/cart-abandonment
 *
 * Process abandoned carts and queue reminder emails
 */
export async function GET(request: NextRequest): Promise<NextResponse> {
  // Verify cron secret
  const authHeader = request.headers.get('authorization');
  const cronSecret = process.env.CRON_SECRET;

  // In development, allow without secret for testing
  if (process.env.NODE_ENV === 'production' && cronSecret) {
    if (authHeader !== `Bearer ${cronSecret}`) {
      logger.warn('Unauthorized cart abandonment cron attempt', { category: 'CRON' });
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }
  }

  const result = await processAbandonedCarts();

  if (result.success) {
    logger.info('Cart abandonment cron completed', {
      category: 'CRON',
      processed: result.processed,
      skipped: result.skipped,
      errorCount: result.errors.length
    });
  } else {
    logger.error('Cart abandonment cron failed', new Error(result.errors.join('; ')), {
      category: 'CRON',
      errors: result.errors
    });
  }

  return NextResponse.json(result);
}

/**
 * Process abandoned carts and send reminder emails
 */
async function processAbandonedCarts(): Promise<AbandonedCartResult> {
  const errors: string[] = [];
  let processed = 0;
  let skipped = 0;

  try {
    const cutoffTime = new Date(Date.now() - ABANDONMENT_THRESHOLD_MS);
    const emailCutoffTime = new Date(Date.now() - EMAIL_COOLDOWN_MS);

    // Find users with abandoned carts
    // - Cart items updated more than ABANDONMENT_THRESHOLD ago
    // - User is logged in (has userId)
    // - User hasn't been emailed about abandoned cart recently
    const usersWithAbandonedCarts = await prisma.user.findMany({
      where: {
        cart: {
          some: {
            updatedAt: { lte: cutoffTime }
          }
        },
        // Only users who haven't received abandoned cart email recently
        emailLogs: {
          none: {
            template: 'abandoned-cart',
            createdAt: { gte: emailCutoffTime }
          }
        },
        // Respect email preferences
        emailPreferences: {
          OR: [
            { unsubscribeAll: false, promotions: true },
            { unsubscribeAll: { equals: false } }, // default opt-in
            { userId: { equals: undefined } } // no preferences = opted in
          ]
        }
      },
      select: {
        id: true,
        email: true,
        name: true,
        cart: {
          where: {
            updatedAt: { lte: cutoffTime }
          },
          include: {
            product: {
              select: {
                title: true,
                discountedPrice: true,
                images: {
                  select: { url: true },
                  take: 1
                }
              }
            }
          }
        },
        emailPreferences: {
          select: {
            unsubscribeAll: true,
            promotions: true
          }
        }
      }
    });

    for (const user of usersWithAbandonedCarts) {
      // Skip if no cart items
      if (user.cart.length === 0) {
        skipped++;
        continue;
      }

      // Check email preferences
      const prefs = user.emailPreferences;
      if (prefs?.unsubscribeAll || prefs?.promotions === false) {
        skipped++;
        continue;
      }

      try {
        // Calculate cart total
        const cartTotal = user.cart.reduce(
          (sum, item) => sum + Number(item.product.discountedPrice) * item.quantity,
          0
        );

        // Queue abandoned cart email
        await emailService.sendAbandonedCartReminder({
          id: user.id,
          email: user.email,
          name: user.name || 'there',
          cartItems: user.cart.map(item => ({
            name: item.product.title,
            quantity: item.quantity,
            price: Number(item.product.discountedPrice),
            image: item.product.images[0]?.url
          })),
          cartTotal
        });

        processed++;
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        errors.push(`Failed to process user ${user.id}: ${errorMessage}`);
      }
    }

    return {
      success: true,
      processed,
      skipped,
      errors
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    return {
      success: false,
      processed,
      skipped,
      errors: [`System error: ${errorMessage}`]
    };
  }
}

// Also support POST for flexibility with different cron services
export async function POST(request: NextRequest): Promise<NextResponse> {
  return GET(request);
}