From eff0fa8f110a1044ad1286686bfb2985cf0a5d43 Mon Sep 17 00:00:00 2001 From: Rahul Garud Date: Wed, 28 Aug 2024 19:11:37 +0530 Subject: [PATCH] integreation of create edit delete --- src/components/AddBlockModal.tsx | 111 +++++-- src/pages/block.tsx | 477 +++++++++++++++++++++---------- 2 files changed, 422 insertions(+), 166 deletions(-) diff --git a/src/components/AddBlockModal.tsx b/src/components/AddBlockModal.tsx index 249225c5..ba4703c4 100644 --- a/src/components/AddBlockModal.tsx +++ b/src/components/AddBlockModal.tsx @@ -15,6 +15,7 @@ import { import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined"; import { useTranslation } from "next-i18next"; import { getDistrictsForState } from "@/services/MasterDataService"; +import { getCohortList } from "@/services/CohortService/cohortService"; interface AddBlockModalProps { open: boolean; @@ -53,6 +54,11 @@ export const AddBlockModal: React.FC = ({ const [districts, setDistricts] = useState< { value: string; label: string }[] >([]); + + const [districtsOptionRead, setDistrictsOptionRead] = useState([]); + const [districtCodeArr, setDistrictCodeArr] = useState([]); + const [districtNameArr, setDistrictNameArr] = useState([]); + const { t } = useTranslation(); useEffect(() => { @@ -64,29 +70,92 @@ export const AddBlockModal: React.FC = ({ setErrors({}); }, [initialValues]); - useEffect(() => { - const fetchDistricts = async () => { - try { - const response = await getDistrictsForState({ fieldName: "districts" }); - if (response.result.values) { - setDistricts(response.result.values); - console.log("modal all districts", response.result.values); - } else { - console.error("Unexpected response format:", response); - setDistricts([]); - } - } catch (error: any) { - console.error("Error fetching districts:", error.message); - setDistricts([]); - } - }; + const fetchDistricts = async () => { + try { + const data = await getDistrictsForState({ + fieldName: "districts", + }); + + const districts = data?.result?.values || []; + setDistrictsOptionRead(districts); + + const districtNameArray = districts.map((item: any) => item.label); + setDistrictNameArr(districtNameArray); + + const districtCodeArray = districts.map((item: any) => item.value); + setDistrictCodeArr(districtCodeArray); + + // const districtFieldID = data?.result?.fieldId || ""; + // setDistrictFieldId(districtFieldID); + + console.log("districtNameArray", districtNameArray); + } catch (error) { + console.error("Error fetching districts", error); + } + }; + useEffect(() => { if (open) fetchDistricts(); }, [open, formData.controllingField]); + const getFilteredCohortData = async () => { + try { + const reqParams = { + limit: 0, + offset: 0, + filters: { + name: "", + states: "", + type: "DISTRICT", + }, + sort: ["name","asc"], + }; + + const response = await getCohortList(reqParams); + + const cohortDetails = response?.results?.cohortDetails || []; + + const filteredDistrictData = cohortDetails + .map( + (districtDetail: { + cohortId: any; + name: string; + createdAt: any; + updatedAt: any; + createdBy: any; + updatedBy: any; + }) => { + const transformedName = districtDetail.name; + + const matchingDistrict = districtsOptionRead.find( + (district: { label: string }) => + district.label === transformedName + ); + return { + label: transformedName, + value: matchingDistrict ? matchingDistrict.value : null, + createdAt: districtDetail.createdAt, + updatedAt: districtDetail.updatedAt, + createdBy: districtDetail.createdBy, + updatedBy: districtDetail.updatedBy, + cohortId: districtDetail?.cohortId, + }; + } + ) + .filter((district: { label: any }) => + districtNameArr.includes(district.label) + ); + + console.log("filteredDistrictData", filteredDistrictData); + + setDistricts(filteredDistrictData); + } catch (error) { + console.error("Error fetching and filtering cohort districts", error); + } + }; useEffect(() => { - console.log("Selected District:", formData.controllingField); - }, [formData.controllingField]); + getFilteredCohortData(); + }, []); const validateField = ( field: keyof typeof formData, @@ -214,10 +283,11 @@ export const AddBlockModal: React.FC = ({ variant="outlined" margin="dense" error={!!errors.controllingField} + disabled={isEditing} > {t("COMMON.SELECT_DISTRICT")} - {districts.length > 0 ? ( - districts.map((district) => ( + {districtsOptionRead.length > 0 ? ( + districtsOptionRead.map((district: any) => ( {district.label} @@ -252,6 +322,7 @@ export const AddBlockModal: React.FC = ({ onChange={handleChange("value")} error={!!errors.value} helperText={errors.value} + disabled={isEditing} /> diff --git a/src/pages/block.tsx b/src/pages/block.tsx index 15e75cfa..135aa6eb 100644 --- a/src/pages/block.tsx +++ b/src/pages/block.tsx @@ -17,21 +17,25 @@ import { getBlocksForDistricts, deleteOption, createOrUpdateOption, + updateCohort, } from "@/services/MasterDataService"; import { transformLabel } from "@/utils/Helper"; import { showToastMessage } from "@/components/Toastify"; import ConfirmationModal from "@/components/ConfirmationModal"; import { AddBlockModal } from "@/components/AddBlockModal"; import PageSizeSelector from "@/components/PageSelector"; -import { SORT, Storage } from "@/utils/app.constant"; +import { SORT, Status, Storage } from "@/utils/app.constant"; import { getUserDetailsInfo } from "@/services/UserList"; import { createCohort, getCohortList, } from "@/services/CohortService/cohortService"; import { Numbers } from "@/utils/app.constant"; +import { set } from "date-fns"; type StateDetail = { + name: string | undefined; + controllingField: string | undefined; block: string | undefined; selectedDistrict: string | undefined; value: string; @@ -44,6 +48,8 @@ type DistrictDetail = { }; type BlockDetail = { + status: Status; + cohortId(cohortId: any): unknown; updatedBy: any; createdBy: any; updatedAt: any; @@ -53,6 +59,11 @@ type BlockDetail = { block: string; }; +interface BlockOption { + label: string; + value: any; +} + const Block: React.FC = () => { const { t } = useTranslation(); const [selectedSort, setSelectedSort] = useState("Sort"); @@ -87,6 +98,16 @@ const Block: React.FC = () => { const [searchKeyword, setSearchKeyword] = useState(""); const [pagination, setPagination] = useState(true); const [cohortBlockDetails, setCohortBlockDetails] = useState([]); + const [blocksOptionRead, setBlocksOptionRead] = useState([]); + const [blockNameArr, setBlockNameArr] = useState([]); + const [blockCodeArr, setBlockCodeArr] = useState([]); + + const [districtsOptionRead, setDistrictsOptionRead] = useState([]); + const [districtCodeArr, setDistrictCodeArr] = useState([]); + const [districtNameArr, setDistrictNameArr] = useState([]); + const [cohortIdForDelete, setCohortIdForDelete] = useState(""); + const [cohortIdForEdit, setCohortIdForEdit] = useState(); + const [cohortIdOfDistrict, setCohortIdOfDistrict] = useState(); useEffect(() => { const fetchUserDetail = async () => { @@ -117,157 +138,218 @@ const Block: React.FC = () => { fetchUserDetail(); }, []); - useEffect(() => { - const fetchDistricts = async () => { - try { - const data = await getDistrictsForState({ - controllingfieldfk: stateCode || "", - fieldName: "districts", - }); - - const districts = data?.result?.values || []; - setDistrictData(districts); - - console.log("districts", districts); - - const districtFieldID = data?.result?.fieldId || ""; - setDistrictFieldId(districtFieldID); - - // Automatically select the first district if it exists - if (districts.length > 0) { - setSelectedDistrict(districts[0].value); - } - } catch (error) { - console.error("Error fetching districts", error); - } - }; - - fetchDistricts(); - }, [stateCode]); + const fetchDistricts = async () => { + try { + const data = await getDistrictsForState({ + controllingfieldfk: stateCode || "", + fieldName: "districts", + }); - const getCohortSearchDistrict = async () => { - const limit = pageLimit; - const offset = pageOffset * limit; - const reqParams = { - limit: limit, - offset: offset, - filters: { - name: searchKeyword, - states: stateCode, - type: "DISTRICT", - }, - sort: sortBy, - }; + const districts = data?.result?.values || []; + setDistrictsOptionRead(districts); - const response = await getCohortList(reqParams); + const districtNameArray = districts.map((item: any) => item.label); + setDistrictNameArr(districtNameArray); - const cohortDetails = response?.results?.cohortDetails; - console.log("cohortDetails", cohortDetails); + const districtCodeArray = districts.map((item: any) => item.value); + setDistrictCodeArr(districtCodeArray); - if (cohortDetails && cohortDetails.length > 0) { - const firstCohort = cohortDetails[0]; - const cohortID = firstCohort?.cohortId; - const cohortSTATUS = firstCohort?.status; + const districtFieldID = data?.result?.fieldId || ""; + setDistrictFieldId(districtFieldID); - setCohortId(cohortID); - setCohortStatus(cohortSTATUS); - } else { - console.error("No cohort details available."); + console.log("districtNameArray", districtNameArray); + } catch (error) { + console.error("Error fetching districts", error); } }; useEffect(() => { - getCohortSearchDistrict(); - }, [selectedDistrict]); - - const getCohortSearchBlock = async () => { - const limit = pageLimit; - const offset = pageOffset * limit; - const reqParams = { - limit: limit, - offset: offset, - filters: { - name: searchKeyword, - districts: selectedDistrict, - type: "BLOCK", - }, - sort: sortBy, - }; - - const response = await getCohortList(reqParams); - - const cohortDetails = response?.results?.cohortDetails; - console.log("cohortDetails", cohortDetails); - setCohortBlockDetails(cohortDetails); - - if (cohortDetails && cohortDetails.length > 0) { - const firstCohort = cohortDetails[0]; - const cohortID = firstCohort?.cohortId; - const cohortSTATUS = firstCohort?.status; - - setCohortId(cohortID); - setCohortStatus(cohortSTATUS); + fetchDistricts(); + }, [stateCode]); - const totalCount = response?.count || 0; - console.log("totalCount", totalCount); - setPaginationCount(totalCount); + const getFilteredCohortData = async () => { + try { + const reqParams = { + limit: 0, + offset: 0, + filters: { + name: searchKeyword, + states: stateCode, + type: "DISTRICT", + }, + sort: sortBy, + }; + + const response = await getCohortList(reqParams); + + const cohortDetails = response?.results?.cohortDetails || []; + + const filteredDistrictData = cohortDetails + .map( + (districtDetail: { + cohortId: any; + name: string; + createdAt: any; + updatedAt: any; + createdBy: any; + updatedBy: any; + }) => { + const transformedName = districtDetail.name; + + const matchingDistrict = districtsOptionRead.find( + (district: { label: string }) => + district.label === transformedName + ); + return { + label: transformedName, + value: matchingDistrict ? matchingDistrict.value : null, + createdAt: districtDetail.createdAt, + updatedAt: districtDetail.updatedAt, + createdBy: districtDetail.createdBy, + updatedBy: districtDetail.updatedBy, + cohortId: districtDetail?.cohortId, + }; + } + ) + .filter((district: { label: any }) => + districtNameArr.includes(district.label) + ); - setPagination(totalCount > 10); - setPageSizeArray( - totalCount > 15 - ? [5, 10, 15] - : totalCount > 10 - ? [5, 10] - : totalCount > 5 - ? [5] - : [] - ); + console.log("filteredDistrictData", filteredDistrictData); - setPageCount(Math.ceil(totalCount / limit)); - } else { - console.error("No cohort details available."); - setCohortBlockDetails([]); + setDistrictData(filteredDistrictData); + } catch (error) { + console.error("Error fetching and filtering cohort districts", error); + setLoading(false); } }; - useEffect(() => { - if (selectedDistrict) { - getCohortSearchBlock(); + if (stateCode) { + getFilteredCohortData(); } - }, [selectedDistrict, searchKeyword, sortBy, pageOffset, pageLimit]); + }, [searchKeyword, pageLimit, pageOffset, stateCode, sortBy]); - const fetchBlocks = async (DistrictId: string) => { - console.log("districtId", DistrictId); - setLoading(true); + const fetchBlocks = async () => { try { const response = await getBlocksForDistricts({ - limit: 0, - offset: 0, controllingfieldfk: selectedDistrict || "", fieldName: "blocks", }); + console.log("selectedDistrict block", selectedDistrict); + const blocks = response?.result?.values || []; + setBlocksOptionRead(blocks); + console.log("blocks", blocks); - console.log("block response", response); - setBlockData(response?.result?.values || []); + const blockNameArray = blocks.map((item: any) => item.label); + setBlockNameArr(blockNameArray); - const blockFieldID = response?.result?.fieldId || ""; + const blockCodeArray = blocks.map((item: any) => item.value); + setBlockCodeArr(blockCodeArray); - console.log("blockFieldID", blockFieldID); + const blockFieldID = response?.result?.fieldId || ""; setBlocksFieldId(blockFieldID); - - console.log("new blockFeldId", blocksFieldId); } catch (error) { console.error("Error fetching blocks", error); } finally { - setLoading(false); + } + }; + + useEffect(() => { + fetchBlocks(); + }, [selectedDistrict]); + + const getCohortSearchBlock = async (selectedDistrict: string) => { + try { + const reqParams = { + limit: 0, + offset: 0, + filters: { + name: searchKeyword, + states: stateCode, + districts: selectedDistrict, + type: "BLOCK", + }, + sort: sortBy, + }; + + const response = await getCohortList(reqParams); + const cohortDetails = response?.results?.cohortDetails || []; + + console.log("Cohort Details:", cohortDetails); + + const filteredBlockData = cohortDetails + .map( + (blockDetail: { + cohortId: any; + name: string; + code: string; + createdAt: any; + updatedAt: any; + createdBy: any; + updatedBy: any; + status: string; + }) => { + const transformedName = blockDetail.name; + console.log("Transformed Name:", transformedName); + + const matchingBlock = blocksOptionRead.find( + (block: BlockOption) => block.label === transformedName + ); + + console.log("Matching Block:", matchingBlock); + + return { + name: transformedName, + code: matchingBlock?.value ?? "", + status: blockDetail.status, + createdAt: blockDetail.createdAt, + updatedAt: blockDetail.updatedAt, + createdBy: blockDetail.createdBy, + updatedBy: blockDetail.updatedBy, + cohortId: blockDetail.cohortId, + }; + } + ) + .filter((block: { name: string }) => blockNameArr.includes(block.name)); + + console.log("Filtered Block Data:", filteredBlockData); + + setBlockData(filteredBlockData); + + + const totalCount = filteredBlockData.length; + setPaginationCount(totalCount); + setPageCount(Math.ceil(totalCount / pageLimit)); + } catch (error) { + console.error("Error fetching and filtering cohort blocks", error); } }; useEffect(() => { if (selectedDistrict) { - fetchBlocks(selectedDistrict); + getCohortSearchBlock(selectedDistrict); } - }, [selectedDistrict]); + }, [blockNameArr, searchKeyword, pageLimit, pageOffset, sortBy]); + + function transformLabels(label: string) { + if (!label || typeof label !== "string") return ""; + return label + .toLowerCase() + .replace(/_/g, " ") + .replace(/\b\w/g, (char) => char.toUpperCase()); + } + + const filteredCohortOptionData = () => { + const startIndex = pageOffset * pageLimit; + const endIndex = startIndex + pageLimit; + + const transformedData = blockData.map((item) => ({ + ...item, + label: transformLabels(item.label), + })); + + return transformedData.slice(startIndex, endIndex); + }; const columns = [ { @@ -335,26 +417,47 @@ const Block: React.FC = () => { const handleDistrictChange = async (event: SelectChangeEvent) => { const selectedDistrict = event.target.value; - setSelectedDistrict(selectedDistrict); + setSelectedDistrict(selectedDistrict); + + await getCohortSearchBlock(selectedDistrict); }; + useEffect(() => { + if (selectedDistrict) { + getCohortSearchBlock(selectedDistrict); + } + }, [ + blockNameArr, + searchKeyword, + pageLimit, + pageOffset, + sortBy, + selectedDistrict, + ]); + const handleEdit = (rowData: any) => { setModalOpen(true); - const updatedRowData = { - ...rowData, - selectedDistrict: selectedDistrict, + const cohortIdForEDIT = rowData.cohortId; + setCohortIdForEdit(cohortIdForEDIT); + + const initialValues: StateDetail = { + name: rowData.name || "", + value: rowData.code || "", + selectedDistrict: selectedDistrict || "", + controllingField: "", + block: "", + label: "", }; - - console.log("updatedRowData", updatedRowData); - - setSelectedStateForEdit(updatedRowData); + console.log("initialValues", initialValues); + setSelectedStateForEdit(initialValues); }; - const handleDelete = (rowData: BlockDetail) => { console.log("deleted data for row", rowData); setSelectedStateForDelete(rowData); setConfirmationDialogOpen(true); + setCohortIdForDelete(rowData.cohortId); }; + console.log("cohortIdForDelete", cohortIdForDelete); const handleSearch = (keyword: string) => { setSearchKeyword(keyword); @@ -375,6 +478,28 @@ const Block: React.FC = () => { showToastMessage(t("COMMON.BLOCK_DELETED_FAILURE"), "error"); } } + //delete cohort + if (cohortIdForDelete) { + let cohortDetails = { + status: Status.ARCHIVED, + }; + const resp = await updateCohort(cohortIdForDelete, cohortDetails); + if (resp?.responseCode === 200) { + const cohort = filteredCohortOptionData()?.find( + (item: any) => item.cohortId == cohortIdForDelete + ); + if (cohort) { + cohort.status = Status.ARCHIVED; + } + } else { + console.log("Cohort Not Archived"); + } + setCohortIdForDelete(""); + } else { + console.log("No Cohort Selected"); + setCohortIdForDelete(""); + } + setConfirmationDialogOpen(false); }; @@ -434,11 +559,13 @@ const Block: React.FC = () => { console.log("insdie add state clicked"); }; - const handleAddDistrictSubmit = async ( + //create cohort + const handleCreateCohortSubmit = async ( name: string, value: string, controllingField: string, - blocksFieldId: string + DistrictId?: string, + extraArgument?: any ) => { const newDistrict = { options: [ @@ -449,18 +576,14 @@ const Block: React.FC = () => { }, ], }; - console.log("Submitting newDistrict:", newDistrict); - try { const response = await createOrUpdateOption(blocksFieldId, newDistrict); - console.log("submit response district", response); - if (response) { - await fetchBlocks(blocksFieldId || ""); + await fetchBlocks(); } } catch (error) { - console.error("Error adding block:", error); + console.error("Error adding district:", error); } const queryParameters = { @@ -480,17 +603,65 @@ const Block: React.FC = () => { }, ], }; + try { + const cohortCreateResponse = await createCohort(queryParameters); + if (cohortCreateResponse) { + await getCohortSearchBlock(selectedDistrict); + filteredCohortOptionData(); + showToastMessage(t("COMMON.BLOCK_ADDED_SUCCESS"), "success"); + } else if (cohortCreateResponse.responseCode === 409) { + showToastMessage(t("COMMON.BLOCK_DUPLICATION_FAILURE"), "error"); + } + } catch (error) { + console.error("Error creating cohort:", error); + showToastMessage(t("COMMON.BLOCK_DUPLICATION_FAILURE"), "error"); + } + setModalOpen(false); + setSelectedStateForEdit(null); + }; - console.log("queryParameters block", queryParameters); + const handleUpdateCohortSubmit = async ( + name: string, + value: string, + controllingField: string, + DistrictId?: string, + extraArgument?: any + ) => { + const newDistrict = { + options: [ + { + controllingfieldfk: controllingField, + name, + value, + }, + ], + }; + console.log("newDistrict", newDistrict); + try { + const response = await createOrUpdateOption(blocksFieldId, newDistrict); - const cohortList = await createCohort(queryParameters); + if (response) { + await fetchBlocks(); + } + } catch (error) { + console.error("Error adding district:", error); + } - console.log("fetched cohorlist in block success", cohortList); + const queryParameters = { + name: name, + }; try { - if (cohortList) { + const cohortCreateResponse = await updateCohort( + cohortIdForEdit, + queryParameters + ); + if (cohortCreateResponse) { + await getCohortSearchBlock(selectedDistrict); + + filteredCohortOptionData(); showToastMessage(t("COMMON.BLOCK_UPDATED_SUCCESS"), "success"); - } else if (cohortList.responseCode === 409) { + } else if (cohortCreateResponse.responseCode === 409) { showToastMessage(t("COMMON.BLOCK_DUPLICATION_FAILURE"), "error"); } } catch (error) { @@ -506,21 +677,35 @@ const Block: React.FC = () => { setModalOpen(false)} - onSubmit={(name: string, value: string, controllingField: string) => - handleAddDistrictSubmit(name, value, controllingField, blocksFieldId) - } + onSubmit={(name: string, value: string, controllingField: string) => { + if (selectedStateForEdit) { + handleUpdateCohortSubmit( + name, + value, + controllingField, + blocksFieldId, + selectedStateForEdit.value + ); + } else { + handleCreateCohortSubmit( + name, + value, + controllingField, + blocksFieldId + ); + } + }} fieldId={blocksFieldId} initialValues={ selectedStateForEdit ? { controllingField: selectedStateForEdit.selectedDistrict, - name: selectedStateForEdit.block, + name: selectedStateForEdit.name, value: selectedStateForEdit.value, } : {} } /> - { key={districtDetail.value} value={districtDetail.value} > - {transformLabel(districtDetail.label)} + {transformLabels(districtDetail.label)} ))} @@ -631,7 +816,7 @@ const Block: React.FC = () => { ) : blockData.length > 0 ? ( = Numbers.FIVE}