Skip to content

Commit

Permalink
Replace useDispatch with useQuery in Asset Management, Location M…
Browse files Browse the repository at this point in the history
…anagement, Facility Cover Image Popup, Doctor Capacity and Triage (#7004)

* Replace `useDispatch` with `useQuery` in Asset Create page

* Replace `useDispatch` with `useQuery` in Add Location Form

* Replace `useDispatch` with `useQuery` in Delete Cover Image Edit Modal

* Replace `useDispatch` with `useQuery` in Doctor Capacity and Counts

* Replace `useDispatch` with `useQuery` in Triage Form

* Replace `useDispatch` with `useQuery` in Doctor Capacity form

* fix bugs and cypress tests

---------

Co-authored-by: Mohammed Nihal <[email protected]>
  • Loading branch information
rithviknishad and nihal467 authored Jan 31, 2024
1 parent 2fe3b2d commit 9f852af
Show file tree
Hide file tree
Showing 12 changed files with 238 additions and 438 deletions.
2 changes: 1 addition & 1 deletion cypress/pageobject/Asset/AssetCreation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export class AssetPage {
cy.get(
"[data-testid=asset-last-serviced-on-input] input[type='text']"
).click();
cy.get("#date-input").click().type(lastServicedOn);
cy.get("#date-input").click().clear().type(lastServicedOn);
cy.get("[data-testid=asset-notes-input] textarea").clear().type(notes);
}

Expand Down
6 changes: 2 additions & 4 deletions src/Components/Assets/AssetTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ export enum AssetLocationType {
}

export interface AssetLocationObject {
id: string;
id?: string;
name: string;
description: string;
created_date?: string;
modified_date?: string;
location_type: AssetLocationType;
middleware_address?: string;
facility: {
facility?: {
id: string;
name: string;
};
Expand Down Expand Up @@ -105,8 +105,6 @@ export interface AssetData {
};
}

export type AssetUpdate = Partial<AssetData>;

export interface AssetsResponse {
count: number;
next?: string;
Expand Down
118 changes: 57 additions & 61 deletions src/Components/Facility/AddLocationForm.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import { useState, useEffect, lazy, SyntheticEvent } from "react";
import { useDispatch } from "react-redux";
import {
createFacilityAssetLocation,
getAnyFacility,
getFacilityAssetLocation,
updateFacilityAssetLocation,
} from "../../Redux/actions";
import { useState, lazy, SyntheticEvent } from "react";
import * as Notification from "../../Utils/Notifications.js";
import { navigate } from "raviger";
import { Submit, Cancel } from "../Common/components/ButtonV2";
Expand All @@ -14,17 +7,18 @@ import TextAreaFormField from "../Form/FormFields/TextAreaFormField";
import Page from "../Common/components/Page";
import { SelectFormField } from "../Form/FormFields/SelectFormField";
import { AssetLocationType } from "../Assets/AssetTypes";
import useQuery from "../../Utils/request/useQuery";
import routes from "../../Redux/api";
import request from "../../Utils/request/request";

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

interface LocationFormProps {
interface Props {
facilityId: string;
locationId?: string;
}

export const AddLocationForm = (props: LocationFormProps) => {
const { facilityId, locationId } = props;
const dispatchAction: any = useDispatch();
export const AddLocationForm = ({ facilityId, locationId }: Props) => {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [name, setName] = useState("");
const [middlewareAddress, setMiddlewareAddress] = useState("");
Expand All @@ -41,29 +35,30 @@ export const AddLocationForm = (props: LocationFormProps) => {
const headerText = !locationId ? "Add Location" : "Update Location";
const buttonText = !locationId ? "Add Location" : "Update Location";

useEffect(() => {
async function fetchFacilityName() {
setIsLoading(true);
if (facilityId) {
const res = await dispatchAction(getAnyFacility(facilityId));

setFacilityName(res?.data?.name || "");
}
if (locationId) {
const res = await dispatchAction(
getFacilityAssetLocation(facilityId, locationId)
);

setName(res?.data?.name || "");
setLocationName(res?.data?.name || "");
setDescription(res?.data?.description || "");
setLocationType(res?.data?.location_type || "");
setMiddlewareAddress(res?.data?.middleware_address || "");
}
setIsLoading(false);
}
fetchFacilityName();
}, [dispatchAction, facilityId, locationId]);
const facilityQuery = useQuery(routes.getAnyFacility, {
pathParams: { id: facilityId },
prefetch: !locationId,
onResponse: ({ data }) => {
data?.name && setFacilityName(data.name);
},
});

const locationQuery = useQuery(routes.getFacilityAssetLocation, {
pathParams: {
facility_external_id: facilityId,
external_id: locationId!,
},
prefetch: !!locationId,
onResponse: ({ data }) => {
if (!data) return;
setFacilityName(data.facility?.name ?? "");
setName(data.name);
setLocationName(data.name);
setDescription(data.description);
setLocationType(data.location_type);
setMiddlewareAddress(data.middleware_address ?? "");
},
});

const validateForm = () => {
let formValid = true;
Expand Down Expand Up @@ -109,39 +104,40 @@ export const AddLocationForm = (props: LocationFormProps) => {
name,
description,
middleware_address: middlewareAddress,
location_type: locationType,
location_type: locationType as AssetLocationType,
};

const res = await dispatchAction(
locationId
? updateFacilityAssetLocation(data, facilityId, locationId)
: createFacilityAssetLocation(data, facilityId)
);
const { res, error } = await (locationId
? request(routes.updateFacilityAssetLocation, {
body: data,
pathParams: {
facility_external_id: facilityId,
external_id: locationId,
},
})
: request(routes.createFacilityAssetLocation, {
body: data,
pathParams: { facility_external_id: facilityId },
}));

setIsLoading(false);
if (res) {
if (res.status === 201 || res.status === 200) {
const notificationMessage = locationId

if (res?.ok) {
navigate(`/facility/${facilityId}/location`, { replace: true });
Notification.Success({
msg: locationId
? "Location updated successfully"
: "Location created successfully";

navigate(`/facility/${facilityId}/location`, {
replace: true,
});
Notification.Success({
msg: notificationMessage,
});
} else if (res.status === 400) {
Object.keys(res.data).forEach((key) => {
setErrors((prevState: any) => ({
...prevState,
[key]: res.data[key],
}));
});
}
: "Location created successfully",
});
return;
}

if (error) {
setErrors(error);
}
};

if (isLoading) {
if (isLoading || locationQuery.loading || facilityQuery.loading) {
return <Loading />;
}

Expand Down
90 changes: 35 additions & 55 deletions src/Components/Facility/AssetCreate.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as Notification from "../../Utils/Notifications.js";

import { AssetClass, AssetData, AssetType } from "../Assets/AssetTypes";
import { AssetClass, AssetType } from "../Assets/AssetTypes";
import { Cancel, Submit } from "../Common/components/ButtonV2";
import {
LegacyRef,
Expand All @@ -11,12 +11,6 @@ import {
useReducer,
useState,
} from "react";
import {
createAsset,
getAsset,
listFacilityAssetLocation,
updateAsset,
} from "../../Redux/actions";

import CareIcon from "../../CAREUI/icons/CareIcon";
import { FieldErrorText, FieldLabel } from "../Form/FormFields/FormField";
Expand All @@ -32,13 +26,15 @@ import TextFormField from "../Form/FormFields/TextFormField";
import { navigate } from "raviger";
import { parseQueryParams } from "../../Utils/primitives";
import useAppHistory from "../../Common/hooks/useAppHistory";
import { useDispatch } from "react-redux";
import useVisibility from "../../Utils/useVisibility";
import { validateEmailAddress } from "../../Common/validation";
import { dateQueryString, parsePhoneNumber } from "../../Utils/utils.js";
import dayjs from "../../Utils/dayjs";
import DateFormField from "../Form/FormFields/DateFormField.js";
import { t } from "i18next";
import useQuery from "../../Utils/request/useQuery.js";
import routes from "../../Redux/api.js";
import request from "../../Utils/request/request.js";

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

Expand Down Expand Up @@ -124,18 +120,12 @@ const AssetCreate = (props: AssetProps) => {
const [support_email, setSupportEmail] = useState("");
const [location, setLocation] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [locations, setLocations] = useState<{ name: string; id: string }[]>(
[]
);
const [asset, setAsset] = useState<AssetData>();
const [facilityName, setFacilityName] = useState("");
const [qrCodeId, setQrCodeId] = useState("");
const [manufacturer, setManufacturer] = useState("");
const [warranty_amc_end_of_validity, setWarrantyAmcEndOfValidity] =
useState<any>(null);
const [last_serviced_on, setLastServicedOn] = useState<any>(null);
const [notes, setNotes] = useState("");
const dispatchAction: any = useDispatch();
const [isScannerActive, setIsScannerActive] = useState<boolean>(false);

const [currentSection, setCurrentSection] =
Expand Down Expand Up @@ -173,32 +163,20 @@ const AssetCreate = (props: AssetProps) => {
});
}, [generalDetailsVisible, warrantyDetailsVisible, serviceDetailsVisible]);

useEffect(() => {
setIsLoading(true);
dispatchAction(
listFacilityAssetLocation({}, { facility_external_id: facilityId })
).then(({ data }: any) => {
if (data.count > 0) {
setFacilityName(data.results[0].facility?.name);
setLocations(data.results);
}
setIsLoading(false);
});
const locationsQuery = useQuery(routes.listFacilityAssetLocation, {
pathParams: { facility_external_id: facilityId },
query: { limit: 1 },
});

if (assetId) {
setIsLoading(true);
dispatchAction(getAsset(assetId)).then(({ data }: any) => {
setAsset(data);
setIsLoading(false);
});
}
}, [assetId, dispatchAction, facilityId]);
const assetQuery = useQuery(routes.getAsset, {
pathParams: { external_id: assetId! },
prefetch: !!assetId,
onResponse: ({ data: asset }) => {
if (!asset) return;

useEffect(() => {
if (asset) {
setName(asset.name);
setDescription(asset.description);
setLocation(asset.location_object.id);
setLocation(asset.location_object.id!);
setAssetType(asset.asset_type);
setAssetClass(asset.asset_class);
setIsWorking(String(asset.is_working));
Expand All @@ -215,8 +193,8 @@ const AssetCreate = (props: AssetProps) => {
asset.last_service?.serviced_on &&
setLastServicedOn(asset.last_service?.serviced_on);
asset.last_service?.note && setNotes(asset.last_service?.note);
}
}, [asset]);
},
});

const validateForm = () => {
const errors = { ...initError };
Expand Down Expand Up @@ -355,26 +333,25 @@ const AssetCreate = (props: AssetProps) => {
}

if (!assetId) {
const res = await dispatchAction(createAsset(data));
if (res && res.data && res.status === 201) {
Notification.Success({
msg: "Asset created successfully",
});
if (!addMore) {
goBack();
} else {
const { res } = await request(routes.createAsset, { body: data });
if (res?.ok) {
Notification.Success({ msg: "Asset created successfully" });
if (addMore) {
resetFilters();
const pageContainer = window.document.getElementById("pages");
pageContainer?.scroll(0, 0);
} else {
goBack();
}
}
setIsLoading(false);
} else {
const res = await dispatchAction(updateAsset(assetId, data));
if (res && res.data && res.status === 200) {
Notification.Success({
msg: "Asset updated successfully",
});
const { res } = await request(routes.updateAsset, {
pathParams: { external_id: assetId },
body: data,
});
if (res?.ok) {
Notification.Success({ msg: "Asset updated successfully" });
goBack();
}
setIsLoading(false);
Expand All @@ -400,14 +377,15 @@ const AssetCreate = (props: AssetProps) => {
setIsScannerActive(false);
};

if (isLoading) return <Loading />;
if (isLoading || locationsQuery.loading || assetQuery.loading) {
return <Loading />;
}

if (locations.length === 0) {
if (locationsQuery.data?.count === 0) {
return (
<Page
title={assetId ? t("update_asset") : t("create_new_asset")}
crumbsReplacements={{
[facilityId]: { name: facilityName },
assets: { style: "text-gray-200 pointer-events-none" },
[assetId || "????"]: { name },
}}
Expand Down Expand Up @@ -486,7 +464,9 @@ const AssetCreate = (props: AssetProps) => {
title={`${assetId ? t("update") : t("create")} Asset`}
className="grow-0 pl-6"
crumbsReplacements={{
[facilityId]: { name: facilityName },
[facilityId]: {
name: locationsQuery.data?.results[0].facility?.name,
},
assets: { style: "text-gray-200 pointer-events-none" },
[assetId || "????"]: { name },
}}
Expand Down
Loading

0 comments on commit 9f852af

Please sign in to comment.