Skip to content

Commit

Permalink
Merge pull request #65 from Samstar10/fix-pagination-bug
Browse files Browse the repository at this point in the history
Fix pagination bug
  • Loading branch information
Michaelndula authored Aug 23, 2024
2 parents 9e1058a + a2000fb commit 453af81
Show file tree
Hide file tree
Showing 2 changed files with 163 additions and 50 deletions.
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.3",
"version": "1.2.4",
"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": "837fc06789dabccc8bbc80af708c504fd6008f1f"
"gitHead": "00d79e741645544de68c19f1fb22501c60dd9000"
}
209 changes: 161 additions & 48 deletions packages/esm-patient-visits-report-app/src/hooks/useOPDCategories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import {getPaddedDateString, getPaddedTodayDateRange} from "../helpers/dateOps";
export function useOPDCategories(initialCategory="outPatientClients") {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [backgroundLoading, setBackgroundLoading] = useState(false);
const [currentPaginationState, setCurrentPaginationState] = useState({
size: 50,
size: 25,
page: 0
});
const [category, setCategory] = useState(initialCategory);
Expand Down Expand Up @@ -37,65 +38,177 @@ 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 => ({
// 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) => {
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);

let currentPage = 0;
let allData = [];
let hasMoreData = true;
let totalFetchedPatients = 0;
let totalFetchedOpdVisits = 0;
let totalFetchedOpdRevisits = 0;
let fetchedSummary = {
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
}))])
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)
}
}
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) {
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
}))

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

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

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

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

useEffect(() => {
setCurrentPaginationState(prev => ({...prev, page: 0}))
getOPDVisits({...currentPaginationState})
getOPDVisits()
}, [dateRange, category])

return {
Expand Down

0 comments on commit 453af81

Please sign in to comment.