All files / app/api/payments/create-order route.ts

100% Statements 128/128
96.29% Branches 26/27
100% Functions 1/1
100% Lines 128/128

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 1691x                             1x 1x 1x   19x 19x   19x 1x 1x     18x 18x 18x 18x 18x   19x 2x 2x     16x 16x   19x 2x 2x 2x 2x 2x   14x 14x     14x 14x 14x 14x 14x 14x   19x 1x 1x 1x 1x 1x     13x 13x 13x   13x 13x 13x 13x 13x 13x 13x   19x 1x 1x 1x 1x 19x   1x 1x     13x 13x 13x 13x 13x 13x   19x 6x 6x 2x 2x 2x 2x 2x 6x     11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 19x 19x 19x 19x 19x     10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 19x 19x 19x 19x 19x   10x 10x 10x 10x 10x 10x 10x 10x 10x 19x 19x 19x 1x 1x 1x 1x 1x 1x 9x 19x 19x 1x 1x 1x 19x  
/**
 * Create Razorpay Order API
 *
 * POST /api/payments/create-order
 *
 * Creates a Razorpay order for subscription payment
 */
 
import { NextRequest, NextResponse } from 'next/server';
import { razorpay, isRazorpayConfigured, PRICING } from '@/lib/razorpay/client';
import { createClient } from '@/lib/supabase/server';
import { getAdminClient } from '@/lib/supabase/admin';
import { getUserTrustScore } from '@/lib/trust/calculate';
import { z } from 'zod';
 
const createOrderSchema = z.object({
  tier: z.enum(['basic', 'pro', 'premium']),
});
 
export async function POST(request: NextRequest) {
  try {
    // Check if Razorpay is configured
    if (!isRazorpayConfigured()) {
      return NextResponse.json({ error: 'Payment service not configured' }, { status: 503 });
    }
 
    // Authenticate user
    const supabase = await createClient();
    const {
      data: { user },
      error: authError,
    } = await supabase.auth.getUser();
 
    if (authError || !user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
 
    // Parse request body
    const body = await request.json();
    const parsed = createOrderSchema.safeParse(body);
 
    if (!parsed.success) {
      return NextResponse.json(
        { error: 'Invalid request', details: parsed.error.flatten() },
        { status: 400 }
      );
    }
 
    const { tier } = parsed.data;
    const pricing = PRICING[tier];
 
    // Get user profile for receipt and trust score
    const adminClient = getAdminClient();
    const { data: profile } = await adminClient
      .from('profiles')
      .select('id, username, display_name, bio, avatar_url, whatsapp')
      .eq('user_id', user.id)
      .single();
 
    if (!profile) {
      return NextResponse.json(
        { error: 'Profile not found. Complete onboarding first.' },
        { status: 400 }
      );
    }
 
    // Calculate trust score for discount eligibility
    let discountApplied = false;
    let discountPercentage = 0;
    let finalAmount: number = pricing.amount;
 
    try {
      const trustResult = await getUserTrustScore(adminClient, user.id, profile.id, {
        display_name: profile.display_name,
        bio: profile.bio,
        avatar_url: profile.avatar_url,
        whatsapp: profile.whatsapp,
      });
 
      if (trustResult.score >= 80) {
        discountApplied = true;
        discountPercentage = 50;
        finalAmount = Math.round(pricing.amount / 2);
      }
    } catch (trustError) {
      // If trust score calculation fails, proceed without discount
      console.error('Trust score calculation error:', trustError);
    }
 
    // Check if user already has an active subscription for this tier or higher
    const { data: existingSubscription } = await adminClient
      .from('subscriptions')
      .select('*')
      .eq('user_id', user.id)
      .eq('status', 'active')
      .single();
 
    if (existingSubscription) {
      const tierOrder = { free: 0, basic: 1, pro: 2, premium: 3 };
      if (tierOrder[existingSubscription.tier as keyof typeof tierOrder] >= tierOrder[tier]) {
        return NextResponse.json(
          { error: 'You already have this plan or a higher tier active' },
          { status: 400 }
        );
      }
    }
 
    // Create Razorpay order
    const receiptId = `rcpt_${profile.id.slice(0, 8)}_${Date.now()}`;
 
    const order = await razorpay.orders.create({
      amount: finalAmount,
      currency: pricing.currency,
      receipt: receiptId,
      notes: {
        user_id: user.id,
        profile_id: profile.id,
        tier: tier,
        username: profile.username,
        discount_applied: discountApplied ? 'true' : 'false',
        discount_percentage: discountPercentage.toString(),
        original_amount: pricing.amount.toString(),
      },
    });
 
    // Store pending payment in database
    await adminClient.from('payments').insert({
      user_id: user.id,
      amount: finalAmount,
      currency: pricing.currency,
      razorpay_order_id: order.id,
      status: 'pending',
      description: pricing.description,
      meta: {
        tier,
        receipt_id: receiptId,
        discount_applied: discountApplied,
        discount_reason: discountApplied ? 'trust_score_80' : null,
        discount_percentage: discountPercentage,
        original_amount: pricing.amount,
      },
    });
 
    return NextResponse.json({
      orderId: order.id,
      amount: order.amount,
      currency: order.currency,
      keyId: process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID,
      name: 'ProofID',
      description: pricing.description,
      prefill: {
        email: user.email,
        name: profile.display_name || profile.username,
      },
      discount: discountApplied
        ? {
            applied: true,
            percentage: discountPercentage,
            originalAmount: pricing.amount,
            reason: 'trust_score_80',
          }
        : null,
    });
  } catch (error) {
    console.error('Create order error:', error);
    return NextResponse.json({ error: 'Failed to create order' }, { status: 500 });
  }
}