All files / components InviteProcessor.tsx

31.48% Statements 17/54
42.85% Branches 3/7
100% Functions 2/2
31.48% Lines 17/54

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 981x                                     1x 1x 1x 1x   1x   1x   1x   1x   1x                                                 1x                                                     1x         1x   1x 1x     1x 1x  
'use client';
 
import { useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useToast } from '@/hooks/use-toast';
import { createClient } from '@/lib/supabase/client';
 
interface PendingAction {
  type: 'write_testimonial';
  requestId: string;
  inviterName: string;
}
 
/**
 * Client component that processes invite tokens after login.
 * This handles the case where existing users accept invites -
 * since they don't go through onboarding, the invite needs to be
 * processed separately on dashboard load.
 */
export function InviteProcessor() {
  const { toast } = useToast();
  const router = useRouter();
  const processedRef = useRef(false);
 
  useEffect(() => {
    // Prevent double processing in strict mode
    if (processedRef.current) return;
 
    const processInvite = async () => {
      // Check for invite token in sessionStorage
      const inviteToken = sessionStorage.getItem('invite_token');
 
      if (!inviteToken) return;
 
      processedRef.current = true;
 
      try {
        const supabase = createClient();
        const {
          data: { user },
        } = await supabase.auth.getUser();
 
        if (!user) return;
 
        console.log('[InviteProcessor] Processing invite token for user:', user.id);
 
        const response = await fetch('/api/invites/accept', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ token: inviteToken, userId: user.id }),
        });
 
        const result = await response.json();
 
        // Always clear the token after attempting to process
        sessionStorage.removeItem('invite_token');
 
        if (response.ok && result.success) {
          console.log('[InviteProcessor] Invite accepted successfully:', result);
 
          // Check if there's a pending action (e.g., write testimonial)
          const pendingAction = result.pendingAction as PendingAction | null;
          if (pendingAction?.type === 'write_testimonial') {
            toast({
              title: 'One More Step!',
              description: `Please write a testimonial for ${pendingAction.inviterName}`,
            });
            // Redirect to the testimonial write page
            router.push(`/testimonial/write/${pendingAction.requestId}`);
            return;
          }
 
          // Normal success flow
          toast({
            title: 'Invite Accepted!',
            description: result.inviter
              ? `You're now connected with ${result.inviter.name}`
              : 'Your invitation has been accepted.',
          });
        } else {
          // Don't show error toast for already accepted or expired invites
          // as this is expected behavior
          console.log('[InviteProcessor] Invite processing result:', result);
        }
      } catch (error) {
        console.error('[InviteProcessor] Failed to process invite:', error);
        // Clear token even on error
        sessionStorage.removeItem('invite_token');
      }
    };
 
    processInvite();
  }, [toast, router]);
 
  // This component doesn't render anything
  return null;
}