Skip to content

Your favorite shift management application!

2.5 KB
Raw Blame
"use client";

import { useQuery } from "@tanstack/react-query";
import { queryKeys } from "@/lib/query-keys";
import { LIVE_REFETCH_INTERVAL } from "@/lib/query-client";
import { formatDateToLocal } from "@/lib/date-utils";
import { ApiError } from "@/lib/api-error";
import { useIsCalendarAccessible } from "@/hooks/useCalendars";

export interface ShiftStatsData {
  period: string;
  startDate: string;
  endDate: string;
  stats: Record<string, { count: number; totalMinutes: number }>;
  totalMinutes: number;
  totalShifts: number;
  avgMinutesPerShift: number;
  avgShiftsPerDay: number;
  avgMinutesPerDay: number;
  minDuration: number;
  maxDuration: number;
  daysWithShifts: number;
  trendData: Array<{ date: string; count: number; totalMinutes: number }>;
}

interface UseShiftStatsOptions {
  calendarId: string | undefined;
  currentDate: Date;
  period: "week" | "month" | "year";
}

/**
 * Fetch shift statistics from API
 */
async function fetchShiftStatsApi(
  calendarId: string,
  period: string,
  currentDate: Date
): Promise<ShiftStatsData> {
  const params = new URLSearchParams({
    calendarId,
    period,
    date: formatDateToLocal(currentDate),
  });

  const response = await fetch(`/api/shifts/stats?${params}`);

  if (!response.ok) {
    throw new ApiError("Failed to fetch shift statistics", response.status);
  }

  return await response.json();
}

/**
 * Shift Statistics Hook
 *
 * Provides shift statistics for a calendar with automatic polling.
 * Uses React Query for automatic cache management and live updates.
 *
 * Features:
 * - Automatic polling every 5 seconds
 * - Statistics by calendar, period, and date
 * - Manual refetch available if needed
 *
 * @param calendarId - Calendar ID to fetch stats for
 * @param currentDate - Current date for stats calculation
 * @param period - Time period (week, month, year)
 * @returns Object with stats data and loading state
 */
export function useShiftStats({
  calendarId,
  currentDate,
  period,
}: UseShiftStatsOptions) {
  const accessible = useIsCalendarAccessible(calendarId);

  const {
    data: stats = null,
    isLoading: loading,
    error,
    refetch,
  } = useQuery({
    queryKey: queryKeys.stats.shifts(
      calendarId!,
      period,
      formatDateToLocal(currentDate)
    ),
    queryFn: () => fetchShiftStatsApi(calendarId!, period, currentDate),
    enabled: accessible,
    refetchInterval: LIVE_REFETCH_INTERVAL,
  });

  const forbidden = error instanceof ApiError && error.status === 403;

  return {
    stats,
    loading,
    forbidden,
    refetch,
  };
}