All files / src/viewmodels/ticket useTicketViewModel.ts

84.39% Statements 119/141
61.36% Branches 27/44
92.85% Functions 13/14
87.31% Lines 117/134

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 255 256 257 258 259 2601x 1x 1x 1x 1x 1x     1x 1x       1x 1x                             1x 20x 20x 20x 20x 20x 20x 20x 20x 20x   20x 20x 20x 20x   20x 6x 6x 6x   6x 6x 6x   6x 1x     6x 6x               6x       20x   20x 14x 14x 5x 5x   14x 5x 5x   14x 5x 5x       20x 7x   5x 6x 6x 6x   6x 1x 1x 1x 1x             5x   6x           20x 7x   5x 5x 5x   5x 6x   6x 6x 6x 6x                       6x                   6x 6x 6x   6x               6x 6x 6x 6x     6x 6x 17x 17x 17x   17x 2x 2x         6x 1x   6x 6x                     6x 6x                             5x     20x 5x 5x 5x 5x 5x 4x 4x         20x 14x 7x 7x   7x       20x 1x 1x 1x 1x 1x 1x     20x                          
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import * as ExpoLocation from 'expo-location';
import { useAuth } from '@/contexts/AuthContext';
import { ApiError } from '@/services/api';
import { getEventDetail } from '@/services/eventService';
import { getMyTicket, getTicketQrTokenOnce } from '@/services/ticketService';
import type { EventDetail } from '@/models/event';
import type { TicketDetailResponse, TicketQrToken } from '@/models/ticket';
import { getTicketQrAccessMessage } from '@/utils/ticketStatus';
import i18n from '@/i18n';
 
// GLOBAL REGISTRY: Keep track of active stream controllers across the whole app
// to prevent "ghost" connections when navigating back and forth.
const activeStreams = new Map<string, AbortController>();
const TICKET_STATUS_POLL_INTERVAL_MS = 2000;
 
export interface TicketViewModel {
  ticket: TicketDetailResponse | null;
  eventImageUrl: string | null;
  isLoading: boolean;
  apiError: string | null;
  qrToken: TicketQrToken | null;
  qrMessage: string | null;
  isActionLoading: boolean;
  secondsRemaining: number | null;
  refresh: () => Promise<void>;
  resetError: () => void;
}
 
export function useTicketViewModel(ticketId: string): TicketViewModel {
  const { user, token } = useAuth();
  const [ticket, setTicket] = useState<TicketDetailResponse | null>(null);
  const [event, setEvent] = useState<EventDetail | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [apiError, setApiError] = useState<string | null>(null);
  const [qrToken, setQrToken] = useState<TicketQrToken | null>(null);
  const [qrMessage, setQrMessage] = useState<string | null>(null);
  const [isActionLoading, setIsActionLoading] = useState(false);
  const [secondsRemaining, setSecondsRemaining] = useState<number | null>(null);
 
  const pollingRef = useRef<boolean>(false);
  const pollingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const ticketStatusIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const countdownIntervalRef = useRef<NodeJS.Timeout | null>(null);
 
  const fetchTicketAndEvent = useCallback(async () => {
    Iif (!token) return;
    setIsLoading(true);
    setApiError(null);
 
    try {
      const ticketData = await getMyTicket(ticketId, token);
      setTicket(ticketData);
 
      if (!ticketData.qr_access.eligible_now) {
        setQrMessage(getTicketQrAccessMessage(ticketData.qr_access.reason));
      }
 
      const eventData = await getEventDetail(ticketData.event.id, token);
      setEvent(eventData);
    } catch (err) {
      if (err instanceof ApiError) {
        setApiError(err.message);
      } else {
        setApiError(i18n.t('tickets.detail.errors.unexpected'));
      }
    } finally {
      setIsLoading(false);
    }
  }, [ticketId, token]);
 
  const resetError = useCallback(() => setApiError(null), []);
 
  const stopPolling = useCallback(() => {
    pollingRef.current = false;
    if (pollingTimeoutRef.current) {
      clearTimeout(pollingTimeoutRef.current);
      pollingTimeoutRef.current = null;
    }
    if (ticketStatusIntervalRef.current) {
      clearInterval(ticketStatusIntervalRef.current);
      ticketStatusIntervalRef.current = null;
    }
    if (countdownIntervalRef.current) {
      clearInterval(countdownIntervalRef.current);
      countdownIntervalRef.current = null;
    }
  }, []);
 
  const startTicketStatusPolling = useCallback(() => {
    if (!token || !ticketId || ticketStatusIntervalRef.current) return;
 
    const refreshTicketStatus = async () => {
      try {
        const ticketData = await getMyTicket(ticketId, token);
        setTicket(ticketData);
 
        if (ticketData.ticket.status !== 'ACTIVE') {
          setQrToken(null);
          setQrMessage(null);
          setSecondsRemaining(null);
          stopPolling();
        }
      } catch {
        // QR token polling already owns user-facing transient errors.
      }
    };
 
    ticketStatusIntervalRef.current = setInterval(
      () => {
        void refreshTicketStatus();
      },
      TICKET_STATUS_POLL_INTERVAL_MS,
    );
  }, [stopPolling, ticketId, token]);
 
  const startPolling = useCallback(async () => {
    if (!token || !ticketId || pollingRef.current) return;
 
    pollingRef.current = true;
    const abortController = new AbortController();
    activeStreams.set(ticketId, abortController);
 
    const poll = async () => {
      Iif (!pollingRef.current) return;
 
      try {
        let location = null;
        try {
          location = await ExpoLocation.getCurrentPositionAsync({
            accuracy: ExpoLocation.Accuracy.Balanced,
          });
        } catch {
          setQrMessage(i18n.t('tickets.qr.enableLocationServices'));
          pollingTimeoutRef.current = setTimeout(poll, 10000);
          return;
        }
 
        // We fetch both in parallel using allSettled. 
        // This ensures that if getTicketQrTokenOnce fails (e.g. ticket scanned),
        // we still receive and process the latest ticket status from getMyTicket.
        const [ticketResult, tokenResult] = await Promise.allSettled([
          getMyTicket(ticketId, token),
          getTicketQrTokenOnce(
            ticketId,
            { lat: location.coords.latitude, lon: location.coords.longitude },
            token
          )
        ]);
 
        // 1. Update ticket detail/status if successful
        if (ticketResult.status === 'fulfilled') {
          const ticketData = ticketResult.value;
          setTicket(ticketData);
          
          Iif (ticketData.ticket.status !== 'ACTIVE') {
            // Ticket is USED or CANCELED, stop polling immediately
            stopPolling();
            return;
          }
        }
 
        // 2. Update QR token if successful
        if (tokenResult.status === 'fulfilled') {
          const tokenData = tokenResult.value;
          setQrMessage(null);
          setQrToken(tokenData);
          
          // Setup countdown
          const expiresAt = new Date(tokenData.expires_at).getTime();
          const updateCountdown = () => {
            const now = Date.now();
            const diff = Math.max(0, Math.floor((expiresAt - now) / 1000));
            setSecondsRemaining(diff);
            
            if (diff <= 0) {
              if (countdownIntervalRef.current) {
                clearInterval(countdownIntervalRef.current);
              }
            }
          };
 
          if (countdownIntervalRef.current) {
            clearInterval(countdownIntervalRef.current);
          }
          updateCountdown();
          countdownIntervalRef.current = setInterval(updateCountdown, 1000);
        } else E{
          // Token fetch failed (might be because of scan)
          const err = tokenResult.reason;
          Iif (err instanceof Error && err.message === 'AbortError') return;
          
          const message = err instanceof ApiError ? err.message : i18n.t('tickets.qr.connectionLost');
          setQrMessage(getTicketQrAccessMessage(message));
        }
 
        // Schedule next poll if still active
        if (pollingRef.current) {
          pollingTimeoutRef.current = setTimeout(poll, 10000);
        }
      } catch (err) {
        Iif (err instanceof Error && err.message === 'AbortError') return;
        
        const message = err instanceof ApiError ? err.message : i18n.t('tickets.qr.connectionLost');
        setQrMessage(getTicketQrAccessMessage(message));
 
        // Retry later on error
        Iif (pollingRef.current) {
          pollingTimeoutRef.current = setTimeout(poll, 15000);
        }
      }
    };
 
    void poll();
  }, [ticketId, token]);
 
  useEffect(() => {
    void fetchTicketAndEvent();
    return () => {
      stopPolling();
      const controller = activeStreams.get(ticketId);
      if (controller) {
        controller.abort();
        activeStreams.delete(ticketId);
      }
    };
  }, [fetchTicketAndEvent, stopPolling, ticketId]);
 
  useEffect(() => {
    if (ticket && ticket.ticket.status === 'ACTIVE' && ticket.qr_access.eligible_now) {
      void startPolling();
      startTicketStatusPolling();
    } else {
      stopPolling();
    }
  }, [ticket, startPolling, startTicketStatusPolling, stopPolling]);
 
  const refresh = useCallback(async () => {
    stopPolling();
    setTicket(null);
    setQrToken(null);
    setQrMessage(null);
    setSecondsRemaining(null);
    await fetchTicketAndEvent();
  }, [fetchTicketAndEvent, stopPolling]);
 
  return {
    ticket,
    eventImageUrl: event?.image_url ?? null,
    isLoading,
    apiError,
    qrToken,
    qrMessage,
    isActionLoading,
    secondsRemaining,
    refresh,
    resetError,
  };
}