import { useEffect, useState } from 'react'; import { useAuthServiceContext } from '../../services'; import { useOrganizationOwnerService } from '../../services/OrganizationOwnerService.tsx'; import { referencesPractitioner } from '../OrganizationOwnerNotice/ownerReference'; import type { SponsoredBilling } from './subscriptionWarningCopy'; const SPONSORED_MODE = 'contractor_sponsored'; /** * The sponsorship an administrator's billing warning is worded for, or undefined when the practice pays for itself or * the warning is not theirs. Sponsorship is the current billing mode, never the contractor's designation. The owner is * read for this practice and person only; until it answers, or if it cannot, it is unknown and no takeover is offered. */ export function useSponsoredBilling(billingMode: string | null | undefined, enabled: boolean): SponsoredBilling | undefined { const { currentOrganization, currentUser } = useAuthServiceContext(); const { fetchOwner } = useOrganizationOwnerService(); const organizationId = currentOrganization?.id; const practitionerId = currentUser?.fhir?.resourceType === 'Practitioner' ? currentUser.fhir.id : undefined; const key = enabled && billingMode === SPONSORED_MODE && organizationId ? organizationId + '|' + (practitionerId ?? '') : undefined; const [read, setRead] = useState<{ key: string; owner: SponsoredBilling['owner'] }>(); // Every opening reads afresh: on any change, including a return to an earlier practice or a warning that went // and came back, the previous answer is dropped in this render, before it can be shown. const [openedFor, setOpenedFor] = useState(key); if (openedFor !== key) { setOpenedFor(key); setRead(undefined); } useEffect(() => { if (!key || !organizationId) return; let active = true; fetchOwner(organizationId) .then((state) => { if (!active) return; const owner = state.status !== 'accepted' ? 'none' : referencesPractitioner(state.ownerPractitionerId, practitionerId) ? 'viewer' : 'other'; setRead({ key, owner }); }) .catch(() => { if (active) setRead({ key, owner: 'unknown' }); }); return () => { active = false; }; }, [key, organizationId, practitionerId, fetchOwner]); if (!key) return undefined; return { owner: read?.key === key ? read.owner : 'unknown' }; }