Skip to content

Commit

Permalink
Replaced useDispatch with useQuery/request in Inventory Management (#…
Browse files Browse the repository at this point in the history
…7041)

* replace useDispacth with useQuery in inventoryList

* replace useDispatch with useQuery/request in InventoryLog

* fix failed test case

* replace useDispatch with useQuery/request in MinQuantity List

* replace useDispatch with useQuery/request in minimum quantity required modal

* replace useDispatch with useQuery/request in SetInventoryForm

* implement requested changes

* replace useDispatch with useQuery/request in AddInventoryForm

* delete all unused fire requests

* implement requested changes

* remove duplicatly defined model

---------

Co-authored-by: Mohammed Nihal <[email protected]>
  • Loading branch information
sriharsh05 and nihal467 authored Jan 31, 2024
1 parent 9f852af commit 9d2f678
Show file tree
Hide file tree
Showing 9 changed files with 317 additions and 460 deletions.
128 changes: 46 additions & 82 deletions src/Components/Facility/AddInventoryForm.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
import { useCallback, useReducer, useState, useEffect, lazy } from "react";
import { useDispatch } from "react-redux";
import { useReducer, useState, useEffect, lazy } from "react";
import Card from "../../CAREUI/display/Card";
import { statusType, useAbortableEffect } from "../../Common/utils";
import {
getItems,
postInventory,
getAnyFacility,
getInventorySummary,
} from "../../Redux/actions";
import * as Notification from "../../Utils/Notifications.js";
import Page from "../Common/components/Page";
import { FieldLabel } from "../Form/FormFields/FormField";
import { SelectFormField } from "../Form/FormFields/SelectFormField";
import TextFormField from "../Form/FormFields/TextFormField";
import { InventoryItemsModel } from "./models";
import { Cancel, Submit } from "../Common/components/ButtonV2";
import useAppHistory from "../../Common/hooks/useAppHistory";
import useQuery from "../../Utils/request/useQuery";
import routes from "../../Redux/api";
import request from "../../Utils/request/request";

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

Expand Down Expand Up @@ -59,77 +53,41 @@ export const AddInventoryForm = (props: any) => {
const { goBack } = useAppHistory();
const [state, dispatch] = useReducer(inventoryFormReducer, initialState);
const { facilityId } = props;
const dispatchAction: any = useDispatch();
const [isLoading, setIsLoading] = useState(false);
const [offset, _setOffset] = useState(0);
const [stockError, setStockError] = useState("");
const [inventory, setInventory] = useState<any>([]);
const [data, setData] = useState<Array<InventoryItemsModel>>([]);
const [currentUnit, setCurrentUnit] = useState<any>();
const [facilityName, setFacilityName] = useState("");

const limit = 14;

const fetchData = useCallback(
async (status: statusType) => {
setIsLoading(true);
const res = await dispatchAction(getItems({ limit, offset }));
if (!status.aborted) {
if (res && res.data) {
setData(res.data.results);
}
setIsLoading(false);
}
},
[dispatchAction, offset]
);
useAbortableEffect(
(status: statusType) => {
fetchData(status);
const { data } = useQuery(routes.getItems, {
query: {
limit,
offset,
},
[fetchData]
);
});

const fetchInventoryData = useCallback(
async (status: statusType) => {
setIsLoading(true);
const res = await dispatchAction(
getInventorySummary(facilityId, { limit, offset })
);
if (!status.aborted) {
if (res && res.data) {
setInventory(res.data.results);
}
setIsLoading(false);
}
const { data: inventory } = useQuery(routes.getInventorySummary, {
pathParams: {
facility_external_id: facilityId,
},
[dispatchAction, facilityId]
);

useAbortableEffect(
(status: statusType) => {
fetchInventoryData(status);
query: {
limit,
offset,
},
[fetchInventoryData]
);
prefetch: facilityId !== undefined,
});

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

setFacilityName(res?.data?.name || "");
} else {
setFacilityName("");
}
}

fetchFacilityName();
}, [dispatchAction, facilityId]);
const { data: facilityObject } = useQuery(routes.getAnyFacility, {
pathParams: { id: facilityId },
prefetch: !!facilityId,
});

useEffect(() => {
// set the default units according to the item
const item = data.find((item) => item.id === Number(state.form.id));
const item = data?.results.find(
(item) => item.id === Number(state.form.id)
);
if (item) {
dispatch({
type: "set_form",
Expand All @@ -140,7 +98,9 @@ export const AddInventoryForm = (props: any) => {
}, [state.form.id]);

const defaultUnitConverter = (unitData: any) => {
const unitName = data[Number(unitData.item - 1)].allowed_units?.filter(
const unitName = data?.results[
Number(unitData.item - 1)
].allowed_units?.filter(
(u: any) => Number(u.id) === Number(unitData.unit)
)[0].name;
if (unitName === "Dozen") {
Expand All @@ -155,9 +115,9 @@ export const AddInventoryForm = (props: any) => {
// this function determines whether the stock which user has demanded to use is available or not !

const stockValidation = (data: any) => {
if (inventory && inventory.length) {
if (inventory && inventory.results.length) {
// get the stock cont of item selected
const stockBefore = inventory.filter(
const stockBefore = inventory.results.filter(
(inventoryItem: any) =>
Number(inventoryItem.item_object.id) === Number(data.item)
);
Expand All @@ -177,7 +137,7 @@ export const AddInventoryForm = (props: any) => {
}
setStockError("");
return true;
} else if (inventory && inventory.length === 0) {
} else if (inventory && inventory.results.length === 0) {
setStockError("No Stock Available !");
setIsLoading(false);
return false;
Expand Down Expand Up @@ -243,17 +203,19 @@ export const AddInventoryForm = (props: any) => {
data.quantity = data.quantity / 1000;
data.unit = 6;
}
const res = await dispatchAction(postInventory(data, { facilityId }));
await request(routes.createInventory, {
body: data,
pathParams: { facilityId },
onResponse: ({ res, data }) => {
if (res?.ok && data) {
Notification.Success({
msg: "Inventory created successfully",
});
goBack();
}
},
});
setIsLoading(false);

if (res && res.data && (res.status === 200 || res.status === 201)) {
Notification.Success({
msg: "Inventory created successfully",
});
goBack();
} else {
setIsLoading(false);
}
} else {
setIsLoading(false);
}
Expand All @@ -273,7 +235,9 @@ export const AddInventoryForm = (props: any) => {
<Page
title={"Manage Inventory"}
backUrl={`/facility/${facilityId}/inventory`}
crumbsReplacements={{ [facilityId]: { name: facilityName } }}
crumbsReplacements={{
[facilityId]: { name: facilityObject ? facilityObject.name : "" },
}}
>
<div className="mt-4">
<Card>
Expand All @@ -287,7 +251,7 @@ export const AddInventoryForm = (props: any) => {
name="id"
onChange={handleChange}
value={state.form.id}
options={data.map((e) => {
options={(data?.results ?? []).map((e) => {
return { id: e.id, name: e.name };
})}
optionValue={(inventory) => inventory.id}
Expand Down
75 changes: 23 additions & 52 deletions src/Components/Facility/InventoryList.tsx
Original file line number Diff line number Diff line change
@@ -1,65 +1,36 @@
import { useState, useCallback, useEffect, lazy } from "react";

import { useState, lazy } from "react";
import { navigate } from "raviger";
import { useDispatch } from "react-redux";
import { statusType, useAbortableEffect } from "../../Common/utils";
import { getInventorySummary, getAnyFacility } from "../../Redux/actions";
import Pagination from "../Common/Pagination";
import { classNames } from "../../Utils/utils";
import Page from "../Common/components/Page";
import ButtonV2 from "../Common/components/ButtonV2";
import { NonReadOnlyUsers } from "../../Utils/AuthorizeFor";
import useQuery from "../../Utils/request/useQuery";
import routes from "../../Redux/api";
const Loading = lazy(() => import("../Common/Loading"));

export default function InventoryList(props: any) {
const { facilityId }: any = props;
const dispatchAction: any = useDispatch();
const [isLoading, setIsLoading] = useState(false);
const initialInventory: any[] = [];
let inventoryItem: any = null;
const [inventory, setInventory] = useState(initialInventory);
const [offset, setOffset] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const [totalCount, setTotalCount] = useState(0);
const [facilityName, setFacilityName] = useState("");
const limit = 14;

const fetchData = useCallback(
async (status: statusType) => {
setIsLoading(true);
const res = await dispatchAction(
getInventorySummary(facilityId, { limit, offset })
);
if (!status.aborted) {
if (res?.data) {
setInventory(res.data.results);
setTotalCount(res.data.count);
}
setIsLoading(false);
}
const { data: inventoryData } = useQuery(routes.getInventorySummary, {
pathParams: {
facility_external_id: facilityId,
},
[dispatchAction, offset, facilityId]
);

useAbortableEffect(
(status: statusType) => {
fetchData(status);
query: {
limit,
offset,
},
[fetchData]
);

useEffect(() => {
async function fetchFacilityName() {
if (facilityId) {
const res = await dispatchAction(getAnyFacility(facilityId));
prefetch: facilityId !== undefined,
});

setFacilityName(res?.data?.name || "");
} else {
setFacilityName("");
}
}
fetchFacilityName();
}, [dispatchAction, facilityId]);
const { data: facilityObject } = useQuery(routes.getAnyFacility, {
pathParams: { id: facilityId },
prefetch: !!facilityId,
});

const handlePagination = (page: number, limit: number) => {
const offset = (page - 1) * limit;
Expand All @@ -68,8 +39,8 @@ export default function InventoryList(props: any) {
};

let inventoryList: any = [];
if (inventory?.length) {
inventoryList = inventory.map((inventoryItem: any) => (
if (inventoryData?.results.length) {
inventoryList = inventoryData.results.map((inventoryItem: any) => (
<tr
id={`${inventoryItem.item_object?.name.replaceAll(" ", "-")}`}
key={inventoryItem.id}
Expand Down Expand Up @@ -101,7 +72,7 @@ export default function InventoryList(props: any) {
</td>
</tr>
));
} else if (inventory && inventory.length === 0) {
} else if (inventoryData?.results && inventoryData.results.length === 0) {
inventoryList = (
<tr className="bg-white">
<td colSpan={3} className="border-b border-gray-200 p-5 text-center">
Expand All @@ -113,9 +84,9 @@ export default function InventoryList(props: any) {
);
}

if (isLoading || !inventory) {
if (!inventoryData?.results) {
inventoryItem = <Loading />;
} else if (inventory) {
} else if (inventoryData.results) {
inventoryItem = (
<>
<div className="-mx-4 overflow-x-auto p-4 sm:-mx-8 sm:px-8">
Expand All @@ -135,12 +106,12 @@ export default function InventoryList(props: any) {
</table>
</div>
</div>
{totalCount > limit && (
{inventoryData?.count > limit && (
<div className="mt-4 flex w-full justify-center">
<Pagination
cPage={currentPage}
defaultPerPage={limit}
data={{ totalCount }}
data={{ totalCount: inventoryData ? inventoryData.count : 0 }}
onChange={handlePagination}
/>
</div>
Expand All @@ -153,7 +124,7 @@ export default function InventoryList(props: any) {
<Page
title="Inventory Manager"
className="mx-3 md:mx-8"
crumbsReplacements={{ [facilityId]: { name: facilityName } }}
crumbsReplacements={{ [facilityId]: { name: facilityObject?.name } }}
backUrl={`/facility/${facilityId}`}
>
<div className="container mx-auto px-4 sm:px-8">
Expand Down
Loading

0 comments on commit 9d2f678

Please sign in to comment.