All files / src/features/dashboard/services summary.service.ts

95.23% Statements 20/21
100% Branches 4/4
85.71% Functions 6/7
95.23% Lines 20/21

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                                                2x     10x 10x 2x 7x                     2x 14x 14x     11x     11x   11x 1x 1x     10x   3x 3x         2x   11x           2x 11x          
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '../../../lib/http-client';
import type { SummaryCardProps } from '../components/summary-cards';
import type { CardType, TrendType } from '@/constants/dashboard';
import { DASHBOARD_API_ENDPOINTS } from '@/constants/dashboard';
 
// Summary API response type from Strapi
interface SummaryApiResponse {
  id: number;
  documentId: string;
  title: string;
  value: string;
  percentage: string;
  trend: TrendType;
  color: CardType;
  actions: boolean;
  order: number;
  createdAt: string;
  updatedAt: string;
  publishedAt: string;
  locale: string;
}
 
// Transform API response to SummaryCardsProps
const transformApiResponse = (
  apiData: SummaryApiResponse[]
): SummaryCardProps[] => {
  console.log('Transforming Summary API response:', apiData);
  return apiData
    .sort((a, b) => a.order - b.order) // Sort by order
    .map(item => ({
      title: item.title,
      value: item.value,
      percentage: item.percentage,
      trend: item.trend,
      color: item.color,
      actions: item.actions,
    }));
};
 
// Fetch summary data from backend API using the reusable HTTP client
export const fetchSummaryData = async (): Promise<SummaryCardProps[]> => {
  try {
    const result = await apiClient.get<{ data: SummaryApiResponse[] }>(
      DASHBOARD_API_ENDPOINTS.OVERVIEWS
    );
    console.log('Raw summary API response:', result);
 
    // Handle Strapi's response format
    const apiData = result.data || result;
 
    if (!Array.isArray(apiData)) {
      console.error('Expected array but got:', typeof apiData);
      throw new Error('Invalid response format');
    }
 
    return transformApiResponse(apiData);
  } catch (error) {
    console.error('Error fetching summary data:', error);
    throw error;
  }
};
 
// Query keys for React Query
export const summaryKeys = {
  all: ['summary'] as const,
  lists: () => [...summaryKeys.all, 'list'] as const,
  list: (filters: Record<string, any>) =>
    [...summaryKeys.lists(), { filters }] as const,
};
 
// React Query hook for fetching summary data
export const useSummaryData = () => {
  return useQuery({
    queryKey: summaryKeys.lists(),
    queryFn: fetchSummaryData,
  });
};