import { useCallback } from 'react'; import type { Organization } from 'fhir/r4'; import type { SaveTransport } from '../utils/saveOperation'; import { useAuthServiceContext, useOrganizationServiceContext } from '../services'; import { environment } from '../environments/environment'; /** * Re-reads the practice, as the signed-in caller, into the session copy every practice save is built * from. Resolves undefined when the read fails, so the caller can say the copy may be stale. * `transport`: the save this re-read belongs to. Retired, nothing is sent, and its answer is installed nowhere. */ export const useRefreshSessionOrganization = () => { const { wpOrganization, setWpOrganization } = useAuthServiceContext(); const { fetchOrganizationAsCaller } = useOrganizationServiceContext(); return useCallback(async (transport?: SaveTransport): Promise => { const id = wpOrganization.current?.id; if (!id) return undefined; let fresh: Organization; try { fresh = await fetchOrganizationAsCaller(id, environment.wpData?.installationId, undefined, transport); } catch (error) { // A retired save's read is not a failed read: it is said nowhere. if ((error as { name?: unknown } | null)?.name === 'SaveRetiredError') throw error; return undefined; } transport?.admit(); if (wpOrganization.current?.id === id) setWpOrganization(fresh); return fresh; }, [wpOrganization, setWpOrganization, fetchOrganizationAsCaller]); };