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

Fix graph fetching #68

Merged
merged 4 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions packages/esm-patient-visits-report-app/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sjthc/esm-patient-visits-report-app",
"version": "1.2.4",
"version": "1.2.5",
"license": "MPL-2.0",
"description": "Custom Patient Visits Reports microfrontend for the OpenMRS SPA",
"browser": "dist/sjthc-esm-patient-visits-report-app.js",
Expand Down Expand Up @@ -60,5 +60,5 @@
"@types/uuid": "^9.0.4",
"webpack": "^5.88.2"
},
"gitHead": "00d79e741645544de68c19f1fb22501c60dd9000"
"gitHead": "e7a5be2c1f42c82f62be401ea16c00cc6933a8ce"
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,13 @@ const PatientVisitsReportHome: React.FC<PatientVisistsReportHomeProps> = () => {
{
header: t('id', 'ID'),
key: 'openmrsID',
},
{
header: t('diagnosis', 'Diagnosis'),
key: 'diagnosis',
}
]

if (category === "outPatientClients" || category === "opdVisits" || category === "opdRevisits" || category === "consultation"){
tableData.push({
header: t('diagnosis', 'Diagnosis'),
key: 'diagnosis'
})
}

const filteredData = opdCategoriesData?.filter((patient) => {
return patient.diagnosis?.toLowerCase().includes(searchString.toLowerCase())
})
Expand Down
215 changes: 78 additions & 137 deletions packages/esm-patient-visits-report-app/src/hooks/useOPDCategories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,74 +38,6 @@ export function useOPDCategories(initialCategory="outPatientClients") {
const [totalOpdVisits, setTotalOpdVisits] = useState(0);
const [totalOpdRevisits, setTotalOpdRevisits] = useState(0);

// const getOPDVisits = async ({page, size}) => {
// try {
// setLoading(true);

// const formatDateForReq = (dateString) => {
// const date = new Date(dateString);
// const year = date.getFullYear();
// const month = String(date.getMonth() + 1).padStart(2, '0');
// const day = String(date.getDate()).padStart(2, '0');
// return `${day}-${month}-${year}`;
// }

// let startString = formatDateForReq(dateRange.start);
// let endString = formatDateForReq(dateRange.end);

// const url = `/ws/rest/v1/ehospital/${category}?startDate=${startString}&endDate=${endString}&page=${page}&size=${size}`;
// const {data} = await openmrsFetch(url);
// const cardUrl = `/ws/rest/v1/ehospital/outPatientClients?startDate=${startString}&endDate=${endString}&page=${page}&size=${size}`;
// const {data: cardData} = await openmrsFetch(cardUrl);

// setData([])
// if (data.results.length > 0) {
// setData(prev => [...prev, ...data.results.map(result => ({
// ...result,
// fullName: result?.name,
// age: result?.age,
// gender: result?.sex,
// opdNumber: result.identifiers.find(item => item.identifierType.toLowerCase()?.includes("opd"))?.identifier,
// openmrsID: result.identifiers.find(item => item.identifierType.toLowerCase()?.includes("openmrs"))?.identifier,
// diagnosis: result?.diagnosis
// }))])
// setTotalPatients(cardData.totalPatients);
// setTotalOpdVisits(cardData.totalOpdVisits);
// setTotalOpdRevisits(cardData.totalOpdRevisits);
// setSummary(data.summary)
// }else {
// setSummary({
// groupYear: {},
// groupMonth: {},
// groupWeek: {}
// })
// }

// if (data.results.length === size)
// setCurrentPaginationState(prev => ({
// ...prev,
// page: ++prev.page
// }))

// }catch(e) {
// return e
// }finally{
// setLoading(false)
// }
// }

const deepMerge = (target, source) => {
for (let key in source) {
if (source[key] instanceof Object) {
if (!target[key]) Object.assign(target, { [key]: {} });
deepMerge(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
return target;
};

const getOPDVisits = async () => {
try {
const formatDateForReq = (dateString) => {
Expand All @@ -114,97 +46,106 @@ export function useOPDCategories(initialCategory="outPatientClients") {
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${day}-${month}-${year}`;
}
};

let startString = formatDateForReq(dateRange.start);
let endString = formatDateForReq(dateRange.end);

let currentPage = 0;
let allData = [];
let allData = [];
let hasMoreData = true;
let totalFetchedPatients = 0;
let totalFetchedOpdVisits = 0;
let totalFetchedOpdRevisits = 0;
let fetchedSummary = {
groupYear: {},
groupMonth: {},
groupWeek: {}
}


let cumulativeSummary = {
groupYear: {},
groupMonth: {},
groupWeek: {},
};

setLoading(true);

const firstBatchUrl = `/ws/rest/v1/ehospital/${category}?startDate=${startString}&endDate=${endString}&page=0&size=25`;
const { data: firstBatchResponse } = await openmrsFetch(firstBatchUrl);
const cardUrl = `/ws/rest/v1/ehospital/outPatientClients?startDate=${startString}&endDate=${endString}&page=0&size=25`;
const { data: cardData } = await openmrsFetch(cardUrl);

const firstBatchData = firstBatchResponse.results.map(result => ({
...result,
fullName: result?.name,
age: result?.age,
gender: result?.sex,
opdNumber: result.identifiers.find(item => item.identifierType.toLowerCase()?.includes("opd"))?.identifier,
openmrsID: result.identifiers.find(item => item.identifierType.toLowerCase()?.includes("openmrs"))?.identifier,
diagnosis: result?.diagnosis
}))

setData(firstBatchData);
totalFetchedPatients += cardData.totalPatients;
totalFetchedOpdVisits += cardData.totalOpdVisits;
totalFetchedOpdRevisits += cardData.totalOpdRevisits;
fetchedSummary = cardData.summary
setSummary(fetchedSummary)

if (firstBatchData.length < 25) {
setTotalPatients(firstBatchResponse.totalPatients);
}

setLoading(false);

if (firstBatchData.length === 25) {
setBackgroundLoading(true);
currentPage += 1;

while (hasMoreData) {

while (hasMoreData) {
const url = `/ws/rest/v1/ehospital/${category}?startDate=${startString}&endDate=${endString}&page=${currentPage}&size=25`;
const { data } = await openmrsFetch(url);

const fetchedData = data.results.map(result => ({
...result,
fullName: result?.name,
age: result?.age,
gender: result?.sex,
opdNumber: result.identifiers.find(item => item.identifierType.toLowerCase()?.includes("opd"))?.identifier,
openmrsID: result.identifiers.find(item => item.identifierType.toLowerCase()?.includes("openmrs"))?.identifier,
diagnosis: result?.diagnosis
}))

const { data: batchResponse } = await openmrsFetch(url);
const cardUrl = `/ws/rest/v1/ehospital/outPatientClients?startDate=${startString}&endDate=${endString}&page=${currentPage}&size=25`;
const { data: cardData } = await openmrsFetch(cardUrl);

const fetchedData = batchResponse.results.map(result => ({
...result,
fullName: result?.name,
age: result?.age,
gender: result?.sex,
opdNumber: result.identifiers.find(item => item.identifierType.toLowerCase()?.includes("opd"))?.identifier,
openmrsID: result.identifiers.find(item => item.identifierType.toLowerCase()?.includes("openmrs"))?.identifier,
diagnosis: result?.diagnosis
}));

allData = [...allData, ...fetchedData];
totalFetchedPatients += fetchedData.length;
fetchedSummary = deepMerge(fetchedSummary, data.summary)
setData(prevData => [...prevData, ...fetchedData]);
setData(allData);

if (currentPage === 0) {
totalFetchedOpdVisits += cardData.totalOpdVisits;
totalFetchedOpdRevisits += cardData.totalOpdRevisits;
setLoading(false);
} else {
setBackgroundLoading(true);
}

totalFetchedPatients += cardData.totalPatients;

const updateSummary = (sourceSummary, targetSummary) => {
Object.keys(sourceSummary).forEach(key => {
if (targetSummary[key]) {
targetSummary[key] += sourceSummary[key];
} else {
targetSummary[key] = sourceSummary[key];
}
});
};

updateSummary(batchResponse.summary.groupYear, cumulativeSummary.groupYear);
updateSummary(batchResponse.summary.groupMonth, cumulativeSummary.groupMonth);
updateSummary(batchResponse.summary.groupWeek, cumulativeSummary.groupWeek);

currentPage += 1;

if (fetchedData.length < 25) {
hasMoreData = false;
setBackgroundLoading(false);
}
}

setTotalPatients(totalFetchedPatients);
setTotalOpdVisits(totalFetchedOpdVisits);
setTotalOpdRevisits(totalFetchedOpdRevisits);
setSummary(fetchedSummary)
// setData(allData);
setLoading(false);
setBackgroundLoading(false);
}

cumulativeSummary.groupMonth = Object.keys(cumulativeSummary.groupMonth)
.sort((a, b) => {
const [aMonth, aWeek] = a.split('_Week');
const [bMonth, bWeek] = b.split('_Week');

const aDate: any = new Date(`${aMonth} 1, 2024`);
const bDate: any = new Date(`${bMonth} 1, 2024`);

return aDate - bDate || parseInt(aWeek) - parseInt(bWeek);
})
.reduce((sortedSummary, key) => {
sortedSummary[key] = cumulativeSummary.groupMonth[key];
return sortedSummary;
}, {});

setData(allData);
setTotalPatients(totalFetchedPatients);
setTotalOpdVisits(totalFetchedOpdVisits);
setTotalOpdRevisits(totalFetchedOpdRevisits);
setSummary(cumulativeSummary);
setLoading(false);
setBackgroundLoading(false);

} catch (e) {
console.error(e);
setLoading(false);
setBackgroundLoading(false);
}
};
};

useEffect(() => {
setCurrentPaginationState(prev => ({...prev, page: 0}))
Expand Down
Loading