Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

populate mamba reports #1847

Merged
merged 9 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,34 @@ 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 identifiers = patient.identifier;
let pTrackerIdentifier;

for (let i = identifiers.length - 1; i >= 0; i--) {
if (identifiers[i].type.coding[0].code === identifiersTypes.ptrackerIdentifierType) {
pTrackerIdentifier = identifiers[i];
break;
}
}
lucyjemutai marked this conversation as resolved.
Show resolved Hide resolved

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

return (
<>
Expand All @@ -27,7 +47,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 @@ -237,58 +225,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;
lucyjemutai marked this conversation as resolved.
Show resolved Hide resolved
},
},
{
key: 'motherStatus',
header: t('motherStatus', 'Mother Status'),
encounterTypes: [encounterTypes.labourAndDelivery],
getObsValue: async ([encounter]) => {
return getObsFromEncounter(encounter, obsConcepts.motherStatusConcept);
encounterTypes: [],
getObsValue: () => {
return motherStatus;
lucyjemutai marked this conversation as resolved.
Show resolved Hide resolved
},
},
],
[],
[t, motherHivStatus, deliveryDate, motherStatus],
);

const arvTherapyColumns: SummaryCardColumn[] = useMemo(
Expand Down Expand Up @@ -366,8 +325,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
Loading