Skip to content

Commit

Permalink
Migrate useDispatch to request for exports (#8668)
Browse files Browse the repository at this point in the history
  • Loading branch information
rithviknishad authored Oct 1, 2024
1 parent d76d6d8 commit 80ca084
Show file tree
Hide file tree
Showing 16 changed files with 165 additions and 150 deletions.
30 changes: 16 additions & 14 deletions src/Common/hooks/useExport.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import dayjs from "../../Utils/dayjs";
import { useState } from "react";
import { useDispatch } from "react-redux";

export default function useExport() {
const dispatch: any = useDispatch();
const [isExporting, setIsExporting] = useState(false);

const getTimestamp = () => {
Expand All @@ -16,17 +14,17 @@ export default function useExport() {

const exportCSV = async (
filenamePrefix: string,
action: any,
getData: () => Promise<string | null>,
parse = (data: string) => data,
) => {
setIsExporting(true);

const filename = `${filenamePrefix}_${getTimestamp()}.csv`;

const res = await dispatch(action);
if (res.status === 200) {
const data = await getData();
if (data) {
const a = document.createElement("a");
const blob = new Blob([parse(res.data)], {
const blob = new Blob([parse(data)], {
type: "text/csv",
});
a.href = URL.createObjectURL(blob);
Expand All @@ -39,15 +37,15 @@ export default function useExport() {

const exportJSON = async (
filenamePrefix: string,
action: any,
getData: () => Promise<{ results: object[] } | null>,
parse = (data: string) => data,
) => {
setIsExporting(true);

const res = await dispatch(action);
if (res.status === 200) {
const data = await getData();
if (data?.results.length) {
const a = document.createElement("a");
const blob = new Blob([parse(JSON.stringify(res.data.results))], {
const blob = new Blob([parse(JSON.stringify(data.results))], {
type: "application/json",
});
a.href = URL.createObjectURL(blob);
Expand All @@ -59,7 +57,7 @@ export default function useExport() {
};

const exportFile = (
action: any,
action: () => Promise<{ results: object[] } | string | null>,
filePrefix = "export",
type = "csv",
parse = (data: string) => data,
Expand All @@ -68,13 +66,17 @@ export default function useExport() {

switch (type) {
case "csv":
exportCSV(filePrefix, action(), parse);
exportCSV(filePrefix, action as Parameters<typeof exportCSV>[1], parse);
break;
case "json":
exportJSON(filePrefix, action(), parse);
exportJSON(
filePrefix,
action as Parameters<typeof exportJSON>[1],
parse,
);
break;
default:
exportCSV(filePrefix, action(), parse);
exportCSV(filePrefix, action as Parameters<typeof exportCSV>[1], parse);
}
};

Expand Down
27 changes: 12 additions & 15 deletions src/Components/Assets/AssetsList.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Scanner } from "@yudiel/react-qr-scanner";
import * as Notification from "../../Utils/Notifications.js";
import { listAssets } from "../../Redux/actions";
import { assetClassProps, AssetData } from "./AssetTypes";
import { useState, useEffect, lazy } from "react";
import { Link, navigate } from "raviger";
Expand Down Expand Up @@ -317,13 +316,12 @@ const AssetsList = () => {
},
{
label: "Export Assets (JSON)",
action: () =>
authorizedForImportExport &&
listAssets({
...qParams,
json: true,
limit: totalCount,
}),
action: async () => {
const { data } = await request(routes.listAssets, {
query: { ...qParams, json: true, limit: totalCount },
});
return data ?? null;
},
type: "json",
filePrefix: `assets_${facility?.name ?? "all"}`,
options: {
Expand All @@ -334,13 +332,12 @@ const AssetsList = () => {
},
{
label: "Export Assets (CSV)",
action: () =>
authorizedForImportExport &&
listAssets({
...qParams,
csv: true,
limit: totalCount,
}),
action: async () => {
const { data } = await request(routes.listAssets, {
query: { ...qParams, csv: true, limit: totalCount },
});
return data ?? null;
},
type: "csv",
filePrefix: `assets_${facility?.name ?? "all"}`,
options: {
Expand Down
53 changes: 42 additions & 11 deletions src/Components/Common/Export.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import DropdownMenu, {
import ButtonV2 from "../../Components/Common/components/ButtonV2";
import CareIcon from "../../CAREUI/icons/CareIcon";
import useExport from "../../Common/hooks/useExport";
import { Route } from "../../Utils/request/types";
import request from "../../Utils/request/request";

interface ExportItem {
options?: DropdownItemProps;
type?: "csv" | "json";
filePrefix?: string;
label: string;
parse?: (data: string) => string;
action?: any;
action?: Parameters<ReturnType<typeof useExport>["exportFile"]>[0];
route?: Route<string | { results: object[] }, unknown>;
}

interface ExportMenuProps {
Expand All @@ -27,7 +30,8 @@ interface ExportButtonProps {
tooltip?: string | undefined;
tooltipClassName?: string;
type?: "csv" | "json";
action?: any;
action?: Parameters<ReturnType<typeof useExport>["exportFile"]>[0];
route?: Route<string | { results: object[] }, unknown>;
parse?: (data: string) => string;
filenamePrefix: string;
}
Expand All @@ -45,9 +49,18 @@ export const ExportMenu = ({
return (
<ButtonV2
disabled={isExporting || disabled}
onClick={() =>
exportFile(item.action, item.filePrefix, item.type, item.parse)
}
onClick={() => {
let action = item.action;
if (item.route) {
action = async () => {
const { data } = await request(item.route!);
return data ?? null;
};
}
if (action) {
exportFile(action, item.filePrefix, item.type, item.parse);
}
}}
border
ghost
className="py-2.5"
Expand All @@ -69,9 +82,18 @@ export const ExportMenu = ({
{exportItems.map((item) => (
<DropdownItem
key={item.label}
onClick={() =>
exportFile(item.action, item.filePrefix, item.type, item.parse)
}
onClick={() => {
let action = item.action;
if (item.route) {
action = async () => {
const { data } = await request(item.route!);
return data ?? null;
};
}
if (action) {
exportFile(action, item.filePrefix, item.type, item.parse);
}
}}
{...item.options}
>
{item.label}
Expand All @@ -94,9 +116,18 @@ export const ExportButton = ({
<>
<ButtonV2
disabled={isExporting || props.disabled}
onClick={() =>
exportFile(props.action, props.filenamePrefix, type, parse)
}
onClick={() => {
let action = props.action;
if (props.route) {
action = async () => {
const { data } = await request(props.route!);
return data ?? null;
};
}
if (action) {
exportFile(action, props.filenamePrefix, type, parse);
}
}}
className="tooltip mx-2 p-4 text-lg text-secondary-800 disabled:bg-transparent disabled:text-secondary-500"
variant="secondary"
ghost
Expand Down
13 changes: 7 additions & 6 deletions src/Components/ExternalResult/ResultList.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import ButtonV2 from "../Common/components/ButtonV2";
import { navigate } from "raviger";
import { lazy, useState } from "react";
import { externalResultList } from "../../Redux/actions";
import ListFilter from "./ListFilter";
import FacilitiesSelectDialogue from "./FacilitiesSelectDialogue";
import { FacilityModel } from "../Facility/models";
Expand All @@ -19,6 +18,7 @@ import { parsePhoneNumber } from "../../Utils/utils";
import useAuthUser from "../../Common/hooks/useAuthUser";
import { NonReadOnlyUsers } from "../../Utils/AuthorizeFor";
import ExternalResultImportModal from "./ExternalResultImportModal";
import request from "../../Utils/request/request";

const Loading = lazy(() => import("../Common/Loading"));

Expand Down Expand Up @@ -254,11 +254,12 @@ export default function ResultList() {
: []),
{
label: "Export Results",
action: () =>
externalResultList(
{ ...qParams, csv: true },
"externalResultList",
),
action: async () => {
const { data } = await request(routes.externalResultList, {
query: { ...qParams, csv: true },
});
return data ?? null;
},
filePrefix: "external_results",
options: {
icon: <CareIcon icon="l-export" />,
Expand Down
12 changes: 5 additions & 7 deletions src/Components/Facility/ConsultationDetails/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
getConsultation,
getPatient,
listAssetBeds,
listShiftRequests,
} from "../../../Redux/actions";
import { statusType, useAbortableEffect } from "../../../Common/utils";
import { lazy, useCallback, useState } from "react";
Expand Down Expand Up @@ -179,12 +178,11 @@ export const ConsultationDetails = (props: any) => {
setAbhaNumberData(abhaNumberData);

// Get shifting data
const shiftingRes = await dispatch(
listShiftRequests({ patient: id }, "shift-list-call"),
);
if (shiftingRes?.data?.results) {
const data = shiftingRes.data.results;
setActiveShiftingData(data);
const shiftRequestsQuery = await request(routes.listShiftRequests, {
query: { patient: id },
});
if (shiftRequestsQuery.data?.results) {
setActiveShiftingData(shiftRequestsQuery.data.results);
}
} else {
navigate("/not-found");
Expand Down
14 changes: 4 additions & 10 deletions src/Components/Facility/HospitalList.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
import {
downloadFacility,
downloadFacilityCapacity,
downloadFacilityDoctors,
downloadFacilityTriage,
} from "../../Redux/actions";
import { lazy, useEffect } from "react";
import { AdvancedFilterButton } from "../../CAREUI/interactive/FiltersSlideover";
import CountBlock from "../../CAREUI/display/Count";
Expand Down Expand Up @@ -160,22 +154,22 @@ export const HospitalList = () => {
exportItems={[
{
label: "Facilities",
action: downloadFacility,
route: routes.downloadFacility,
filePrefix: "facilities",
},
{
label: "Capacities",
action: downloadFacilityCapacity,
route: routes.downloadFacilityCapacity,
filePrefix: "capacities",
},
{
label: "Doctors",
action: downloadFacilityDoctors,
route: routes.downloadFacilityDoctors,
filePrefix: "doctors",
},
{
label: "Triages",
action: downloadFacilityTriage,
route: routes.downloadFacilityTriage,
filePrefix: "triages",
},
]}
Expand Down
22 changes: 13 additions & 9 deletions src/Components/Patient/ManagePatients.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
import { FacilityModel, PatientCategory } from "../Facility/models";
import { Link, navigate } from "raviger";
import { ReactNode, lazy, useEffect, useState } from "react";
import { getAllPatient } from "../../Redux/actions";
import { parseOptionId } from "../../Common/utils";

import { AdvancedFilterButton } from "../../CAREUI/interactive/FiltersSlideover";
Expand Down Expand Up @@ -53,6 +52,7 @@ import {
import { ICD11DiagnosisModel } from "../Diagnosis/types.js";
import { getDiagnosesByIds } from "../Diagnosis/utils.js";
import Tabs from "../Common/components/Tabs.js";
import request from "../../Utils/request/request.js";

const Loading = lazy(() => import("../Common/Loading"));

Expand Down Expand Up @@ -276,13 +276,6 @@ export const PatientManager = () => {
!durations.every((x) => x === 0);

let managePatients: any = null;

const exportPatients = (isFiltered: boolean) => {
const filters = { ...params, csv: true, facility: qParams.facility };
if (!isFiltered) delete filters.is_active;
return () => getAllPatient(filters, "downloadPatients");
};

const preventDuplicatePatientsDuetoPolicyId = (data: any) => {
// Generate a array which contains imforamation of duplicate patient IDs and there respective linenumbers
const lines = data.split("\n"); // Split the data into individual lines
Expand Down Expand Up @@ -923,7 +916,18 @@ export const PatientManager = () => {
exportItems={[
{
label: "Export Live patients",
action: exportPatients(true),
action: async () => {
const query = {
...params,
csv: true,
facility: qParams.facility,
};
delete qParams.is_active;
const { data } = await request(routes.patientList, {
query,
});
return data ?? null;
},
parse: preventDuplicatePatientsDuetoPolicyId,
},
]}
Expand Down
8 changes: 6 additions & 2 deletions src/Components/Patient/SampleViewAdmin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
SAMPLE_FLOW_RULES,
SAMPLE_TYPE_CHOICES,
} from "../../Common/constants";
import { downloadSampleTests } from "../../Redux/actions";
import * as Notification from "../../Utils/Notifications";
import { SampleTestModel } from "./models";
import UpdateStatusDialog from "./UpdateStatusDialog";
Expand Down Expand Up @@ -314,7 +313,12 @@ export default function SampleViewAdmin() {
breadcrumbs={false}
componentRight={
<ExportButton
action={() => downloadSampleTests({ ...qParams })}
action={async () => {
const { data } = await request(routes.getTestSampleList, {
query: { ...qParams, csv: true },
});
return data ?? null;
}}
parse={parseExportData}
filenamePrefix="samples"
/>
Expand Down
Loading

0 comments on commit 80ca084

Please sign in to comment.