Skip to content

Commit 8f37be0

Browse files
committed
OHRI-2295 Update OHRI endpoints to use SWR
1 parent 41f1f66 commit 8f37be0

21 files changed

+374
-544
lines changed

packages/esm-commons-lib/src/api.resource.ts

+54-90
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,21 @@
1-
import { openmrsFetch } from '@openmrs/esm-framework';
1+
import { fhirBaseUrl, openmrsFetch, restBaseUrl } from '@openmrs/esm-framework';
22
import dayjs from 'dayjs';
3-
import {
4-
finalHIVCodeConcept,
5-
finalPositiveHIVValueConcept,
6-
computedHIV_StatusConcept,
7-
encounterRepresentation,
8-
covidOutcomesCohortUUID,
9-
} from './constants';
3+
import { encounterRepresentation } from './constants';
104
import useSWR from 'swr';
11-
12-
const BASE_WS_API_URL = '/ws/rest/v1/';
13-
const BASE_FHIR_API_URL = '/ws/fhir2/R4/';
5+
import { configSchema } from './config-schema';
6+
import { type ReportDataArray } from './types';
147

158
export function fetchLastVisit(uuid: string) {
16-
return openmrsFetch(`/ws/fhir2/R4/Encounter?patient=${uuid}&_sort=-date&_count=1`);
9+
return openmrsFetch(`${fhirBaseUrl}/Encounter?patient=${uuid}&_sort=-date&_count=1`);
1710
}
1811

1912
export function fetchPatientList(offSet: number = 0, pageSize: number = 10) {
20-
return openmrsFetch(`/ws/fhir2/R4/Patient?_getpagesoffset=${offSet}&_count=${pageSize}&_summary=data`);
13+
return openmrsFetch(`${fhirBaseUrl}/Patient?_getpagesoffset=${offSet}&_count=${pageSize}&_summary=data`);
2114
}
2215

2316
export function fetchTodayClients() {
2417
let date = dayjs().format('YYYY-MM-DD');
25-
return openmrsFetch(`/ws/fhir2/R4/Encounter?date=${date}`).then(({ data }) => {
18+
return openmrsFetch(`${fhirBaseUrl}/Encounter?date=${date}`).then(({ data }) => {
2619
if (data.entry?.length) {
2720
return cleanDuplicatePatientReferences(data);
2821
}
@@ -35,7 +28,7 @@ export function fetchPatientsFromObservationCodeConcept(codeConcept: string, val
3528
let startDate = dayjs().subtract(cutOffDays, 'day').format('YYYY-MM-DD');
3629

3730
return openmrsFetch(
38-
`/ws/fhir2/R4/Observation?code=${codeConcept}${valueConcept ? `&value-concept=${valueConcept}` : ''}${
31+
`${fhirBaseUrl}/Observation?code=${codeConcept}${valueConcept ? `&value-concept=${valueConcept}` : ''}${
3932
cutOffDays ? `&_lastUpdated=ge${startDate}&_lastUpdated=le${endDate}` : ''
4033
}`,
4134
).then(({ data }) => {
@@ -54,13 +47,13 @@ function cleanDuplicatePatientReferences(data) {
5447
patientRefs = Array.from(patientRefs);
5548
return Promise.all(
5649
patientRefs.map((ref) => {
57-
return openmrsFetch(BASE_FHIR_API_URL + ref);
50+
return openmrsFetch(fhirBaseUrl + `/` + ref);
5851
}),
5952
);
6053
}
6154

6255
export function performPatientSearch(query, objectVersion) {
63-
return openmrsFetch(`${BASE_WS_API_URL}/patient?q=${query}${objectVersion ? `&v=${objectVersion}` : ''}`, {
56+
return openmrsFetch(`${restBaseUrl}/patient?q=${query}${objectVersion ? `&v=${objectVersion}` : ''}`, {
6457
method: 'GET',
6558
});
6659
}
@@ -77,27 +70,25 @@ export function getPatients(searchPhrase?: string, offset?: number, pageSize: nu
7770
}
7871

7972
export async function getCohort(cohortUuid: string, version?: string) {
80-
const { data } = await openmrsFetch(
81-
BASE_WS_API_URL + `cohortm/cohort/${cohortUuid}${version ? `?v=${version}` : ``}`,
82-
);
73+
const { data } = await openmrsFetch(restBaseUrl + `/cohortm/cohort/${cohortUuid}${version ? `?v=${version}` : ``}`);
8374
data.cohortMembers = data.cohortMembers.filter((member) => !member.voided);
8475
return data;
8576
}
8677

8778
export async function getReportingCohort(cohortUuid: string, queryParams?: string[]) {
8879
const params = queryParams ? queryParams.join('&') : '';
89-
const url = params ? `reportingrest/cohort/${cohortUuid}?${params}` : `reportingrest/cohort/${cohortUuid}`;
90-
const { data } = await openmrsFetch(BASE_WS_API_URL + url);
80+
const url = params ? `/reportingrest/cohort/${cohortUuid}?${params}` : `/reportingrest/cohort/${cohortUuid}`;
81+
const { data } = await openmrsFetch(restBaseUrl + url);
9182
return data;
9283
}
9384

9485
export async function getReportingCohortMembers(cohortUuid: string, queryParams?: string[]) {
9586
const params = queryParams ? queryParams.join('&') : '';
96-
const url = params ? `reportingrest/cohort/${cohortUuid}?${params}` : `reportingrest/cohort/${cohortUuid}`;
97-
const { data } = await openmrsFetch(BASE_WS_API_URL + url);
87+
const url = params ? `/reportingrest/cohort/${cohortUuid}?${params}` : `/reportingrest/cohort/${cohortUuid}`;
88+
const { data } = await openmrsFetch(restBaseUrl + url);
9889
return Promise.all(
9990
data.members.map((member) => {
100-
return openmrsFetch(BASE_WS_API_URL + `patient/${member.uuid}?v=full`);
91+
return openmrsFetch(restBaseUrl + `/patient/${member.uuid}?v=full`);
10192
}),
10293
);
10394
}
@@ -106,8 +97,7 @@ export async function getCohorts(cohortTypeUuid?: string) {
10697
const {
10798
data: { results, error },
10899
} = await openmrsFetch(
109-
BASE_WS_API_URL +
110-
`cohortm/cohort?v=custom:(uuid,name,voided)${cohortTypeUuid ? `&cohortType=${cohortTypeUuid}` : ''}`,
100+
restBaseUrl + `/cohortm/cohort?v=custom:(uuid,name,voided)${cohortTypeUuid ? `&cohortType=${cohortTypeUuid}` : ''}`,
111101
);
112102
if (error) {
113103
throw error;
@@ -116,7 +106,7 @@ export async function getCohorts(cohortTypeUuid?: string) {
116106
}
117107

118108
export function addPatientToCohort(patientUuid: string, cohortUuid: string) {
119-
return openmrsFetch(`${BASE_WS_API_URL}cohortm/cohortmember`, {
109+
return openmrsFetch(`${restBaseUrl}/cohortm/cohortmember`, {
120110
method: 'POST',
121111
headers: {
122112
'Content-Type': 'application/json',
@@ -130,13 +120,13 @@ export function addPatientToCohort(patientUuid: string, cohortUuid: string) {
130120
}
131121

132122
export function evictCohortMembership(membershipUuid: string) {
133-
return openmrsFetch(`${BASE_WS_API_URL}cohortm/cohortmember/${membershipUuid}`, { method: 'DELETE' });
123+
return openmrsFetch(`${restBaseUrl}/cohortm/cohortmember/${membershipUuid}`, { method: 'DELETE' });
134124
}
135125

136126
export async function getPatientListsForPatient(patientUuid: string) {
137127
const {
138128
data: { results, error },
139-
} = await openmrsFetch(`${BASE_WS_API_URL}cohortm/cohortmember?patient=${patientUuid}&v=full`);
129+
} = await openmrsFetch(`${restBaseUrl}/cohortm/cohortmember?patient=${patientUuid}&v=full`);
140130
if (error) {
141131
throw error;
142132
}
@@ -145,7 +135,7 @@ export async function getPatientListsForPatient(patientUuid: string) {
145135

146136
export function fetchPatientsFinalHIVStatus(patientUUID: string) {
147137
return openmrsFetch(
148-
`/ws/fhir2/R4/Observation?code=${finalHIVCodeConcept}&value-concept=${finalPositiveHIVValueConcept}&patient=${patientUUID}&_sort=-date&_count=1`,
138+
`${fhirBaseUrl}/Observation?code=${configSchema.obsConcepts._default.finalHIVCodeConcept}&value-concept=${configSchema.obsConcepts._default.finalPositiveHIVValueConcept}&patient=${patientUUID}&_sort=-date&_count=1`,
149139
).then(({ data }) => {
150140
if (data.entry?.length) {
151141
return data.entry[0].resource.valueCodeableConcept.coding[0].display;
@@ -160,13 +150,13 @@ export function fetchPatientObservationFromEncounter(
160150
observationCode: string,
161151
) {
162152
return openmrsFetch(
163-
`/ws/fhir2/R4/Observation?patient=${patientUUID}&encounter=${encounterUUID}&code=${observationCode}&_sort=-date&_count=1`,
153+
`${fhirBaseUrl}/Observation?patient=${patientUUID}&encounter=${encounterUUID}&code=${observationCode}&_sort=-date&_count=1`,
164154
);
165155
}
166156

167157
export function fetchPatientComputedConcept_HIV_Status(patientUUID: string) {
168158
return openmrsFetch(
169-
`/ws/fhir2/R4/Observation?code=${computedHIV_StatusConcept}&value-concept=${computedHIV_StatusConcept}&patient=${patientUUID}&_sort=-date&_count=1`,
159+
`${fhirBaseUrl}/Observation?code=${configSchema.obsConcepts._default.computedHIV_StatusConcept}&value-concept=${configSchema.obsConcepts._default.computedHIV_StatusConcept}&patient=${patientUUID}&_sort=-date&_count=1`,
170160
).then(({ data }) => {
171161
if (data.entry?.length) {
172162
return data.entry[0].resource.valueCodeableConcept.coding[0].display;
@@ -177,7 +167,7 @@ export function fetchPatientComputedConcept_HIV_Status(patientUUID: string) {
177167

178168
export function fetchPatientLastEncounter(patientUuid: string, encounterType) {
179169
const query = `encounterType=${encounterType}&patient=${patientUuid}`;
180-
return openmrsFetch(`/ws/rest/v1/encounter?${query}&v=${encounterRepresentation}`).then(({ data }) => {
170+
return openmrsFetch(`${restBaseUrl}/encounter?${query}&v=${encounterRepresentation}`).then(({ data }) => {
181171
if (data.results.length) {
182172
const sortedEncounters = data.results.sort(
183173
(firstEncounter, secondEncounter) =>
@@ -190,26 +180,8 @@ export function fetchPatientLastEncounter(patientUuid: string, encounterType) {
190180
});
191181
}
192182

193-
export function fetchPatientCovidOutcome() {
194-
return openmrsFetch(`/ws/rest/v1/reportingrest/cohort/${covidOutcomesCohortUUID}`).then(({ data }) => {
195-
if (data.members?.length) {
196-
let patientRefs = data.members.map((member) => {
197-
return member.uuid;
198-
});
199-
patientRefs = new Set([...patientRefs]);
200-
patientRefs = Array.from(patientRefs);
201-
return Promise.all(
202-
patientRefs.map((ref) => {
203-
return openmrsFetch(BASE_FHIR_API_URL + '/Person/' + ref);
204-
}),
205-
);
206-
}
207-
return [];
208-
});
209-
}
210-
211183
export function fetchConceptNameByUuid(conceptUuid: string) {
212-
return openmrsFetch(`/ws/rest/v1/concept/${conceptUuid}/name?limit=1`).then(({ data }) => {
184+
return openmrsFetch(`${restBaseUrl}/concept/${conceptUuid}/name?limit=1`).then(({ data }) => {
213185
if (data.results.length) {
214186
const concept = data.results[data.results.length - 1];
215187
return concept.display;
@@ -219,7 +191,7 @@ export function fetchConceptNameByUuid(conceptUuid: string) {
219191
}
220192

221193
export function fetchPatientRelationships(patientUuid: string) {
222-
return openmrsFetch(`${BASE_WS_API_URL}relationship?person=${patientUuid}&v=full`).then(({ data }) => {
194+
return openmrsFetch(`${restBaseUrl}/relationship?person=${patientUuid}&v=full`).then(({ data }) => {
223195
if (data.results.length) {
224196
return data.results;
225197
}
@@ -228,35 +200,15 @@ export function fetchPatientRelationships(patientUuid: string) {
228200
}
229201

230202
export function fetchOpenMRSForms(formNames: string[]) {
231-
const fetch = (name) => openmrsFetch(`/ws/rest/v1/form?q=${name}&v=full`);
203+
const fetch = (name) => openmrsFetch(`${restBaseUrl}/form?q=${name}&v=full`);
232204
return Promise.all(formNames.map((name) => fetch(name)));
233205
}
234206

235207
export function fetchFormsClobData(valueReferences: string[]) {
236-
const fetch = (ref: string) => openmrsFetch(`/ws/rest/v1/clobdata/${ref}`);
208+
const fetch = (ref: string) => openmrsFetch(`${restBaseUrl}/clobdata/${ref}`);
237209
return Promise.all(valueReferences?.map((ref) => fetch(ref)));
238210
}
239211

240-
export async function fetchMambaReportData(reportId: string) {
241-
try {
242-
const response = await openmrsFetch(`ws/rest/v1/mamba/report?report_id=${reportId}`);
243-
const data = await response.json();
244-
245-
if (data && data.results && data.results.length > 0) {
246-
const record = data.results[0].record;
247-
248-
for (const item of record) {
249-
return item.value ? parseInt(item.value, 10) : 0;
250-
}
251-
}
252-
253-
return 0;
254-
} catch (error) {
255-
console.error(`Error fetching data for report_id=${reportId}: `, error);
256-
throw new Error(`Error fetching data for report_id=${reportId}: ${error}`);
257-
}
258-
}
259-
260212
export function fetchEtlData(
261213
reportType: 'fetchMambaAncData' | 'MotherHivStatus',
262214
reportId?: string,
@@ -285,10 +237,10 @@ export function fetchEtlData(
285237
let endpoint = '';
286238
switch (reportType) {
287239
case 'fetchMambaAncData':
288-
endpoint = `/ws/rest/v1/mamba/report?report_id=${reportId}&person_uuid=${patientUuid}`;
240+
endpoint = `${restBaseUrl}/mamba/report?report_id=${reportId}&person_uuid=${patientUuid}`;
289241
break;
290242
case 'MotherHivStatus':
291-
endpoint = `/ws/rest/v1/mamba/report?report_id=${reportId}&ptracker_id=${pTrackerId}&person_uuid=${patientUuid}`;
243+
endpoint = `${restBaseUrl}/mamba/report?report_id=${reportId}&ptracker_id=${pTrackerId}&person_uuid=${patientUuid}`;
292244
break;
293245
default:
294246
throw new Error('Invalid report type');
@@ -323,19 +275,19 @@ export async function getCohortList(
323275
) {
324276
const params = queryParams ? queryParams.join('&') : '';
325277
const cohortMembersUrl = params
326-
? `reportingrest/cohort/${cohortUuid}?${params}`
327-
: `reportingrest/cohort/${cohortUuid}`;
328-
const cohortUrl = `cohortm/cohort/${cohortUuid}?v=full`;
278+
? `/reportingrest/cohort/${cohortUuid}?${params}`
279+
: `/reportingrest/cohort/${cohortUuid}`;
280+
const cohortUrl = `/cohortm/cohort/${cohortUuid}?v=full`;
329281

330282
const url = isReportingCohort ? cohortMembersUrl : cohortUrl;
331283

332-
const { data } = await openmrsFetch(BASE_WS_API_URL + url);
284+
const { data } = await openmrsFetch(restBaseUrl + url);
333285

334286
if (data?.members) {
335287
return Promise.all(
336288
data.members.map((member) => {
337289
return openmrsFetch(
338-
`/ws/rest/v1/encounter?encounterType=${encounterType}&patient=${member.uuid}&v=${encounterRepresentation}`,
290+
`${restBaseUrl}/encounter?encounterType=${encounterType}&patient=${member.uuid}&v=${encounterRepresentation}`,
339291
).then(({ data }) => {
340292
if (data.results.length) {
341293
const sortedEncounters = data.results.sort(
@@ -355,15 +307,14 @@ export async function getCohortList(
355307
return Promise.all(
356308
data.cohortMembers.map((member) => {
357309
return openmrsFetch(
358-
`/ws/rest/v1/encounter?encounterType=${encounterType}&patient=${member.patient.uuid}&v=${encounterRepresentation}`,
310+
`${restBaseUrl}/encounter?encounterType=${encounterType}&patient=${member.patient.uuid}&v=${encounterRepresentation}`,
359311
).then(({ data }) => {
360312
if (data.results.length) {
361-
const sortedEncounters = data.results
362-
.sort(
363-
(firstEncounter, secondEncounter) =>
364-
new Date(secondEncounter.encounterDatetime).getTime() -
365-
new Date(firstEncounter.encounterDatetime).getTime(),
366-
);
313+
const sortedEncounters = data.results.sort(
314+
(firstEncounter, secondEncounter) =>
315+
new Date(secondEncounter.encounterDatetime).getTime() -
316+
new Date(firstEncounter.encounterDatetime).getTime(),
317+
);
367318
return sortedEncounters[0];
368319
}
369320
return null;
@@ -372,3 +323,16 @@ export async function getCohortList(
372323
);
373324
}
374325
}
326+
327+
export function useMambaReportData(reportId: string) {
328+
const { data, error, isLoading } = useSWR<{ data: { results: ReportDataArray } }, Error>(
329+
`${restBaseUrl}/mamba/report?report_id=${reportId}`,
330+
openmrsFetch,
331+
);
332+
333+
return {
334+
data: data?.data?.results[0]?.record[0]?.value ?? 0,
335+
error,
336+
isLoading,
337+
};
338+
}

packages/esm-commons-lib/src/components/banner-tags/.patient-status-tag.test.tsx

-36
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
1-
import React, { useEffect, useState } from 'react';
1+
import React from 'react';
22
import { Tag } from '@carbon/react';
33
import { useTranslation } from 'react-i18next';
4-
import { isPatientHivPositive } from './patientHivStatus';
4+
import { usePatientsFinalHIVStatus } from './usePatientHivStatus';
5+
import { useConfig } from '@openmrs/esm-framework';
56

67
export function PatientStatusBannerTag({ patientUuid }) {
78
const { t } = useTranslation();
8-
const [hivPositive, setHivPositive] = useState(false);
9+
const { obsConcepts } = useConfig();
10+
const { isLoading, hivStatus, error } = usePatientsFinalHIVStatus(
11+
patientUuid,
12+
obsConcepts.finalHIVCodeConcept,
13+
obsConcepts.finalPositiveHIVValueConcept,
14+
);
915

10-
useEffect(() => {
11-
isPatientHivPositive(patientUuid).then((result) => setHivPositive(result));
12-
}, [hivPositive, patientUuid]);
16+
if (isLoading) {
17+
return <p>{t('loading', 'Loading...')}</p>;
18+
}
1319

14-
//TODO: Improve refresh time
15-
// forceRerender();
20+
if (error) {
21+
return <p>{t('error', 'Error...')}</p>;
22+
}
1623

17-
return <>{hivPositive && <Tag type="red">{t('hivPositive', 'HIV Positive')}</Tag>}</>;
24+
return <>{hivStatus && <Tag type="red">{t('hivPositive', 'HIV Positive')}</Tag>}</>;
1825
}

0 commit comments

Comments
 (0)