Skip to content

Commit

Permalink
OHRI-2295 Update OHRI endpoints to use SWR
Browse files Browse the repository at this point in the history
  • Loading branch information
CynthiaKamau committed Jul 12, 2024
1 parent 41f1f66 commit 673fcc2
Show file tree
Hide file tree
Showing 14 changed files with 325 additions and 450 deletions.
64 changes: 25 additions & 39 deletions packages/esm-commons-lib/src/api.resource.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
import { openmrsFetch } from '@openmrs/esm-framework';
import dayjs from 'dayjs';
import {
finalHIVCodeConcept,
finalPositiveHIVValueConcept,
computedHIV_StatusConcept,
encounterRepresentation,
covidOutcomesCohortUUID,
} from './constants';
import { BASE_FHIR_API_URL, BASE_WS_API_URL, encounterRepresentation } from './constants';
import useSWR from 'swr';

const BASE_WS_API_URL = '/ws/rest/v1/';
const BASE_FHIR_API_URL = '/ws/fhir2/R4/';
import { configSchema } from './config-schema';

export function fetchLastVisit(uuid: string) {
return openmrsFetch(`/ws/fhir2/R4/Encounter?patient=${uuid}&_sort=-date&_count=1`);
Expand Down Expand Up @@ -145,7 +137,7 @@ export async function getPatientListsForPatient(patientUuid: string) {

export function fetchPatientsFinalHIVStatus(patientUUID: string) {
return openmrsFetch(
`/ws/fhir2/R4/Observation?code=${finalHIVCodeConcept}&value-concept=${finalPositiveHIVValueConcept}&patient=${patientUUID}&_sort=-date&_count=1`,
`/ws/fhir2/R4/Observation?code=${configSchema.obsConcepts._default.finalHIVCodeConcept}&value-concept=${configSchema.obsConcepts._default.finalPositiveHIVValueConcept}&patient=${patientUUID}&_sort=-date&_count=1`,
).then(({ data }) => {
if (data.entry?.length) {
return data.entry[0].resource.valueCodeableConcept.coding[0].display;
Expand All @@ -166,7 +158,7 @@ export function fetchPatientObservationFromEncounter(

export function fetchPatientComputedConcept_HIV_Status(patientUUID: string) {
return openmrsFetch(
`/ws/fhir2/R4/Observation?code=${computedHIV_StatusConcept}&value-concept=${computedHIV_StatusConcept}&patient=${patientUUID}&_sort=-date&_count=1`,
`/ws/fhir2/R4/Observation?code=${configSchema.obsConcepts._default.computedHIV_StatusConcept}&value-concept=${configSchema.obsConcepts._default.computedHIV_StatusConcept}&patient=${patientUUID}&_sort=-date&_count=1`,
).then(({ data }) => {
if (data.entry?.length) {
return data.entry[0].resource.valueCodeableConcept.coding[0].display;
Expand All @@ -191,7 +183,9 @@ export function fetchPatientLastEncounter(patientUuid: string, encounterType) {
}

export function fetchPatientCovidOutcome() {
return openmrsFetch(`/ws/rest/v1/reportingrest/cohort/${covidOutcomesCohortUUID}`).then(({ data }) => {
return openmrsFetch(
`/ws/rest/v1/reportingrest/cohort/${configSchema.obsConcepts._default.covidOutcomesCohortUUID}`,
).then(({ data }) => {
if (data.members?.length) {
let patientRefs = data.members.map((member) => {
return member.uuid;
Expand Down Expand Up @@ -237,26 +231,6 @@ export function fetchFormsClobData(valueReferences: string[]) {
return Promise.all(valueReferences?.map((ref) => fetch(ref)));
}

export async function fetchMambaReportData(reportId: string) {
try {
const response = await openmrsFetch(`ws/rest/v1/mamba/report?report_id=${reportId}`);
const data = await response.json();

if (data && data.results && data.results.length > 0) {
const record = data.results[0].record;

for (const item of record) {
return item.value ? parseInt(item.value, 10) : 0;
}
}

return 0;
} catch (error) {
console.error(`Error fetching data for report_id=${reportId}: `, error);
throw new Error(`Error fetching data for report_id=${reportId}: ${error}`);
}
}

export function fetchEtlData(
reportType: 'fetchMambaAncData' | 'MotherHivStatus',
reportId?: string,
Expand Down Expand Up @@ -358,12 +332,11 @@ export async function getCohortList(
`/ws/rest/v1/encounter?encounterType=${encounterType}&patient=${member.patient.uuid}&v=${encounterRepresentation}`,
).then(({ data }) => {
if (data.results.length) {
const sortedEncounters = data.results
.sort(
(firstEncounter, secondEncounter) =>
new Date(secondEncounter.encounterDatetime).getTime() -
new Date(firstEncounter.encounterDatetime).getTime(),
);
const sortedEncounters = data.results.sort(
(firstEncounter, secondEncounter) =>
new Date(secondEncounter.encounterDatetime).getTime() -
new Date(firstEncounter.encounterDatetime).getTime(),
);
return sortedEncounters[0];
}
return null;
Expand All @@ -372,3 +345,16 @@ export async function getCohortList(
);
}
}

export function useMambaReportData(reportId: string) {
const { data, error, isLoading } = useSWR<{ data: { results: any } }, Error>(
`${BASE_WS_API_URL}/mamba/report?report_id=${reportId}`,
openmrsFetch,
);

return {
data: data?.data ? data?.data?.results : '0',
error,
isLoading,
};
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import React, { useEffect, useState } from 'react';
import React from 'react';
import { Tag } from '@carbon/react';
import { useTranslation } from 'react-i18next';
import { isPatientHivPositive } from './patientHivStatus';
import { usePatientsFinalHIVStatus } from './usePatientHivStatus';
import { useConfig } from '@openmrs/esm-framework';

export function PatientStatusBannerTag({ patientUuid }) {
const { t } = useTranslation();
const [hivPositive, setHivPositive] = useState(false);
const { obsConcepts } = useConfig();
const { isLoading, hivStatus, error } = usePatientsFinalHIVStatus(
patientUuid,
obsConcepts.finalHIVCodeConcept,
obsConcepts.finalPositiveHIVValueConcept,
);

useEffect(() => {
isPatientHivPositive(patientUuid).then((result) => setHivPositive(result));
}, [hivPositive, patientUuid]);
if (isLoading) {
return <p>{t('loading', 'Loading...')}</p>;
}

//TODO: Improve refresh time
// forceRerender();
if (error) {
return <p>{t('error', 'Error...')}</p>;
}

return <>{hivPositive && <Tag type="red">{t('hivPositive', 'HIV Positive')}</Tag>}</>;
return <>{hivStatus && <Tag type="red">{t('hivPositive', 'HIV Positive')}</Tag>}</>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { PatientStatusBannerTag } from './patient-status-tag.component';
import { usePatientsFinalHIVStatus } from './usePatientHivStatus';
import { useConfig } from '@openmrs/esm-framework';

const mockedUsePatientsFinalHIVStatus = jest.mocked(usePatientsFinalHIVStatus);
const mockUseConfig = jest.mocked(useConfig);

jest.mock('./usePatientHivStatus', () => {
const originalModule = jest.requireActual('./usePatientHivStatus');

return {
...originalModule,
usePatientsFinalHIVStatus: jest.fn().mockImplementation(() => ({
hivStatus: true,
isLoading: false,
})),
};
});

describe('PatientStatusBannerTag', () => {
beforeEach(() => {
jest.clearAllMocks();
mockUseConfig.mockReturnValue({
obsConcepts: {
finalHIVCodeConcept: 'e16b0068-b6a2-46b7-aba9-e3be00a7b4ab',
finalPositiveHIVValueConcept: '703AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
},
});
});

const samplePatientUuid = '703AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';

it('renders red tag when patient is HIV positive', async () => {
render(<PatientStatusBannerTag patientUuid={samplePatientUuid} />);
expect(screen.getByText(/HIV Positive/i)).toBeInTheDocument();
});

it('does not render red tag when patient is not HIV positive', async () => {
mockedUsePatientsFinalHIVStatus.mockReturnValue({ hivStatus: false, isLoading: false, error: null });
render(<PatientStatusBannerTag patientUuid={samplePatientUuid} />);
expect(screen.queryByText('HIV Positive')).not.toBeInTheDocument();
});
});

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { fhirBaseUrl, openmrsFetch } from '@openmrs/esm-framework';
import useSWR from 'swr';

export function usePatientsFinalHIVStatus(
patientUuid: string,
finalHIVCodeConcept: string,
finalPositiveHIVValueConcept: string,
) {
const url = `${fhirBaseUrl}/Observation?code=${finalHIVCodeConcept}&value-concept=${finalPositiveHIVValueConcept}&patient=${patientUuid}&_sort=-date&_count=1`;
const { data, error, isLoading, mutate } = useSWR<{ data: any }, Error>(url, openmrsFetch);

const hivStatusResult = data?.data?.entry[0].resource.valueCodeableConcept.coding[0].display;
const hivStatus = hivStatusResult.toLowerCase().includes('positive') ? true : false;

return { hivStatus: hivStatus, isLoading: isLoading, error: error };
}
Loading

0 comments on commit 673fcc2

Please sign in to comment.