diff --git a/src/components/AddBlockModal.tsx b/src/components/AddBlockModal.tsx index fd3af937..8c321d77 100644 --- a/src/components/AddBlockModal.tsx +++ b/src/components/AddBlockModal.tsx @@ -111,7 +111,7 @@ export const AddBlockModal: React.FC = ({ const districts = data?.result?.values || []; setDistrictsOptionRead(districts); - const districtNameArray = districts.map((item: any) => item.label); + const districtNameArray = districts.map((item: any) => item?.label?.toLowerCase()); setDistrictNameArr(districtNameArray); const districtCodeArray = districts.map((item: any) => item.value); @@ -162,7 +162,7 @@ export const AddBlockModal: React.FC = ({ const matchingDistrict = districtsOptionRead.find( (district: { label: string }) => - district.label === transformedName + district?.label?.toLowerCase() === transformedName?.toLowerCase() ); return { label: transformedName, @@ -176,7 +176,7 @@ export const AddBlockModal: React.FC = ({ } ) .filter((district: { label: any }) => - districtNameArr.includes(district.label) + districtNameArr.includes(district?.label?.toLowerCase()) ); setDistricts(filteredDistrictData); } catch (error) { diff --git a/src/components/HeaderComponent.tsx b/src/components/HeaderComponent.tsx index 031eb31f..97a78df7 100644 --- a/src/components/HeaderComponent.tsx +++ b/src/components/HeaderComponent.tsx @@ -1,4 +1,8 @@ import SearchBar from "@/components/layouts/header/SearchBar"; +import { formatedBlocks, formatedDistricts } from "@/services/formatedCohorts"; +import { QueryKeys, Role, Status, TelemetryEventType } from "@/utils/app.constant"; +import { telemetryFactory } from "@/utils/telemetry"; +import useSubmittedButtonStore from "@/utils/useSharedState"; import AddIcon from "@mui/icons-material/Add"; import { Box, @@ -6,29 +10,22 @@ import { FormControl, MenuItem, Typography, - useMediaQuery, - Divider, + useMediaQuery } from "@mui/material"; import Select from "@mui/material/Select"; import { useTheme } from "@mui/material/styles"; +import Tab from "@mui/material/Tab"; +import Tabs from "@mui/material/Tabs"; +import { useQueryClient } from "@tanstack/react-query"; import { useTranslation } from "next-i18next"; +import { useRouter } from "next/router"; import { useEffect, useState } from "react"; -import { QueryKeys, Role, Status, TelemetryEventType } from "@/utils/app.constant"; -import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord"; import { getCenterList, getStateBlockDistrictList, } from "../services/MasterDataService"; -import AreaSelection from "./AreaSelection"; import { transformArray } from "../utils/Helper"; -import Tab from "@mui/material/Tab"; -import Tabs from "@mui/material/Tabs"; -import { useQueryClient } from "@tanstack/react-query"; -import { formatedBlocks, formatedDistricts } from "@/services/formatedCohorts"; -import { useRouter } from "next/router"; -import useSubmittedButtonStore from "@/utils/useSharedState"; -import { userAgent } from "next/server"; -import { telemetryFactory } from "@/utils/telemetry"; +import AreaSelection from "./AreaSelection"; interface State { value: string; @@ -103,7 +100,7 @@ const HeaderComponent = ({ const [initialized, setInitialized] = useState(false); const isArchived = useSubmittedButtonStore( (state: any) => state.isArchived -); + ); const [blocks, setBlocks] = useState([]); const selectedBlockStore = useSubmittedButtonStore( @@ -195,23 +192,23 @@ const HeaderComponent = ({ handleDistrictChange(selected, selectedCodes); const windowUrl = window.location.pathname; - const cleanedUrl = windowUrl.replace(/^\//, ''); - const env = cleanedUrl.split("/")[0]; + const cleanedUrl = windowUrl.replace(/^\//, ''); + const env = cleanedUrl.split("/")[0]; - const telemetryInteract = { - context: { - env: env, - cdata: [], - }, - edata: { - id: 'filter-by-district:'+selected[0], - type: TelemetryEventType.CLICK, - subtype: '', - pageid: cleanedUrl, - }, - }; - telemetryFactory.interact(telemetryInteract); + const telemetryInteract = { + context: { + env: env, + cdata: [], + }, + edata: { + id: 'filter-by-district:' + selected[0], + type: TelemetryEventType.CLICK, + subtype: '', + pageid: cleanedUrl, + }, + }; + telemetryFactory.interact(telemetryInteract); }; @@ -268,7 +265,7 @@ const HeaderComponent = ({ cdata: [], }, edata: { - id: 'filter-by-block:'+selected[0], + id: 'filter-by-block:' + selected[0], type: TelemetryEventType.CLICK, subtype: '', pageid: cleanedUrl, @@ -292,7 +289,7 @@ const HeaderComponent = ({ cdata: [], }, edata: { - id: 'filter-by-center:'+selected[0], + id: 'filter-by-center:' + selected[0], type: TelemetryEventType.CLICK, subtype: '', pageid: cleanedUrl, @@ -370,24 +367,22 @@ const HeaderComponent = ({ districtResult[0]?.label ); setSelectedDistrictStore(districtResult[0]?.label); - blockResult = await formatedBlocks( + blockResult = await formatedBlocks( districtResult[0]?.value ); console.log(blockResult) - if(blockResult?.message ==="Request failed with status code 404") - { - setBlocks([]); - } - else - { - setBlocks(blockResult); + if (blockResult?.message === "Request failed with status code 404") { + setBlocks([]); + } + else { + setBlocks(blockResult); - } + } } - - if (!hasBlock && !hasDistrict && userType!==Role.CONTENT_CREATOR) { - if (userType === Role.TEAM_LEADERS || userType==="Centers") { - // setSelectedBlock([t("COMMON.ALL_BLOCKS")]); + + if (!hasBlock && !hasDistrict && userType !== Role.CONTENT_CREATOR) { + if (userType === Role.TEAM_LEADERS || userType === "Centers") { + // setSelectedBlock([t("COMMON.ALL_BLOCKS")]); //setSelectedBlockCode("") router.replace({ pathname: router.pathname, @@ -399,18 +394,17 @@ const HeaderComponent = ({ }); } else { console.log(blockResult) - if(blockResult?.message==="Request failed with status code 404") - { + if (blockResult?.message === "Request failed with status code 404") { setBlocks([]); } - else{ + else { setSelectedBlock([blockResult[0]?.label]); setSelectedBlockCode(blockResult[0]?.value); localStorage.setItem("selectedBlock", blockResult[0]?.label); setSelectedBlockStore(blockResult[0]?.label); - + } - + router.replace({ pathname: router.pathname, query: { @@ -422,14 +416,13 @@ const HeaderComponent = ({ }); } } - else if(userType===Role.CONTENT_CREATOR) - { + else if (userType === Role.CONTENT_CREATOR) { router.replace({ pathname: router.pathname, query: { ...router.query, state: stateField.code, - + }, }); } @@ -542,42 +535,40 @@ const HeaderComponent = ({ // }, [blocks, selectedBlock, handleBlockChangeWrapper]); useEffect(() => { - const handleRouteparam = async() => - { + const handleRouteparam = async () => { const { state, district, block, center } = router.query; if (state) { setSelectedStateCode(state.toString()); } - console.log(district?.toString()) + console.log(district?.toString()) if (district) { setSelectedDistrictCode(district.toString()); // setSelectedDistrict([selectedDistrictStore]) setSelectedDistrict([localStorage.getItem("selectedDistrict")]); if (!localStorage.getItem("selectedDistrict")) { setSelectedDistrict([selectedDistrictStore]); - + } - try{ - const blockResult = await formatedBlocks( + try { + const blockResult = await formatedBlocks( district?.toString() - ); - console.log(blockResult.message) - if(blockResult.message==="Request failed with status code 404") - { - setBlocks([]); + ); + console.log(blockResult.message) + if (blockResult.message === "Request failed with status code 404") { + setBlocks([]); - } - else + } + else setBlocks(blockResult); } - catch{ - // console.log("hii") + catch { + // console.log("hii") } - + } - - if (block ) { + + if (block) { setSelectedBlockCode(block.toString()); console.log(selectedBlockCode); // setSelectedBlock([selectedBlockStore]) @@ -585,7 +576,7 @@ const HeaderComponent = ({ if (!localStorage.getItem("selectedBlock")) setSelectedBlock([selectedBlockStore]); } - + if (center) { console.log(center); @@ -596,7 +587,7 @@ const HeaderComponent = ({ if (!localStorage.getItem("selectedCenter")) setSelectedCenter([selectedCenterStore]); } - + // setInitialized(true) } handleRouteparam(); @@ -619,7 +610,7 @@ const HeaderComponent = ({ )} - {showStateDropdown && ( + {showStateDropdown && ( - {showAddNew && !isArchived && ( + {showAddNew && !isArchived && ( {/* {showAddNew && ( */} - - {showSort && ( - - - - )} - + + {showSort && ( + + + + )} + {/* )} */} {children} diff --git a/src/pages/block.tsx b/src/pages/block.tsx index 35d3d5c2..3b196f10 100644 --- a/src/pages/block.tsx +++ b/src/pages/block.tsx @@ -130,10 +130,10 @@ const Block: React.FC = () => { const queryClient = useQueryClient(); const isArchived = useSubmittedButtonStore( (state: any) => state.isArchived -); -const setIsArchived = useSubmittedButtonStore( -(state: any) => state.setIsArchived -); + ); + const setIsArchived = useSubmittedButtonStore( + (state: any) => state.setIsArchived + ); const [filters, setFilters] = useState({ name: searchKeyword, states: stateCode, @@ -231,7 +231,7 @@ const setIsArchived = useSubmittedButtonStore( // queryFn: () => getCohortList(reqParams), // }); - const response= await getCohortList(reqParams) + const response = await getCohortList(reqParams) const cohortDetails = response?.results?.cohortDetails || []; const filteredDistrictData = cohortDetails @@ -248,7 +248,7 @@ const setIsArchived = useSubmittedButtonStore( const matchingDistrict = districtsOptionRead.find( (district: { label: string }) => - district.label === transformedName + district?.label?.toLowerCase() === transformedName?.toLowerCase() ); return { label: transformedName, @@ -264,8 +264,7 @@ const setIsArchived = useSubmittedButtonStore( .filter((district: { label: any }) => districtNameArr.includes(district.label?.toLowerCase()) ); - if (isFirstVisit) - { + if (isFirstVisit) { if ( filteredDistrictData.length > 0 && selectedDistrict !== t("COMMON.ALL") @@ -290,10 +289,9 @@ const setIsArchived = useSubmittedButtonStore( useEffect(() => { - if(districtData[0]?.value && isFirstVisit) - { + if (districtData[0]?.value && isFirstVisit) { setSelectedDistrict(districtData[0]?.value); - setIsFirstVisit(false); + setIsFirstVisit(false); } }, [districtData]); @@ -314,7 +312,7 @@ const setIsArchived = useSubmittedButtonStore( // }); - const response=await getBlocksForDistricts({ + const response = await getBlocksForDistricts({ controllingfieldfk: selectedDistrict === t("COMMON.ALL") ? "" : selectedDistrict, fieldName: "blocks", @@ -377,7 +375,7 @@ const setIsArchived = useSubmittedButtonStore( // ], // queryFn: () => getCohortList(reqParams), // }); - const response= await getCohortList(reqParams) + const response = await getCohortList(reqParams) const cohortDetails = response?.results?.cohortDetails || []; @@ -422,7 +420,7 @@ const setIsArchived = useSubmittedButtonStore( setPaginationCount(totalCount); setPageCount(Math.ceil(totalCount / pageLimit)); - setLoading(false); + setLoading(false); } catch (error) { console.error("Error fetching and filtering cohort blocks", error); setLoading(false); @@ -507,7 +505,7 @@ const setIsArchived = useSubmittedButtonStore( cdata: [], }, edata: { - id: 'sort-by:'+event.target?.value, + id: 'sort-by:' + event.target?.value, type: TelemetryEventType.CLICK, subtype: '', pageid: cleanedUrl, @@ -552,7 +550,7 @@ const setIsArchived = useSubmittedButtonStore( cdata: [], }, edata: { - id: 'filter-by-district:'+event.target.value, + id: 'filter-by-district:' + event.target.value, type: TelemetryEventType.CLICK, subtype: '', pageid: cleanedUrl, @@ -660,7 +658,7 @@ const setIsArchived = useSubmittedButtonStore( cdata: [], }, edata: { - id: 'changed-tab-to:'+newValue, + id: 'changed-tab-to:' + newValue, type: TelemetryEventType.CLICK, subtype: '', pageid: cleanedUrl, @@ -748,7 +746,7 @@ const setIsArchived = useSubmittedButtonStore( cdata: [], }, edata: { - id: 'change-page-number:'+value, + id: 'change-page-number:' + value, type: TelemetryEventType.CLICK, subtype: '', pageid: cleanedUrl, @@ -815,7 +813,7 @@ const setIsArchived = useSubmittedButtonStore( extraArgument?: any ) => { const newDistrict = { - isCreate:true, + isCreate: true, options: [ { controllingfieldfk: controllingField, @@ -841,14 +839,14 @@ const setIsArchived = useSubmittedButtonStore( fieldId: stateFieldId, // state fieldId value: [stateCode], // state code }, - + { fieldId: districtFieldId, // district fieldId value: [controllingField], // district code }, ], }; - + try { const cohortCreateResponse = await createCohort(queryParameters); if (cohortCreateResponse) { @@ -865,7 +863,7 @@ const setIsArchived = useSubmittedButtonStore( console.error("Error adding district:", error); } - + setModalOpen(false); setSelectedStateForEdit(null); }; @@ -877,77 +875,76 @@ const setIsArchived = useSubmittedButtonStore( DistrictId?: string, extraArgument?: any ) => { - const updatedBy=localStorage.getItem("userId") -if(updatedBy) -{ - const newDistrict = { - isCreate:false, - options: [ - { - controllingfieldfk: controllingField, - name, - value, - updatedBy - - }, - ], - }; - try { - const response = await createOrUpdateOption(blocksFieldId, newDistrict, t); + const updatedBy = localStorage.getItem("userId") + if (updatedBy) { + const newDistrict = { + isCreate: false, + options: [ + { + controllingfieldfk: controllingField, + name, + value, + updatedBy - if (response) { - filteredCohortOptionData(); - } - const queryParameters = { - name: name, - updatedBy:localStorage.getItem('userId'), - - }; - - try { - const cohortCreateResponse = await updateCohort( - cohortIdForEdit, - queryParameters - ); - if (cohortCreateResponse) { - await fetchBlocks(); - await getCohortSearchBlock(selectedDistrict); - showToastMessage(t("COMMON.BLOCK_UPDATED_SUCCESS"), "success"); - const windowUrl = window.location.pathname; - const cleanedUrl = windowUrl.replace(/^\//, ''); - const env = cleanedUrl.split("/")[0]; - - - const telemetryInteract = { - context: { - env: env, - cdata: [], - }, - edata: { - id: 'block-update-success', - type: TelemetryEventType.CLICK, - subtype: '', - pageid: cleanedUrl, }, + ], + }; + try { + const response = await createOrUpdateOption(blocksFieldId, newDistrict, t); + + if (response) { + filteredCohortOptionData(); + } + const queryParameters = { + name: name, + updatedBy: localStorage.getItem('userId'), + }; - telemetryFactory.interact(telemetryInteract); - - } else if (cohortCreateResponse.responseCode === 409) { - showToastMessage(t("COMMON.BLOCK_DUPLICATION_FAILURE"), "error"); + + try { + const cohortCreateResponse = await updateCohort( + cohortIdForEdit, + queryParameters + ); + if (cohortCreateResponse) { + await fetchBlocks(); + await getCohortSearchBlock(selectedDistrict); + showToastMessage(t("COMMON.BLOCK_UPDATED_SUCCESS"), "success"); + const windowUrl = window.location.pathname; + const cleanedUrl = windowUrl.replace(/^\//, ''); + const env = cleanedUrl.split("/")[0]; + + + const telemetryInteract = { + context: { + env: env, + cdata: [], + }, + edata: { + id: 'block-update-success', + type: TelemetryEventType.CLICK, + subtype: '', + pageid: cleanedUrl, + }, + }; + telemetryFactory.interact(telemetryInteract); + + } 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"); + } + } catch (error) { + console.error("Error adding district:", error); } - } catch (error) { - console.error("Error creating cohort:", error); - showToastMessage(t("COMMON.BLOCK_DUPLICATION_FAILURE"), "error"); + + + setModalOpen(false); + setSelectedStateForEdit(null); } - } catch (error) { - console.error("Error adding district:", error); - } - - setModalOpen(false); - setSelectedStateForEdit(null); -} - }; const userProps = { @@ -1001,10 +998,10 @@ if(updatedBy) initialValues={ selectedStateForEdit ? { - controllingField: selectedStateForEdit.selectedDistrict, - name: selectedStateForEdit.name, - value: selectedStateForEdit.value, - } + controllingField: selectedStateForEdit.selectedDistrict, + name: selectedStateForEdit.name, + value: selectedStateForEdit.value, + } : {} } /> @@ -1013,8 +1010,8 @@ if(updatedBy) message={ countOfCenter > 0 ? t("COMMON.ARE_YOU_SURE_DELETE_BLOCK", { - centerCount: `${countOfCenter}`, - }) + centerCount: `${countOfCenter}`, + }) : t("COMMON.NO_ACTIVE_CENTERS_DELETE") } handleAction={handleConfirmDelete} diff --git a/src/services/formatedCohorts.ts b/src/services/formatedCohorts.ts index ec678d13..a6f3381a 100644 --- a/src/services/formatedCohorts.ts +++ b/src/services/formatedCohorts.ts @@ -1,11 +1,11 @@ import { - getCohortList, - } from "@/services/CohortService/cohortService"; + getCohortList, +} from "@/services/CohortService/cohortService"; import { - CohortTypes, - - } from "@/utils/app.constant"; + CohortTypes, + +} from "@/utils/app.constant"; import { getStateBlockDistrictList } from "./MasterDataService"; interface Cohort { name: string; @@ -22,43 +22,43 @@ interface FormattedBlocksResult { matchedCohorts: BlockValue[]; } export const formatedDistricts = async () => { - const adminState = JSON.parse( - localStorage.getItem("adminInfo") || "{}" - ).customFields.find( - (field: any) => field.label === "STATES" - );; + const adminState = JSON.parse( + localStorage.getItem("adminInfo") || "{}" + ).customFields.find( + (field: any) => field.label === "STATES" + );; try { const reqParams = { - limit: 0, - offset: 0, - filters: { - // name: searchKeyword, - states: adminState.code, - type: CohortTypes.DISTRICT, - status: ["active"] - - }, - sort: ["name", "asc"], - }; - - const response = await getCohortList(reqParams); - - const cohortDetails = response?.results?.cohortDetails || []; - const object = { - controllingfieldfk: adminState.code, - fieldName: "districts", - }; - const optionReadResponse = await getStateBlockDistrictList(object); - //console.log(blockFieldId) - const result = optionReadResponse?.result?.values; - console.log(cohortDetails) - console.log(result) - const matchedCohorts = result?.map((value: any) => { - const cohortMatch = cohortDetails.find((cohort: any )=> cohort.name === value.label); - return cohortMatch ? { ...value } : null; - }).filter(Boolean); - return matchedCohorts; - // console.log(matchedCohorts); + limit: 0, + offset: 0, + filters: { + // name: searchKeyword, + states: adminState.code, + type: CohortTypes.DISTRICT, + status: ["active"] + + }, + sort: ["name", "asc"], + }; + + const response = await getCohortList(reqParams); + + const cohortDetails = response?.results?.cohortDetails || []; + const object = { + controllingfieldfk: adminState.code, + fieldName: "districts", + }; + const optionReadResponse = await getStateBlockDistrictList(object); + //console.log(blockFieldId) + const result = optionReadResponse?.result?.values; + console.log(cohortDetails) + console.log(result) + const matchedCohorts = result?.map((value: any) => { + const cohortMatch = cohortDetails.find((cohort: any) => cohort?.name?.toLowerCase() === value?.label?.toLowerCase()); + return cohortMatch ? { ...value } : null; + }).filter(Boolean); + return matchedCohorts; + // console.log(matchedCohorts); } catch (error) { console.log('Error in getting Channel Details', error); @@ -103,7 +103,7 @@ export const formatedBlocks = async (districtCode: string) => { const matchedCohorts = result ?.map((value: any) => { const cohortMatch = cohortDetails.find( - (cohort: any) => cohort.name === value.label + (cohort: any) => cohort?.name?.toLowerCase() === value?.label?.toLowerCase() ); // Include cohortId if the match is found return cohortMatch ? { ...value, cohortId: cohortMatch.cohortId } : null;