From 6e24881573e14fb393265255589e5c408d74c406 Mon Sep 17 00:00:00 2001 From: rahul_g Date: Mon, 29 Jul 2024 14:58:33 +0530 Subject: [PATCH] Integrated show district api and no found data added in ka-table, added in utils --- src/components/KaTableComponent.tsx | 13 ++- src/pages/district.tsx | 153 ++++++++++++++++------------ src/pages/state.tsx | 43 ++++---- src/services/MasterDataService.ts | 56 +++++++--- src/utils/formatLabel.ts | 10 ++ 5 files changed, 170 insertions(+), 105 deletions(-) create mode 100644 src/utils/formatLabel.ts diff --git a/src/components/KaTableComponent.tsx b/src/components/KaTableComponent.tsx index 70adefc2..9535a68e 100644 --- a/src/components/KaTableComponent.tsx +++ b/src/components/KaTableComponent.tsx @@ -28,6 +28,7 @@ interface KaTableComponentProps { }[]; paginationEnable?: boolean; showIcons?: boolean; + noData?: boolean; } const KaTableComponent: React.FC = ({ @@ -43,6 +44,7 @@ const KaTableComponent: React.FC = ({ onDelete, showIcons, pageSizes, + noData, }) => { const [selectedRowIds, setSelectedRowIds] = useState([]); @@ -68,7 +70,7 @@ const KaTableComponent: React.FC = ({ {...tableProps} paging={{ enabled: paginationEnable, - pageIndex: 0, + pageIndex: offset, pageSize: limit, pageSizes: pageSizes, position: PagingPosition.Bottom, @@ -94,10 +96,8 @@ const KaTableComponent: React.FC = ({ if (props.column.key === "selection-cell") { return ( - handleCheckboxChange(props.rowData.userId) - } + checked={selectedRowIds.includes(props.rowData.id)} + onChange={() => handleCheckboxChange(props.rowData.id)} /> ); } @@ -110,6 +110,9 @@ const KaTableComponent: React.FC = ({ }, }, }} + noData={{ + text: "No Data Found", + }} /> diff --git a/src/pages/district.tsx b/src/pages/district.tsx index 4d905fa5..fbd020f7 100644 --- a/src/pages/district.tsx +++ b/src/pages/district.tsx @@ -10,13 +10,13 @@ import MenuItem from "@mui/material/MenuItem"; import Select, { SelectChangeEvent } from "@mui/material/Select"; import PageSizeSelector from "@/components/PageSelector"; import { useTranslation } from "next-i18next"; -import { getDistrictList, getStateBlockDistrictList } from "@/services/MasterDataService"; -import Image from "next/image"; -import glass from "../../public/images/empty_hourglass.svg"; import CustomModal from "@/components/CustomModal"; -import ConfirmationModal from "@/components/ConfirmationModal"; -import { Typography } from "@mui/material"; import { SortDirection, DataType } from "ka-table/enums"; +import { + getStateBlockDistrictList, + getDistrictsForState, +} from "@/services/MasterDataService"; +import formatLabel from "@/utils/formatLabel"; type StateDetail = { value: string; @@ -24,13 +24,13 @@ type StateDetail = { }; type DistrictDetail = { + value: string; label: string; }; const District: React.FC = () => { const { t } = useTranslation(); const [selectedState, setSelectedState] = useState(""); - const [selectedDistrict, setSelectedDistrict] = useState("-"); const [selectedSort, setSelectedSort] = useState("Sort"); const [pageOffset, setPageOffset] = useState(0); const [pageLimit, setPageLimit] = useState(10); @@ -46,6 +46,8 @@ const District: React.FC = () => { const [selectedDistrictForDelete, setSelectedDistrictForDelete] = useState(null); + const [selectedDistrict, setSelectedDistrict] = useState(""); + const columns = useMemo( () => [ { @@ -91,10 +93,14 @@ const District: React.FC = () => { async (event: SelectChangeEvent) => { const selectedState = event.target.value; setSelectedState(selectedState); + try { - const data = await getDistrictList(selectedState); + const data = await getDistrictsForState({ + controllingfieldfk: selectedState, + fieldName: "districts", + }); setDistrictData(data.result || []); - setSelectedDistrict(data.result[0]?.label || "-"); + setSelectedDistrict("-"); } catch (error) { console.error("Error fetching district data", error); } @@ -122,44 +128,53 @@ const District: React.FC = () => { setConfirmationModalOpen(false); }, [selectedDistrictForDelete]); - const handleFilterChange = useCallback( - async (event: SelectChangeEvent) => { - console.log(event.target.value); - setSelectedFilter(event.target.value); - }, - [] - ); + const handleFilterChange = useCallback((event: SelectChangeEvent) => { + console.log(event.target.value); + setSelectedFilter(event.target.value); + }, []); useEffect(() => { const fetchStateData = async () => { try { - const object= - { - - "controllingfieldfk": selectedState, - - "fieldName": "districts" - - } - const data = await getStateBlockDistrictList(object); - setStateData(data.result || []); - const initialSelectedState = data.result[0]?.value || ""; - setSelectedState(initialSelectedState); - const districtData = await getDistrictList(initialSelectedState); - setDistrictData(districtData.result || []); - setSelectedDistrict(districtData.result[0]?.label || "-"); + const data = await getStateBlockDistrictList({ fieldName: "states" }); + if (data?.result) { + setStateData(data.result); + const initialSelectedState = data.result[0]?.value || ""; + setSelectedState(initialSelectedState); + + const initialDistrictData = await getDistrictsForState({ + controllingfieldfk: initialSelectedState, + fieldName: "districts", + }); + if (initialDistrictData?.result) { + setDistrictData(initialDistrictData.result); + } else { + console.error( + "No initial district data returned:", + initialDistrictData + ); + setDistrictData([]); + } + } else { + console.error("No state data returned:", data); + setStateData([]); + } } catch (error) { console.error("Error fetching state data", error); + setStateData([]); } }; fetchStateData(); }, []); - const handleSearch = (keyword: string) => {}; - useEffect(() => { const sortAndPaginateData = () => { + if (districtData.length === 0) { + setSortedDistricts([]); + setPageCount(1); + return; + } const sorted = [...districtData].sort((a, b) => sortDirection === "asc" ? a.label.localeCompare(b.label) @@ -170,7 +185,7 @@ const District: React.FC = () => { (pageOffset + 1) * pageLimit ); setSortedDistricts(paginatedData); - setPageCount(Math.ceil(districtData.length / pageLimit)); + setPageCount(Math.ceil(sorted.length / pageLimit)); }; sortAndPaginateData(); @@ -182,16 +197,17 @@ const District: React.FC = () => { selectedSort, handleStateChange, handleSortChange, - states: stateData.map((state) => state.label) || [], + states: stateData.map((state) => state.value) || [], districts: districtData.map((district) => district.label) || [], selectedState, - selectedDistrict, showStateDropdown: false, selectedFilter, handleFilterChange, - handleSearch, + handleSearch: () => {}, }; + const showPagination = sortedDistricts.length > 10; + return ( { {t("COMMON.ARE_YOU_SURE_DELETE")} - {districtData.length > 0 ? ( - ({ - label: - districtDetail.label - ?.toLocaleLowerCase() - .charAt(0) - .toUpperCase() + - districtDetail.label?.toLocaleLowerCase().slice(1), - actions: "Action buttons", - }))} - limit={pageLimit} - offset={pageOffset} - PagesSelector={() => ( + + + {t("MASTER.STATE")} + + + + ({ + label: formatLabel(districtDetail.label), + actions: "Action buttons", + }))} + limit={pageLimit} + offset={pageOffset} + PagesSelector={() => + showPagination && ( - )} - PageSizeSelector={PageSizeSelectorFunction} - extraActions={[]} - onEdit={handleEdit} - onDelete={handleDelete} - /> - ) : ( - - - - {t("COMMON.NO_DATA_FOUND")} - - - )} + ) + } + PageSizeSelector={PageSizeSelectorFunction} + extraActions={[]} + onEdit={handleEdit} + onDelete={handleDelete} + noData={!!(sortedDistricts.length === 0 ? "No Data Found" : "")} + /> ); diff --git a/src/pages/state.tsx b/src/pages/state.tsx index cc7dcfcc..4efeb379 100644 --- a/src/pages/state.tsx +++ b/src/pages/state.tsx @@ -27,16 +27,20 @@ const State: React.FC = () => { const [pageLimit, setPageLimit] = useState(10); const [stateData, setStateData] = useState([]); const [selectedSort, setSelectedSort] = useState("Sort"); - const [sortBy, setSortBy] = useState<["label", "asc" | "desc"]>(["label", "asc"]); + const [sortBy, setSortBy] = useState<["label", "asc" | "desc"]>([ + "label", + "asc", + ]); const [pageCount, setPageCount] = useState(1); const [pageSize, setPageSize] = useState(10); const [selectedFilter, setSelectedFilter] = useState("All"); const [loading, setLoading] = useState(true); - + // Modal state const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [selectedState, setSelectedState] = useState(null); - const [confirmButtonDisable, setConfirmButtonDisable] = useState(false); + const [confirmButtonDisable, setConfirmButtonDisable] = + useState(false); const [selectedReason, setSelectedReason] = useState(""); const [otherReason, setOtherReason] = useState(""); @@ -110,14 +114,11 @@ const State: React.FC = () => { const fetchStateData = async () => { try { setLoading(true); - const object= - { - - "controllingfieldfk": selectedState, - - "fieldName": "districts" - - } + const object = { + controllingfieldfk: selectedState, + + fieldName: "districts", + }; const data = await getStateBlockDistrictList(object); const sortedData = [...data.result].sort((a, b) => { const [field, order] = sortBy; @@ -166,6 +167,8 @@ const State: React.FC = () => { ] ); + const showPagination = stateData.length > 10; + return (
@@ -181,14 +184,16 @@ const State: React.FC = () => { }))} limit={pageLimit} offset={pageOffset} - PagesSelector={() => ( - - )} + PagesSelector={() => + showPagination && ( + + ) + } PageSizeSelector={() => ( => { +export const getStateBlockDistrictList = async ({ + fieldName, +}: StateListParam): Promise => { const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/fields/options/read`; try { - const response = await post(apiUrl,{ - fieldName}); + const response = await post(apiUrl, { + fieldName, + }); return response?.data; } catch (error) { console.error("error in fetching user details", error); return error; } }; +// services/MasterDataService.ts +export const getDistrictsForState = async ({ + controllingfieldfk, + fieldName, +}: { + controllingfieldfk: string; + fieldName: string; +}): Promise => { + const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/fields/options/read`; + try { + const response = await post(apiUrl, { + controllingfieldfk, + fieldName, + }); + return response?.data; + } catch (error) { + console.error("Error fetching district data", error); + return error; + } +}; -export const getCenterList = async ( { - - filters, limit, offset}:CenterListParam,): Promise => { +export const getCenterList = async ({ + filters, + limit, + offset, +}: CenterListParam): Promise => { const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/cohort/search`; try { - const response = await post(apiUrl,{ - filters, limit, offset}); + const response = await post(apiUrl, { + filters, + limit, + offset, + }); return response?.data; } catch (error) { console.error("error in fetching user details", error); @@ -44,7 +68,7 @@ export const getCenterList = async ( { }; export const getDistrictList = async ( - state?: string | string[], + state?: string | string[] ): Promise => { let apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/fields/options/read/districts`; @@ -62,7 +86,7 @@ export const getDistrictList = async ( }; export const getBlockList = async ( - district?: string | string[], + district?: string | string[] ): Promise => { let apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/fields/options/read/blocks`; diff --git a/src/utils/formatLabel.ts b/src/utils/formatLabel.ts new file mode 100644 index 00000000..7e86a003 --- /dev/null +++ b/src/utils/formatLabel.ts @@ -0,0 +1,10 @@ +import React from "react"; + +const formatLabel = (label: string) => { + return label + .replace(/_/g, " ") + .toLowerCase() + .replace(/\b\w/g, (char) => char.toUpperCase()); +}; + +export default formatLabel;