All files / src/features/appointments/api appointments.hooks.ts

94.11% Statements 32/34
73.91% Branches 17/23
92.3% Functions 24/26
100% Lines 31/31

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136                      176x       29x       17x   4x                                             155x 155x   155x 150x   27x           155x 150x 150x               155x     150x     150x               147x               196x   196x   4x   3x 3x                       273x   273x   5x   5x 5x             77x   77x 2x         1x 1x          
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query'
 
import { useBabies } from '@/features/babies/api/babies.hooks'
import type { Baby } from '@/features/babies/api/babies.schemas'
 
import { createAppointment, fetchAppointments, fetchMedicalSpecialties, updateAppointment,
  deleteAppointment,
} from './appointments.api'
import type { Appointment, AppointmentFormInput, UpdateAppointmentInput } from './appointments.schemas'
 
export function appointmentsQueryKey(babyId: string) {
  return ['babies', babyId, 'appointments'] as const
}
 
function sortByScheduledAt(items: Appointment[]): Appointment[] {
  return [...items].sort((a, b) => a.scheduledAt.localeCompare(b.scheduledAt))
}
 
export function useAppointments(babyId: string | null) {
  return useQuery({
    queryKey: appointmentsQueryKey(babyId ?? ''),
    queryFn: () => fetchAppointments(babyId!),
    enabled: !!babyId,
    select: sortByScheduledAt,
  })
}
 
export interface BabyAppointmentsEntry {
  baby: Baby
  items: Appointment[]
  isPending: boolean
  isError: boolean
}
 
export interface AllBabiesAppointments {
  babies: Baby[]
  isPending: boolean
  isError: boolean
  isEmpty: boolean
  perBaby: BabyAppointmentsEntry[]
  items: Appointment[]
}
 
export function useAllBabiesAppointments(): AllBabiesAppointments {
  const babies = useBabies()
  const babyList = babies.data ?? []
 
  const results = useQueries({
    queries: babyList.map((baby) => ({
      queryKey: appointmentsQueryKey(baby.id),
      queryFn: () => fetchAppointments(baby.id),
      enabled: babies.isSuccess,
      select: sortByScheduledAt,
    })),
  })
 
  const perBaby: BabyAppointmentsEntry[] = babyList.map((baby, index) => {
    const result = results[index]
    return {
      baby,
      items: result?.data ?? [],
      isPending: result?.isPending ?? true,
      isError: result?.isError ?? false,
    }
  })
 
  return {
    babies: babyList,
    isPending: babies.isPending || (babies.isSuccess && results.some((result) => result.isPending)),
    isError: babies.isError || results.some((result) => result.isError),
    isEmpty: babies.isSuccess && babyList.length === 0,
    perBaby,
    items: perBaby.flatMap((entry) => entry.items),
  }
}
 
// Static reference data (medical specialties) — cached for the whole session, no need to refetch.
// No `initialData` here: seeding one would mark the query fresh before the first real
// fetch and, combined with `staleTime: Infinity`, permanently skip it.
export function useMedicalSpecialties() {
  return useQuery({
    queryKey: ['medical-specialties'],
    queryFn: fetchMedicalSpecialties,
    staleTime: Infinity,
  })
}
 
export function useCreateAppointment(babyId: string | null) {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: ({ input, specialistId }: { input: AppointmentFormInput; specialistId?: string }) =>
      createAppointment(babyId!, input, specialistId),
    onSuccess: (appointment) => {
      queryClient.setQueryData<Appointment[]>(appointmentsQueryKey(babyId ?? ''), (prev) =>
        prev ? [...prev, appointment] : [appointment],
      )
    },
  })
}
 
interface UpdateAppointmentVariables {
  appointmentId: string
  input: UpdateAppointmentInput
}
 
export function useUpdateAppointment(babyId: string) {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: ({ appointmentId, input }: UpdateAppointmentVariables) =>
      updateAppointment(babyId, appointmentId, input),
    onSuccess: (updated) => {
      queryClient.setQueryData<Appointment[]>(appointmentsQueryKey(babyId), (prev) =>
        prev?.map((appointment) => (appointment.id === updated.id ? updated : appointment)),
      )
    },
  })
}
 
export function useDeleteAppointment(babyId: string) {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: (appointmentId: string) => deleteAppointment(babyId, appointmentId),
    // Removed from the cached list rather than refetched, matching
    // useDeleteMilestone: the row disappears the moment the API confirms, with
    // no window where a deleted appointment is still on screen.
    onSuccess: (_data, deletedAppointmentId) => {
      queryClient.setQueryData<Appointment[]>(appointmentsQueryKey(babyId), (prev) =>
        prev?.filter((item) => item.id !== deletedAppointmentId),
      )
    },
  })
}