Skip to content

Commit

Permalink
Fix-searching (#36)
Browse files Browse the repository at this point in the history
Fix-searching (#36)
  • Loading branch information
jabahum authored Aug 13, 2024
1 parent 498da5b commit 927463a
Show file tree
Hide file tree
Showing 5 changed files with 112 additions and 78 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useMemo, useState } from "react";
import React, { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
extractErrorMessagesFromResponse,
Expand All @@ -11,7 +11,6 @@ import {
parseDate,
showNotification,
showSnackbar,
usePagination,
} from "@openmrs/esm-framework";
import {
DataTable,
Expand All @@ -37,15 +36,35 @@ const ClientRegistryData: React.FC = () => {
const { t } = useTranslation();
const [isLoading, setIsLoading] = useState(false);

const { patients, isLoading: loading, mutate } = usePatients("sarah", false);
const [searchQuery, setSearchQuery] = useState("");
const [debouncedSearchQuery, setDebouncedSearchQuery] = useState(searchQuery);

// Debounce the search input
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedSearchQuery(searchQuery);
}, 500);

return () => {
clearTimeout(handler);
};
}, [searchQuery]);

const {
patients,
isLoading: loading,
mutate,
} = usePatients(debouncedSearchQuery, false);

const pageSizes = [10, 20, 30, 40, 50];
const [currentPageSize, setPageSize] = useState(10);
const {
goTo,
results: paginatedPatientEntries,
currentPage,
} = usePagination(patients, currentPageSize);
const [currentPage, setCurrentPage] = useState(1);

const paginatedPatientEntries = useMemo(() => {
const startIndex = (currentPage - 1) * currentPageSize;
const endIndex = startIndex + currentPageSize;
return patients?.slice(startIndex, endIndex) || [];
}, [patients, currentPage, currentPageSize]);

const tableHeaders = useMemo(
() => [
Expand All @@ -67,42 +86,8 @@ const ClientRegistryData: React.FC = () => {
[t]
);

const startClientRegistry = async (e) => {
e.preventDefault();
setIsLoading(true);
startClientRegistryTask().then(
() => {
mutate();
setIsLoading(false);
showSnackbar({
isLowContrast: true,
title: t("runTask", "Start Client Registry Task"),
kind: "success",
subtitle: t(
"successfullyStarted",
`You have successfully started Client Registry`
),
});
},
(error) => {
const errorMessages = extractErrorMessagesFromResponse(error);

mutate();
setIsLoading(false);
showNotification({
title: t(
`errorStartingTask', 'Error Starting client registry task"),`
),
kind: "error",
critical: true,
description: errorMessages.join(", "),
});
}
);
};

const tableRows = useMemo(() => {
return patients?.map((patient, index) => ({
return paginatedPatientEntries.map((patient, index) => ({
...patient,
id: patient?.uuid,
name: patient?.person?.display,
Expand Down Expand Up @@ -144,27 +129,84 @@ const ClientRegistryData: React.FC = () => {
>
<ExtensionSlot
className={styles.menuLink}
state={{ patient: patients[index] }}
state={{ patient: paginatedPatientEntries[index] }}
name="cr-patients-actions-slot"
/>
</OrderCustomOverflowMenuComponent>
),
}));
}, [patients]);
}, [paginatedPatientEntries]);

const startClientRegistry = async (e) => {
e.preventDefault();
setIsLoading(true);
startClientRegistryTask().then(
() => {
mutate();
setIsLoading(false);
showSnackbar({
isLowContrast: true,
title: t("runTask", "Start Client Registry Task"),
kind: "success",
subtitle: t(
"successfullyStarted",
`You have successfully started Client Registry`
),
});
},
(error) => {
const errorMessages = extractErrorMessagesFromResponse(error);

mutate();
setIsLoading(false);
showNotification({
title: t("errorStartingTask", "Error Starting client registry task"),
kind: "error",
critical: true,
description: errorMessages.join(", "),
});
}
);
};

const handlePageChange = ({ pageSize, page }) => {
if (pageSize !== currentPageSize) {
setPageSize(pageSize);
setCurrentPage(1); // Reset to the first page when page size changes
} else if (page !== currentPage) {
setCurrentPage(page);
}
};

if (loading) {
return <DataTableSkeleton />;
}

return (
<div style={{ margin: "1rem" }}>
<Button
style={{ marginLeft: "1rem", marginBottom: "1rem" }}
onClick={(e) => startClientRegistry(e)}
kind="primary"
<div
style={{ marginBottom: "1rem", display: "flex", alignItems: "center" }}
>
{isLoading ? <InlineLoading /> : "Send All to CR"}
</Button>
<input
type="text"
placeholder="Search patients"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
style={{
marginRight: "2rem",
marginLeft: "1rem",
padding: "0.5rem",
flex: "1",
}}
/>
<Button
style={{ marginLeft: "1rem" }}
onClick={(e) => startClientRegistry(e)}
kind="primary"
>
{isLoading ? <InlineLoading /> : "Send All to CR"}
</Button>
</div>
<DataTable rows={tableRows} headers={tableHeaders} useZebraStyles>
{({
rows,
Expand All @@ -175,7 +217,7 @@ const ClientRegistryData: React.FC = () => {
getTableContainerProps,
}) => (
<TableContainer
{...getTableContainerProps}
{...getTableContainerProps()}
className={styles.tableContainer}
>
<Table {...getTableProps()} aria-label="patients">
Expand Down Expand Up @@ -217,16 +259,9 @@ const ClientRegistryData: React.FC = () => {
page={currentPage}
pageSize={currentPageSize}
pageSizes={pageSizes}
totalItems={paginatedPatientEntries?.length}
totalItems={patients?.length || 0} // Reflect the total number of patients
className={styles.pagination}
onChange={({ pageSize, page }) => {
if (pageSize !== currentPageSize) {
setPageSize(pageSize);
}
if (page !== currentPage) {
goTo(page);
}
}}
onChange={handlePageChange}
/>
</TableContainer>
)}
Expand Down
2 changes: 1 addition & 1 deletion src/client-registry/client-registry.resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export interface ValueReference {

// get Patients
export function usePatients(q: string, includeDead: boolean) {
const apiUrl = `${restBaseUrl}/patient?q=${q}&v=${v}&includeDead=${includeDead}&totalCount=true&limit=10`;
const apiUrl = `${restBaseUrl}/patient?q=${q}&v=${v}&includeDead=${includeDead}&totalCount=true`;
const { data, error, isLoading, isValidating, mutate } = useSWR<
FetchResponse,
Error
Expand Down
8 changes: 0 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,6 @@ export const syncTaskTypesLink = getSyncLifecycle(
options
);

export const clientRegistryLink = getSyncLifecycle(
createLeftPanelLink({
name: "client-registry",
title: "Client Registry",
}),
options
);

export const scheduleManagerLink = getSyncLifecycle(
createLeftPanelLink({
name: "schedule-manager",
Expand Down
6 changes: 5 additions & 1 deletion src/root.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import ClientRegistry from "./client-registry/client-registry.component";
import FacilityRegistry from "./facility-registry/facility-registry.component";
import ProductRegistry from "./product-registry/product-registry.component";
import ScheduleManager from "./scheduler/scheduler.component";
import SyncTaskTypes from "./fhir/sync-task-types/sync-task-types.component";

const Root: React.FC = () => {
const spaBasePath = window.spaBase;
Expand All @@ -27,7 +28,11 @@ const Root: React.FC = () => {
<main className={styles.container}>
<Routes>
<Route path="/" element={<FacilityMetrics />} />
<Route path="/facility-metrics" element={<FacilityMetrics />} />
<Route path="/fhir-exchange" element={<Fhir />} />
<Route path="/schedule-manager" element={<ScheduleManager />} />
<Route path="/sync-task-types" element={<SyncTaskTypes />} />

<Route
path="/client-registry-dashboard"
element={<ClientRegistry />}
Expand All @@ -40,7 +45,6 @@ const Root: React.FC = () => {
path="/product-registry-dashboard"
element={<ProductRegistry />}
/>
<Route path="/schedule-manager" element={<ScheduleManager />} />
</Routes>
</main>
</BrowserRouter>
Expand Down
17 changes: 10 additions & 7 deletions src/routes.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,17 @@
"slot": "health-exchange-left-panel-slot",
"order": 2
},
{
"component": "scheduleManagerLink",
"name": "scheduler-manager-link",
"slot": "health-exchange-left-panel-slot",
"order": 3
},
{
"component": "registriesDashboard",
"name": "client-registry-link",
"slot": "health-exchange-left-panel-slot"
"name": "registry-link",
"slot": "health-exchange-left-panel-slot",
"order": 4
},
{
"name": "vl-suppression-prediction",
Expand Down Expand Up @@ -161,11 +168,7 @@
"name": "product-registry-dashboard-ext",
"slot": "product-registry-dashboard-slot",
"component": "productRegistry"
},
{
"component": "scheduleManagerLink",
"name": "scheduler-manager-link",
"slot": "health-exchange-left-panel-slot"
}

]
}

0 comments on commit 927463a

Please sign in to comment.