import { useCallback, useEffect, useState } from "react"; import { useCollaborationTeamServiceContext } from "../../../services/CollaborationTeamService.tsx"; import { usePractitionerServiceContext, type PractitionerWithRoles } from "../../../services/PractitionerService.tsx"; import { useFhirServiceContext } from "../../../services/FhirService.tsx"; import { formatFhirHumanName } from "../../../utils/fhirHumanName.tsx"; import { sectionReadFailure, type SectionReadFailure } from "../../../utils/sectionReadRefusal"; import { teamsWithPeopleFrom, type OrgCollabTeam } from "../../../utils/orgCollabTeams"; export interface OrgCollabTeamsState { /** Null until read. */ teams: OrgCollabTeam[] | null; failure: SectionReadFailure | null; reload: () => void; } /** The patient's own collaboration teams that people from this practice are in. */ export const useOrgCollabTeams = (orgId: string, organizationName?: string): OrgCollabTeamsState => { const { listTeams } = useCollaborationTeamServiceContext(); const { fetchPractitioners } = usePractitionerServiceContext(); const { unpackBundle } = useFhirServiceContext(); const [teams, setTeams] = useState(null); const [failure, setFailure] = useState(null); const [attempt, setAttempt] = useState(0); useEffect(() => { let cancelled = false; setTeams(null); setFailure(null); // The staff list only sharpens the match; without it the server's practice names still answer. const staff = fetchPractitioners(orgId) .then((bundle) => unpackBundle(bundle).map((p) => ({ id: p.practitioner.id ?? "", name: formatFhirHumanName(p.practitioner.name) || undefined, }))) .catch(() => null); Promise.all([listTeams(), staff]) .then(([all, people]) => { if (!cancelled) setTeams(teamsWithPeopleFrom(all, people, organizationName)); }) .catch((readError) => { if (!cancelled) setFailure(sectionReadFailure(readError)); }); return () => { cancelled = true; }; }, [orgId, organizationName, attempt, listTeams, fetchPractitioners, unpackBundle]); const reload = useCallback(() => setAttempt((n) => n + 1), []); return { teams, failure, reload }; };