import { useCallback, useMemo } from "react"; import type { Appointment, Location, Organization } from "fhir/r4"; import { useAuthServiceContext } from "../services"; import type { PractitionerWithRoles } from "../services/PractitionerService.tsx"; import { useMyOrganizations } from "./useMyOrganizations.tsx"; import { usePracticeZones } from "./usePracticeToday"; import { appointmentPractice, appointmentPracticeId, type AppointmentPractice } from "../utils/appointmentPractice"; /** * Each appointment's own practice and clock, for lists that can span practices. The signed-in * practice is only a place to look an id up, never an answer for an appointment that names none. */ export const useAppointmentPractices = ( appointments: readonly Appointment[], practitioners: readonly PractitionerWithRoles[], locations: readonly Location[], { readPatientPractices = true }: { readPatientPractices?: boolean } = {}, ): ((appointment: Appointment) => AppointmentPractice) => { const { wpOrganization } = useAuthServiceContext(); const { organizations } = useMyOrganizations({ enabled: readPatientPractices }); const ids = useMemo( () => appointments .map((appointment) => appointmentPracticeId(appointment, practitioners, locations)) .filter((id): id is string => Boolean(id)), [appointments, practitioners, locations], ); const zones = usePracticeZones(ids); const active = wpOrganization?.current; return useCallback( (appointment: Appointment) => appointmentPractice(appointment, { practitioners, locations, organizations: [...(active ? [active as Organization] : []), ...organizations], zoneOf: (id) => zones.get(id) ?? null, }), [practitioners, locations, organizations, active, zones], ); }; export default useAppointmentPractices;