All files / src/hooks useSandbox.ts

100% Statements 16/16
100% Branches 0/0
100% Functions 6/6
100% Lines 15/15

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                    2x 24x                     2x 26x   26x       11x                   11x               2x 22x   22x       9x 9x 9x 9x 9x        
/**
 * React Query hooks for sandbox mode management
 */
 
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getSandboxStatus, toggleSandboxMode, resetSandboxData, SandboxStatus } from '../api/sandbox';
 
/**
 * Hook to fetch current sandbox status
 */
export const useSandboxStatus = () => {
  return useQuery<SandboxStatus, Error>({
    queryKey: ['sandboxStatus'],
    queryFn: getSandboxStatus,
    staleTime: 30 * 1000, // 30 seconds
    refetchOnWindowFocus: true,
  });
};
 
/**
 * Hook to toggle sandbox mode
 */
export const useToggleSandbox = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: toggleSandboxMode,
    onSuccess: (data) => {
      // Update the sandbox status in cache
      queryClient.setQueryData(['sandboxStatus'], (old: SandboxStatus | undefined) => ({
        ...old,
        sandbox_mode: data.sandbox_mode,
      }));
 
      // Reload the page to ensure all components properly reflect the new mode
      // This is necessary because:
      // 1. Backend switches database schemas between live/sandbox
      // 2. Some UI elements need to reflect the new mode (e.g., warnings, disabled features)
      // 3. Prevents stale data from old mode appearing briefly
      window.location.reload();
    },
  });
};
 
/**
 * Hook to reset sandbox data
 */
export const useResetSandbox = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: resetSandboxData,
    onSuccess: () => {
      // Invalidate all data queries after reset
      queryClient.invalidateQueries({ queryKey: ['resources'] });
      queryClient.invalidateQueries({ queryKey: ['events'] });
      queryClient.invalidateQueries({ queryKey: ['services'] });
      queryClient.invalidateQueries({ queryKey: ['customers'] });
      queryClient.invalidateQueries({ queryKey: ['payments'] });
    },
  });
};