Skip to content

Commit

Permalink
populate mamba reports (UCSF-IGHS#1847)
Browse files Browse the repository at this point in the history
* populate mamba reports

* update for the Mother-Hiv-Status

* fetching patient uuid

* address the pr comments

* use SWR for data fetching

* remove console log

* code clean-up

* ptrackerId search

* latest ptrackerId search
  • Loading branch information
lucyjemutai authored May 24, 2024
1 parent 02b422a commit 26b38d0
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 61 deletions.
59 changes: 59 additions & 0 deletions packages/esm-commons-lib/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
encounterRepresentation,
covidOutcomesCohortUUID,
} from '../constants';
import useSWR from 'swr';

const BASE_WS_API_URL = '/ws/rest/v1/';
const BASE_FHIR_API_URL = '/ws/fhir2/R4/';
Expand Down Expand Up @@ -255,3 +256,61 @@ export async function fetchMambaReportData(reportId: string) {
throw new Error(`Error fetching data for report_id=${reportId}: ${error}`);
}
}

export function useDataFetch(
reportType: 'fetchMambaAncData' | 'MotherHivStatus',
reportId?: string,
patientUuid?: string,
pTrackerId?: string,
) {
const fetcher = async (url) => {
const response = await openmrsFetch(url);
const data = await response.json();
if (data && data.results && data.results.length) {
const record = data.results[0].record;

for (const item of record) {
if (!isNaN(item.value)) {
return parseInt(item.value, 10);
} else if (isInvalidValue(item.value)) {
return '--';
} else {
return item.value;
}
}
}
return '--';
};

let endpoint = '';
switch (reportType) {
case 'fetchMambaAncData':
endpoint = `/ws/rest/v1/mamba/report?report_id=${reportId}&person_uuid=${patientUuid}`;
break;
case 'MotherHivStatus':
endpoint = `/ws/rest/v1/mamba/report?report_id=${reportId}&ptracker_id=${pTrackerId}&person_uuid=${patientUuid}`;
break;
default:
throw new Error('Invalid report type');
}

const { data, error } = useSWR(endpoint, fetcher, {
revalidateOnFocus: true,
revalidateOnReconnect: true,
});

return {
data,
isLoading: !error && !data,
isError: error,
};
}

function isInvalidValue(value) {
if (typeof value === 'string') {
return value.trim() === '';
} else if (value instanceof Date) {
return isNaN(value.getTime());
}
return false;
}
1 change: 1 addition & 0 deletions packages/esm-commons-lib/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ export interface DashboardConfig extends DashboardLinkConfig {

export interface PatientChartProps {
patientUuid: string;
pTrackerId?: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,29 @@ import styles from '../common.scss';
import { PatientChartProps } from '@ohri/openmrs-esm-ohri-commons-lib';
import CurrentPregnancy from './tabs/current-pregnancy.component';
import HivExposedInfant from './tabs/hiv-exposed-infant.component';
import { usePatient } from '@openmrs/esm-framework';
import { usePatient, useConfig } from '@openmrs/esm-framework';
import dayjs from 'dayjs';

const MaternalSummary: React.FC<PatientChartProps> = ({ patientUuid }) => {
const { t } = useTranslation();
const { identifiersTypes } = useConfig();
const { patient, isLoading } = usePatient(patientUuid);
const dob = patient?.birthDate;
const age = useMemo(() => dayjs().diff(dayjs(patient?.birthDate), 'year'), [patient?.birthDate]);
const [pTrackerId, setPtrackerId] = useState('');

useEffect(() => {
if (patient) {
const reversedIdentifiers = patient.identifier.slice().reverse();
const pTrackerIdentifier = reversedIdentifiers.find((identifier) => {
return identifier.type.coding[0].code === identifiersTypes.ptrackerIdentifierType;
});

if (pTrackerIdentifier) {
setPtrackerId(pTrackerIdentifier.value);
}
}
}, [identifiersTypes.ptrackerIdentifierType, patient]);

return (
<>
Expand All @@ -27,7 +42,7 @@ const MaternalSummary: React.FC<PatientChartProps> = ({ patientUuid }) => {
</TabList>
<TabPanels>
<TabPanel>
<CurrentPregnancy patientUuid={patientUuid} />
<CurrentPregnancy patientUuid={patientUuid} pTrackerId={pTrackerId} />
</TabPanel>
</TabPanels>
</Tabs>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
fetchPatientLastEncounter,
SummaryCardColumn,
SummaryCard,
fetchMambaReportData,
useDataFetch,
} from '@ohri/openmrs-esm-ohri-commons-lib';
import dayjs from 'dayjs';
import { moduleName } from '../../..';
Expand All @@ -35,7 +35,7 @@ export interface familyItemProps {
hivStatus: string;
finalOutcome: string;
}
const CurrentPregnancy: React.FC<PatientChartProps> = ({ patientUuid }) => {
const CurrentPregnancy: React.FC<PatientChartProps> = ({ patientUuid, pTrackerId }) => {
const { t } = useTranslation();
const currentPregnancyHeader = t('recentPregnancy', 'Recent Pregnancy');
const arvTherapyHeader = t('art', 'ART');
Expand All @@ -48,22 +48,10 @@ const CurrentPregnancy: React.FC<PatientChartProps> = ({ patientUuid }) => {
const [pregnancyOutcomes, setPregnancyOutcomes] = useState([]);
const [infantOutcomes, setInfantOutcomes] = useState([]);
const { formNames, encounterTypes, obsConcepts, formUuids } = useConfig();
const [totalAncCount, setTotalAncCount] = useState(null);

useEffect(() => {
const fetchData = async () => {
try {
const [totalAncCount] = await Promise.all([fetchMambaReportData('no_of_anc_visits')]);

setTotalAncCount(totalAncCount);
} catch (error) {
console.error('Error fetching data:', error);
throw new Error('Error fetching data. Please try again.');
}
};

fetchData();
}, []);
const { data: totalAncCount } = useDataFetch('fetchMambaAncData', 'no_of_anc_visits', patientUuid);
const { data: motherStatus } = useDataFetch('fetchMambaAncData', 'mother_status', patientUuid);
const { data: deliveryDate } = useDataFetch('fetchMambaAncData', 'estimated_date_of_delivery', patientUuid);
const { data: motherHivStatus } = useDataFetch('MotherHivStatus', 'mother_hiv_status', patientUuid, pTrackerId);

const headersFamily = [
{
Expand Down Expand Up @@ -238,58 +226,29 @@ const CurrentPregnancy: React.FC<PatientChartProps> = ({ patientUuid }) => {
{
key: 'motherHIVStatus',
header: t('motherHIVStatus', 'Mother HIV Status'),
encounterTypes: [encounterTypes.motherPostnatal, encounterTypes.labourAndDelivery, encounterTypes.antenatal],
getObsValue: (encounters) => {
const pncArtData = {
artInitiation: getObsFromEncounter(encounters[0], obsConcepts.artInitiationConcept),
motherHIVStatus: getObsFromEncounter(encounters[0], obsConcepts.hivTestResultConcept),
pTrackerId: getObsFromEncounter(encounters[0], obsConcepts.pTrackerIdConcept),
};
const lndArtData = {
artInitiation: getObsFromEncounter(encounters[1], obsConcepts.artInitiationConcept),
motherHIVStatus: getObsFromEncounter(encounters[1], obsConcepts.hivTestResultConcept),
pTrackerId: getObsFromEncounter(encounters[1], obsConcepts.pTrackerIdConcept),
};
const ancArtData = {
artInitiation: getObsFromEncounter(encounters[2], obsConcepts.artInitiationConcept),
motherHIVStatus: getObsFromEncounter(encounters[2], obsConcepts.hivTestResultConcept),
pTrackerId: getObsFromEncounter(encounters[2], obsConcepts.pTrackerIdConcept),
};
const latestArtData = getLatestArtDetails(pncArtData, lndArtData, ancArtData);
if (!latestArtData['motherHIVStatus']) {
return '--';
}

return latestArtData['motherHIVStatus'];
encounterTypes: [],
getObsValue: () => {
return motherHivStatus;
},
},

{
key: 'expectedDeliveryDate',
header: t('expectedDeliveryDate', 'Expected Delivery Date'),
encounterTypes: [encounterTypes.antenatal],
getObsValue: async ([encounter]) => {
return getObsFromEncounter(encounter, obsConcepts.eDDConcept, true);
},
getObsSummary: ([encounter]) => {
let edd = getObsFromEncounter(encounter, obsConcepts.eDDConcept, true);
if (edd !== '--') {
const days = calculateDateDifferenceInDate(edd);
edd = edd > 0 ? `In ${days}` : '';
}
return edd;
encounterTypes: [],
getObsValue: () => {
return deliveryDate;
},
},
{
key: 'motherStatus',
header: t('motherStatus', 'Mother Status'),
encounterTypes: [encounterTypes.labourAndDelivery],
getObsValue: async ([encounter]) => {
return getObsFromEncounter(encounter, obsConcepts.motherStatusConcept);
encounterTypes: [],
getObsValue: () => {
return motherStatus;
},
},
],
[],
[t, motherHivStatus, deliveryDate, motherStatus],
);

const arvTherapyColumns: SummaryCardColumn[] = useMemo(
Expand Down Expand Up @@ -367,8 +326,8 @@ const CurrentPregnancy: React.FC<PatientChartProps> = ({ patientUuid }) => {
{
key: 'ancVisitsAttended',
header: t('ancVisitsAttended', 'ANC visits attended'),
encounterTypes: [encounterTypes.antenatal],
getObsValue: async ([encounter]) => {
encounterTypes: [],
getObsValue: () => {
return totalAncCount;
},
},
Expand Down

0 comments on commit 26b38d0

Please sign in to comment.