All files / src/hooks useTickets.ts

100% Statements 38/38
100% Branches 16/16
100% Functions 5/5
100% Lines 34/34

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                                        21x 21x 21x 21x 21x 21x   21x 8x 8x 8x 8x 8x   8x 1x 1x 1x 1x 1x     7x 7x 3x   2x   2x 1x   1x     4x 3x 1x   2x     7x     8x 8x 2x       21x    
import { useState, useEffect } from 'react'
import type { Ticket } from '../types/tickets'
import type { TicketsApiResponse, TicketFilters } from '../types/tickets'
import { getUserTickets } from '../services/billingService'
import { useAuthStore } from '../stores/useAuthStore'
 
interface UseTicketsResult {
  tickets: Ticket[];
  total: number;
  loading: boolean;
  error: Error | null;
  validationErrors: any; // selon backend, si code 422 renvoie erreurs
}
 
/**
 * Hook pour charger les tickets de l’utilisateur selon des filtres.
 * @param filters TicketFilters
 * @param lang (optionnel) si tu veux envoyer Accept-Language ou rerender sur changement de langue
 */
export function useTickets(filters: TicketFilters): UseTicketsResult {
  const token = useAuthStore(s => s.authToken)
  const [tickets, setTickets] = useState<Ticket[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<Error | null>(null)
  const [validationErrors, setValidationErrors] = useState<any>(null)
 
  useEffect(() => {
    let cancelled = false
    const fetchTickets = async () => {
      setLoading(true)
      setError(null)
      setValidationErrors(null)
 
      if (!token) {
        setError(new Error('User not authenticated'))
        setTickets([])
        setTotal(0)
        setLoading(false)
        return
      }
 
      try {
        const resp: TicketsApiResponse = await getUserTickets(filters, token)
        if (cancelled) return
        // On suppose resp.data.meta.total existe
        setTickets(resp.data.data)
        // Selon meta.total
        if (resp.data.meta && typeof resp.data.meta.total === 'number') {
          setTotal(resp.data.meta.total)
        } else {
          setTotal(resp.data.data.length)
        }
      } catch (err: any) {
        if (cancelled) return
        if (err.response?.status === 422) {
          setValidationErrors(err.response.data.errors)
        } else {
          setError(err instanceof Error ? err : new Error('Unknown error'))
        }
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    fetchTickets()
    return () => {
      cancelled = true
    }
  }, [JSON.stringify(filters), token])
 
  return { tickets, total, loading, error, validationErrors }
}