All files / src/hooks/queries useApplicationStatsQuery.ts

100% Statements 9/9
83.33% Branches 5/6
100% Functions 3/3
100% Lines 8/8

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                                        1x 8x     4x   4x 3x     3x     1x   1x          
// src/hooks/queries/useApplicationStatsQuery.ts
import { useQuery } from '@tanstack/react-query';
import { getApplicationStats, AppStats } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
 
/**
 * Query hook for fetching application-wide statistics (admin feature).
 *
 * Returns app-wide counts for:
 * - Flyers
 * - Users
 * - Flyer items
 * - Stores
 * - Pending corrections
 * - Recipes
 *
 * Uses TanStack Query for automatic caching and refetching (ADR-0005 Phase 5).
 *
 * @returns TanStack Query result with AppStats data
 */
export const useApplicationStatsQuery = () => {
  return useQuery({
    queryKey: queryKeys.applicationStats(),
    queryFn: async (): Promise<AppStats> => {
      const response = await getApplicationStats();
 
      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch application stats');
      }
 
      const json = await response.json();
      // API returns { success: true, data: {...} }, extract the data object
      return json.data ?? json;
    },
    staleTime: 1000 * 60 * 2, // 2 minutes - stats change moderately, not as frequently as activity log
  });
};