From 36436fae0e2ae46234858a1c7c0d2d1665625da9 Mon Sep 17 00:00:00 2001 From: chaitanyakole Date: Thu, 6 Feb 2025 18:07:30 +0530 Subject: [PATCH] Task #234815 Remove Unwanted Code from the Admin Portal --- src/components/AddBlockModal.tsx | 400 ----------- src/components/AddDistrictModal.tsx | 250 ------- src/components/AddStateModal.tsx | 187 ------ src/pages/block.tsx | 998 ---------------------------- src/pages/cohorts.tsx | 55 +- src/pages/course-planner/index.tsx | 50 +- src/pages/district.tsx | 729 -------------------- src/pages/faciliator.tsx | 59 -- src/pages/facilitator.tsx | 59 -- src/pages/mainCourse.tsx | 25 - src/pages/resourceList.tsx | 130 ---- src/pages/state.tsx | 358 ---------- src/pages/stateDetails.tsx | 184 ----- src/pages/subjectDetails.tsx | 563 ---------------- src/pages/team-leader.tsx | 61 -- src/pages/tenant.tsx | 382 ++--------- src/services/Interceptor.ts | 1 - 17 files changed, 66 insertions(+), 4425 deletions(-) delete mode 100644 src/components/AddBlockModal.tsx delete mode 100644 src/components/AddDistrictModal.tsx delete mode 100644 src/components/AddStateModal.tsx delete mode 100644 src/pages/block.tsx delete mode 100644 src/pages/district.tsx delete mode 100644 src/pages/faciliator.tsx delete mode 100644 src/pages/facilitator.tsx delete mode 100644 src/pages/mainCourse.tsx delete mode 100644 src/pages/resourceList.tsx delete mode 100644 src/pages/state.tsx delete mode 100644 src/pages/stateDetails.tsx delete mode 100644 src/pages/subjectDetails.tsx delete mode 100644 src/pages/team-leader.tsx diff --git a/src/components/AddBlockModal.tsx b/src/components/AddBlockModal.tsx deleted file mode 100644 index 05f97e4a..00000000 --- a/src/components/AddBlockModal.tsx +++ /dev/null @@ -1,400 +0,0 @@ -import React, { useState, useEffect } from "react"; -import { - Dialog, - DialogTitle, - DialogContent, - DialogActions, - TextField, - Button, - Typography, - Box, - Select, - MenuItem, - Divider, -} from "@mui/material"; -import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined"; -import { useTranslation } from "next-i18next"; -import { getDistrictsForState } from "@/services/MasterDataService"; -import { getCohortList } from "@/services/CohortService/cohortService"; -import { useQueryClient } from "@tanstack/react-query"; -import { CohortTypes, QueryKeys } from "@/utils/app.constant"; - -interface AddBlockModalProps { - open: boolean; - onClose: () => void; - onSubmit: ( - name: string, - value: string, - controllingField: string, - cohortId: string, - fieldId: string, - districtId?: string - ) => void; - fieldId: string; - initialValues?: { - name?: string; - value?: string; - controllingField?: string; - }; - districtId?: string; -} - -export const AddBlockModal: React.FC = ({ - open, - onClose, - onSubmit, - fieldId, - initialValues = {}, - districtId, -}) => { - const [formData, setFormData] = useState({ - name: initialValues.name || "", - value: initialValues.value || "", - controllingField: initialValues.controllingField || "", - }); - - const [errors, setErrors] = useState>({}); - const [districts, setDistricts] = useState< - { value: string; label: string; cohortId: string | null }[] - >([]); - - const [districtsOptionRead, setDistrictsOptionRead] = useState([]); - const [districtCodeArr, setDistrictCodeArr] = useState([]); - const [districtNameArr, setDistrictNameArr] = useState([]); - const [cohortIdAddNewDropdown, setCohortIdAddNewDropdown] = useState(""); - const [stateCode, setStateCode] = useState(""); - const [stateName, setStateName] = useState(""); - - const { t } = useTranslation(); - const queryClient = useQueryClient(); - - useEffect(() => { - const storedUserData = JSON.parse( - localStorage.getItem("adminInfo") || "{}" - ); - const stateCodes = storedUserData?.customFields[0]?.code; - const stateNames = storedUserData?.customFields[0]?.value; - setStateCode(stateCodes); - setStateName(stateNames); - }, [open]); - - useEffect(() => { - setFormData({ - name: initialValues.name || "", - value: initialValues.value || "", - controllingField: initialValues.controllingField || "", - }); - - setErrors({}); - }, [initialValues]); - - useEffect(() => { - if (formData.controllingField) { - const selectedDistrict = districts.find( - (district) => district.value === formData.controllingField - ); - setCohortIdAddNewDropdown(selectedDistrict?.cohortId || null); - } - }, [formData.controllingField, districts]); - - const fetchDistricts = async () => { - try { - const data = await queryClient.fetchQuery({ - queryKey: [QueryKeys.FIELD_OPTION_READ, stateCode || "", "districts"], - queryFn: () => - getDistrictsForState({ - controllingfieldfk: stateCode || "", - 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); - - } 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: { - // states: stateCode, - type: CohortTypes.DISTRICT, - }, - }; - - const response = await queryClient.fetchQuery({ - queryKey: [ - QueryKeys.FIELD_OPTION_READ, - reqParams.limit, - reqParams.offset, - CohortTypes.DISTRICT, - ], - queryFn: () => 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) - ); - setDistricts(filteredDistrictData); - } catch (error) { - console.error("Error fetching and filtering cohort districts", error); - } - }; - useEffect(() => { - if (open) getFilteredCohortData(); - }, [open, districtNameArr]); - - function transformLabels(label: string) { - if (!label || typeof label !== "string") return ""; - return label - .toLowerCase() - .replace(/_/g, " ") - .replace(/\b\w/g, (char) => char.toUpperCase()); - } - - const validateField = ( - field: keyof typeof formData, - value: string, - requiredMessage: string - ) => { - if (!value) return null; - - if (field !== "controllingField" && !/^[a-zA-Z\s]+$/.test(value)) { - return t("COMMON.INVALID_TEXT"); - } - - const isUnique = (fieldName: string, value: string) => { - return true; - }; - - if (field === "name" && !isUnique("name", value)) { - return t("COMMON.BLOCK_NAME_NOT_UNIQUE"); - } - - if (field === "value" && !isUnique("value", value)) { - return t("COMMON.BLOCK_CODE_NOT_UNIQUE"); - } - - return null; - }; - - const handleChange = - (field: keyof typeof formData) => - async (e: React.ChangeEvent) => { - let value = typeof e.target.value === "string" ? e.target.value : ""; - - if (field === "value") { - value = value.toUpperCase().slice(0, 3); - } - - setFormData((prev) => ({ ...prev, [field]: value })); - - let errorMessage: string | null = validateField(field, value, ""); - - setErrors((prev) => ({ - ...prev, - [field]: errorMessage, - })); - }; - - const validateForm = () => { - const newErrors = { - name: - validateField("name", formData.name, t("COMMON.BLOCK_NAME_REQUIRED")) || - (!formData.name ? t("COMMON.BLOCK_NAME_REQUIRED") : null), - value: - validateField( - "value", - formData.value, - t("COMMON.BLOCK_CODE_REQUIRED") - ) || (!formData.value ? t("COMMON.BLOCK_CODE_REQUIRED") : null), - controllingField: - validateField( - "controllingField", - formData.controllingField, - t("COMMON.DISTRICT_NAME_REQUIRED") - ) || - (!formData.controllingField - ? t("COMMON.DISTRICT_NAME_REQUIRED") - : null), - }; - - setErrors(newErrors); - return !Object.values(newErrors).some((error) => error !== null); - }; - - const handleSubmit = () => { - if (validateForm()) { - const currentCohortId: any = cohortIdAddNewDropdown; - - onSubmit( - formData.name, - formData.value, - formData.controllingField, - currentCohortId, - fieldId, - districtId - ); - - setFormData({ - name: "", - value: "", - controllingField: "", - }); - - onClose(); - } - }; - const isEditing = !!initialValues.name; - const buttonText = isEditing ? t("COMMON.UPDATE") : t("COMMON.SUBMIT"); - const dialogTitle = isEditing - ? t("COMMON.UPDATE_BLOCK") - : t("COMMON.ADD_BLOCK"); - - return ( - - {dialogTitle} - - - {!(formData.controllingField === "All") && ( - - )} - {errors.controllingField && ( - - {errors.controllingField} - - )} - - - - - - {t("COMMON.CODE_NOTIFICATION")} - - - - - - - - - - ); -}; diff --git a/src/components/AddDistrictModal.tsx b/src/components/AddDistrictModal.tsx deleted file mode 100644 index 1dc903a7..00000000 --- a/src/components/AddDistrictModal.tsx +++ /dev/null @@ -1,250 +0,0 @@ -import React, { useState, useEffect } from "react"; -import { - Dialog, - DialogTitle, - DialogContent, - DialogActions, - TextField, - Button, - Typography, - Box, - Select, - MenuItem, - Divider, -} from "@mui/material"; -import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined"; -import { useTranslation } from "next-i18next"; -import { getUserDetailsInfo } from "@/services/UserList"; -import { QueryKeys, Storage } from "@/utils/app.constant"; -import { useQueryClient } from "@tanstack/react-query"; - -interface AddDistrictBlockModalProps { - open: boolean; - onClose: () => void; - onSubmit: ( - name: string, - value: string, - controllingField: string, - fieldId: string, - districtId?: string - ) => void; - fieldId: string; - initialValues?: { - name?: string; - value?: string; - controllingField?: string; - }; - districtId?: string; -} - -const AddDistrictModal: React.FC = ({ - open, - onClose, - onSubmit, - fieldId, - initialValues = {}, - districtId, -}) => { - const [formData, setFormData] = useState({ - name: initialValues?.name ?? "", - value: initialValues?.value ?? "", - controllingField: initialValues?.controllingField ?? "", - }); - - const [errors, setErrors] = useState>({}); - const [stateCode, setStateCode] = useState(""); - const [stateValue, setStateValue] = useState(""); - - const { t } = useTranslation(); - const queryClient = useQueryClient(); - - useEffect(() => { - const fetchUserDetail = async () => { - let userId: any; - try { - if (typeof window !== "undefined" && window.localStorage) { - userId = localStorage.getItem(Storage.USER_ID); - } - const response = await queryClient.fetchQuery({ - queryKey: [QueryKeys.USER_READ, userId, true], - queryFn: () => getUserDetailsInfo(userId, true), - }); - const statesField = response.userData.customFields.find( - (field: { label: string }) => field.label === "STATES" - ); - - if (statesField) { - setStateValue(statesField.value); - setStateCode(statesField.code); - setFormData((prev) => ({ - ...prev, - controllingField: statesField.code, - })); - } - } catch (error) { - console.log(error); - } - }; - if (open) { - fetchUserDetail(); - } - }, [open]); - - useEffect(() => { - setFormData({ - name: initialValues.name ?? "", - value: initialValues.value ?? "", - controllingField: initialValues.controllingField ?? stateCode, - }); - setErrors({}); - }, [initialValues, stateCode]); - - const isValidName = (input: string) => - /^[a-zA-Z]+(?:\s[a-zA-Z]+)*$/.test(input); - - const isValidCode = (input: string) => /^[A-Z]{1,3}$/.test(input); - - const handleChange = (field: string, value: string) => { - if (field === "name") { - value = value.replace(/[^a-zA-Z\s]/g, ""); - } - - if (field === "value" && value.length > 3) { - return; - } - - setFormData((prev) => ({ ...prev, [field]: value })); - - setErrors((prev) => ({ ...prev, [field]: null })); - }; - - const validateForm = () => { - const newErrors: { name?: string; value?: string } = {}; - - if (!formData.name) { - newErrors.name = t("COMMON.DISTRICT_NAME_REQUIRED"); - } else if (!isValidName(formData.name.trim())) { - newErrors.name = t("COMMON.INVALID_TEXT"); - } - - if (!formData.value) { - newErrors.value = t("COMMON.CODE_REQUIRED"); - } else if (!isValidCode(formData.value)) { - newErrors.value = t("COMMON.INVALID_TEXT"); - } - - setErrors(newErrors); - return Object.keys(newErrors).length === 0; - }; - - const handleSubmit = () => { - if (validateForm()) { - onSubmit( - formData.name, - formData.value, - formData.controllingField || stateCode, - fieldId, - districtId - ); - setFormData({ - name: "", - value: "", - controllingField: "", - }); - onClose(); - } - }; - - const isEditing = !!initialValues.name; - const isEditCode = !!initialValues.value; - const buttonText = isEditing ? t("COMMON.UPDATE") : t("COMMON.SUBMIT"); - const dialogTitle = isEditing - ? t("COMMON.UPDATE_DISTRICT") - : t("COMMON.ADD_DISTRICT"); - - return ( - - {dialogTitle} - - - - {errors.controllingField && ( - - {errors.controllingField} - - )} - handleChange("name", e.target.value)} - error={!!errors.name} - helperText={errors.name} - /> - handleChange("value", e.target.value.toUpperCase())} - error={!!errors.value} - helperText={errors.value} - disabled={isEditCode} - /> - - - - {t("COMMON.CODE_NOTIFICATION")} - - - - - - - - - - ); -}; - -export default AddDistrictModal; diff --git a/src/components/AddStateModal.tsx b/src/components/AddStateModal.tsx deleted file mode 100644 index 124991ab..00000000 --- a/src/components/AddStateModal.tsx +++ /dev/null @@ -1,187 +0,0 @@ -import React, { useState, useEffect } from "react"; -import { - Dialog, - DialogTitle, - DialogContent, - DialogActions, - TextField, - Button, - Typography, - Box, - Divider, -} from "@mui/material"; -import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined"; -import { useTranslation } from "next-i18next"; - -interface AddStateModalProps { - open: boolean; - onClose: () => void; - onSubmit: ( - name: string, - value: string, - fieldId: string, - stateId?: string - ) => void; - fieldId: string; - initialValues?: { - name?: string; - value?: string; - }; - stateId?: string; -} - -export const AddStateModal: React.FC = ({ - open, - onClose, - onSubmit, - fieldId, - initialValues = {}, - stateId, -}) => { - const [formData, setFormData] = useState({ - name: initialValues.name || "", - value: initialValues.value || "", - }); - const [errors, setErrors] = useState<{ name?: string; value?: string }>({}); - const { t } = useTranslation(); - - useEffect(() => { - setFormData({ - name: initialValues.name || "", - value: initialValues.value || "", - }); - setErrors({}); - }, [open, initialValues]); - - const isValidName = (input: string) => - /^[a-zA-Z]+(?:\s[a-zA-Z]+)*$/.test(input); - - const isValidCode = (input: string) => /^[A-Z]{1,3}$/.test(input); - - const handleChange = (field: string, value: string) => { - if (field === "name") { - value = value.replace(/[^a-zA-Z\s]/g, ""); - } - - if (field === "value" && value.length > 3) { - return; - } - - setFormData((prev) => ({ ...prev, [field]: value })); - - if (value === "") { - setErrors((prev) => ({ - ...prev, - [field]: t( - field === "name" - ? "COMMON.STATE_NAME_REQUIRED" - : "COMMON.CODE_REQUIRED" - ), - })); - } else if (field === "name" && !isValidName(value.trim())) { - setErrors((prev) => ({ ...prev, [field]: t("COMMON.INVALID_INPUT") })); - } else if (field === "value" && !isValidCode(value)) { - setErrors((prev) => ({ ...prev, [field]: t("COMMON.INVALID_TEXT") })); - } else { - setErrors((prev) => ({ ...prev, [field]: undefined })); - } - }; - - const validateForm = () => { - const newErrors: { name?: string; value?: string } = {}; - - if (!formData.name) { - newErrors.name = t("COMMON.STATE_NAME_REQUIRED"); - } else if (!isValidName(formData.name.trim())) { - newErrors.name = t("COMMON.INVALID_TEXT"); - } - - if (!formData.value) { - newErrors.value = t("COMMON.CODE_REQUIRED"); - } else if (!isValidCode(formData.value)) { - newErrors.value = t("COMMON.INVALID_TEXT"); - } - - setErrors(newErrors); - return Object.keys(newErrors).length === 0; - }; - - const handleSubmit = () => { - if (validateForm()) { - onSubmit(formData.name, formData.value, fieldId, stateId); - } - }; - - return ( - - - {stateId ? t("COMMON.UPDATE_STATE") : t("COMMON.ADD_STATE")} - - - - handleChange("name", e.target.value)} - error={!!errors.name} - helperText={errors.name} - /> - handleChange("value", e.target.value.toUpperCase())} - error={!!errors.value} - helperText={errors.value} - /> - - - - {t("COMMON.CODE_NOTIFICATION")} - - - - - - - - - - - ); -}; diff --git a/src/pages/block.tsx b/src/pages/block.tsx deleted file mode 100644 index e275b8f7..00000000 --- a/src/pages/block.tsx +++ /dev/null @@ -1,998 +0,0 @@ -import React, { useState, useEffect } from "react"; -import KaTableComponent from "../components/KaTableComponent"; -import HeaderComponent from "@/components/HeaderComponent"; -import { Pagination, Typography, useMediaQuery } from "@mui/material"; -import Box from "@mui/material/Box"; -import FormControl from "@mui/material/FormControl"; -import InputLabel from "@mui/material/InputLabel"; -import MenuItem from "@mui/material/MenuItem"; -import Select, { SelectChangeEvent } from "@mui/material/Select"; -import { useTranslation } from "next-i18next"; -import Loader from "@/components/Loader"; -import { useQueryClient } from "@tanstack/react-query"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import { - getDistrictsForState, - 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 { - CohortTypes, - SORT, - Status, - Storage, - Numbers, - QueryKeys, -} from "@/utils/app.constant"; -import { getUserDetailsInfo } from "@/services/UserList"; -import { - createCohort, - getCohortList, -} from "@/services/CohortService/cohortService"; -import { getBlockTableData } from "@/data/tableColumns"; -import { Theme } from "@mui/system"; - -type StateDetail = { - name: string | undefined; - controllingField: string | undefined; - block: string | undefined; - selectedDistrict: string | undefined; - value: string; - label: string; -}; - -type DistrictDetail = { - cohortId(cohortId: any): unknown; - value: string; - label: string; -}; - -type BlockDetail = { - code: any; - parentId(parentId: any): unknown; - status: Status; - cohortId(cohortId: any): unknown; - updatedBy: any; - createdBy: any; - updatedAt: any; - createdAt: any; - value: string; - label: string; - block: string; -}; - -interface BlockOption { - label: string; - value: any; -} - -const Block: React.FC = () => { - const { t } = useTranslation(); - const [selectedSort, setSelectedSort] = useState("Sort"); - const [selectedState, setSelectedState] = useState(""); - const [selectedDistrict, setSelectedDistrict] = useState(""); - const [stateData, setStateData] = useState([]); - const [selectedFilter, setSelectedFilter] = useState("All"); - const [districtData, setDistrictData] = useState([]); - const [blockData, setBlockData] = useState([]); - const [loading, setLoading] = useState(false); - const [pageOffset, setPageOffset] = useState(0); - const [pageLimit, setPageLimit] = useState(10); - const [pageCount, setPageCount] = useState(1); - const [selectedStateForDelete, setSelectedStateForDelete] = - useState(null); - const [confirmationDialogOpen, setConfirmationDialogOpen] = - useState(false); - const [modalOpen, setModalOpen] = useState(false); - const [editState, setEditState] = useState(null); - const [selectedStateForEdit, setSelectedStateForEdit] = - useState(null); - const [blocksFieldId, setBlocksFieldId] = useState("4aab68ae-8382-43aa-a45a-e9b239319857"); - const [districtFieldId, setDistrictFieldId] = useState(""); - const [sortBy, setSortBy] = useState<[string, string]>(["name", "asc"]); - const [paginationCount, setPaginationCount] = useState(0); - const [pageSizeArray, setPageSizeArray] = useState([5, 10, 20, 50]); - const [stateCode, setStateCode] = useState(""); - const [stateValue, setStateValue] = useState(""); - const [stateFieldId, setStateFieldId] = useState(""); - const [searchKeyword, setSearchKeyword] = useState(""); - const [pagination, setPagination] = useState(true); - 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 [blockValueForDelete, setBlockValueForDelete] = useState(); - const [countOfCenter, setCountOfCenter] = useState(0); - const [selectedCohortId, setSelectedCohortId] = useState(null); - const [parentIdBlock, setParentIdBlock] = useState(null); - const [showAllBlocks, setShowAllBlocks] = useState("All"); - const [statusValue, setStatusValue] = useState(Status.ACTIVE); - const [pageSize, setPageSize] = React.useState(10); - const [isFirstVisit, setIsFirstVisit] = useState(true); - const queryClient = useQueryClient(); - - const [filters, setFilters] = useState({ - name: searchKeyword, - states: stateCode, - districts: selectedDistrict, - type: CohortTypes.BLOCK, - status: [statusValue], - }); - - const isMobile = useMediaQuery((theme: Theme) => - theme.breakpoints.down("sm") - ); - - useEffect(() => { - const fetchUserDetail = async () => { - let userId: any; - try { - if (typeof window !== "undefined" && window.localStorage) { - userId = localStorage.getItem(Storage.USER_ID); - } - - const response = await queryClient.fetchQuery({ - queryKey: [QueryKeys.USER_READ, userId, true], - queryFn: () => getUserDetailsInfo(userId, true), - }); - - const statesField = response.userData.customFields.find( - (field: { label: string }) => field.label === "STATES" - ); - - if (statesField) { - setStateValue(statesField.value); - setStateCode(statesField.code); - setStateFieldId(statesField?.fieldId); - } - } catch (error) { - console.log(error); - } - }; - fetchUserDetail(); - }, []); - - const fetchDistricts = async () => { - try { - const data = await queryClient.fetchQuery({ - queryKey: [QueryKeys.FIELD_OPTION_READ, stateCode, "districts"], - queryFn: () => - getDistrictsForState({ - controllingfieldfk: stateCode, - 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); - } catch (error) { - console.error("Error fetching districts", error); - } - }; - - useEffect(() => { - fetchDistricts(); - }, [stateCode]); - - const getFilteredCohortData = async () => { - try { - setLoading(true); - const reqParams = { - limit: 0, - offset: 0, - filters: { - name: searchKeyword, - // states: stateCode, - type: CohortTypes.DISTRICT, - }, - sort: sortBy, - }; - - // const response = await queryClient.fetchQuery({ - // queryKey: [ - // QueryKeys.FIELD_OPTION_READ, - // reqParams.limit, - // reqParams.offset, - // searchKeyword || "", - // CohortTypes.DISTRICT, - // reqParams.sort.join(","), - // ], - // queryFn: () => getCohortList(reqParams), - // }); - - 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) - ); - if (isFirstVisit) - { - if ( - filteredDistrictData.length > 0 && - selectedDistrict !== t("COMMON.ALL") - ) { - setSelectedDistrict(filteredDistrictData[0].value); - } - setIsFirstVisit(false); - } - setDistrictData(filteredDistrictData); - setLoading(false); - } catch (error) { - console.error("Error fetching and filtering cohort districts", error); - } finally { - setLoading(false); - } - }; - useEffect(() => { - if (stateCode) { - getFilteredCohortData(); - } - }, [isFirstVisit, searchKeyword, pageLimit, pageOffset, stateCode]); - - - useEffect(() => { - if(districtData[0]?.value && isFirstVisit) - { - setSelectedDistrict(districtData[0]?.value); - setIsFirstVisit(false); - } - - }, [districtData]); - - const fetchBlocks = async () => { - try { - // const response = await queryClient.fetchQuery({ - // queryKey: [ - // QueryKeys.FIELD_OPTION_READ, - // selectedDistrict === t("COMMON.ALL") ? "" : selectedDistrict, - // "blocks", - // ], - // queryFn: () => - // getBlocksForDistricts({ - // controllingfieldfk: - // selectedDistrict === t("COMMON.ALL") ? "" : selectedDistrict, - // fieldName: "blocks", - // }), - // }); - const response = await getBlocksForDistricts({ - controllingfieldfk: - selectedDistrict === t("COMMON.ALL") ? "" : selectedDistrict, - fieldName: "blocks", - }) - const blocks = response?.result?.values || []; - setBlocksOptionRead(blocks); - - const blockNameArray = blocks.map((item: any) => item.label); - setBlockNameArr(blockNameArray); - - const blockCodeArray = blocks.map((item: any) => item.value); - setBlockCodeArr(blockCodeArray); - - const blockFieldID = response?.result?.fieldId || "4aab68ae-8382-43aa-a45a-e9b239319857"; - setBlocksFieldId(blockFieldID); - } catch (error) { - console.error("Error fetching blocks", error); - } - }; - - useEffect(() => { - fetchBlocks(); - }, [selectedDistrict]); - - const getCohortSearchBlock = async (selectedDistrict: string) => { - try { - setLoading(true); - if (!blocksOptionRead.length || !blockNameArr.length) { - console.warn( - "blocksOptionRead or blockNameArr is empty, waiting for data..." - ); - setLoading(false); - return; - } - - const reqParams = { - limit: 0, - offset: 0, - filters: { - name: searchKeyword, - // states: stateCode, - // districts: - // selectedDistrict === t("COMMON.ALL") ? "" : selectedDistrict, - // type: CohortTypes.BLOCK, - status: [statusValue], - }, - sort: sortBy, - }; - - // const response = await queryClient.fetchQuery({ - // queryKey: [ - // QueryKeys.FIELD_OPTION_READ, - // reqParams.limit, - // reqParams.offset, - // searchKeyword || "", - // stateCode, - // reqParams.filters.districts, - // CohortTypes.BLOCK, - // reqParams.sort.join(","), - // ], - // queryFn: () => getCohortList(reqParams), - // }); - const response = await getCohortList(reqParams) - - const cohortDetails = response?.results?.cohortDetails || []; - const filteredBlockData = cohortDetails - .map( - (blockDetail: { - parentId: any; - cohortId: any; - name: string; - code: string; - createdAt: any; - updatedAt: any; - createdBy: any; - updatedBy: any; - status: string; - }) => { - const transformedName = blockDetail.name; - - const matchingBlock = blocksOptionRead.find( - (block: BlockOption) => block.label === transformedName - ); - - return { - name: transformedName, - code: matchingBlock?.value ?? "", - status: blockDetail.status, - createdAt: blockDetail.createdAt, - updatedAt: blockDetail.updatedAt, - createdBy: blockDetail.createdBy, - updatedBy: blockDetail.updatedBy, - cohortId: blockDetail.cohortId, - parentId: blockDetail.parentId, - }; - } - ) - .filter((block: { name: string }) => blockNameArr.includes(block.name)); - - setBlockData(filteredBlockData); - setShowAllBlocks(filteredBlockData); - - const totalCount = filteredBlockData.length; - setPaginationCount(totalCount); - setPageCount(Math.ceil(totalCount / pageLimit)); - - setLoading(false); - } catch (error) { - console.error("Error fetching and filtering cohort blocks", error); - setLoading(false); - } - }; - - useEffect(() => { - if (selectedDistrict) { - getCohortSearchBlock(selectedDistrict); - } - }, [ - filters, - searchKeyword, - pageLimit, - pageOffset, - sortBy, - blocksOptionRead, - blockNameArr, - ]); - - const getCohortDataCohort = async () => { - try { - const reqParams = { - limit: 0, - offset: 0, - filters: { - // blocks: parentIdBlock, //cohort id of block - }, - }; - - const response: any = await getCohortList(reqParams); - - const activeCenters = response?.results?.cohortDetails || []; - - const activeCentersCount = activeCenters.filter( - (block: { status: string }) => block.status === "active" - ).length; - setCountOfCenter(activeCentersCount); - } catch (error) { - console.error("Error fetching and filtering cohort districts", error); - } - }; - - useEffect(() => { - if (parentIdBlock) { - getCohortDataCohort(); - } - }, [parentIdBlock]); - - 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 handleSortChange = async (event: SelectChangeEvent) => { - const sortOrder = - event.target.value === "Z-A" ? SORT.DESCENDING : SORT.ASCENDING; - setSortBy(["name", sortOrder]); - setSelectedSort(event.target.value); - }; - - const handleStateChange = async (event: SelectChangeEvent) => { - const selectedState = event.target.value; - setSelectedState(selectedState); - }; - - const handleDistrictChange = async (event: SelectChangeEvent) => { - setPageOffset(Numbers.ZERO); - setPageCount(Numbers.ONE); - - const selectedDistrict = event.target.value; - setSelectedDistrict(selectedDistrict); - setShowAllBlocks(""); - - const selectedDistrictData = districtData.find( - (district) => district.value === selectedDistrict - ); - - const cohortId = selectedDistrictData?.cohortId as any | null; - - setSelectedCohortId(cohortId); - if (selectedDistrict) { - await getCohortSearchBlock(selectedDistrict); - } - }; - - useEffect(() => { - if (selectedDistrict) { - getCohortSearchBlock(selectedDistrict); - } - }, [blockNameArr, searchKeyword, pageLimit, pageOffset, selectedDistrict]); - - const handleEdit = (rowData: any) => { - setModalOpen(true); - const cohortIdForEDIT = rowData.cohortId; - setCohortIdForEdit(cohortIdForEDIT); - - const initialValues: StateDetail = { - name: rowData.name || "", - value: rowData.code || "", - selectedDistrict: selectedDistrict || "All", - controllingField: "", - block: "", - label: "", - }; - setSelectedStateForEdit(initialValues); - }; - const handleDelete = (rowData: BlockDetail) => { - setSelectedStateForDelete(rowData); - setCohortIdForDelete(rowData.cohortId); - setConfirmationDialogOpen(true); - - setParentIdBlock(rowData.code as any | null); - const blockValue = rowData.value; - setBlockValueForDelete(blockValue); - }; - - const handleSearch = (keyword: string) => { - setPageOffset(Numbers.ZERO); - setPageCount(Numbers.ONE); - setSearchKeyword(keyword); - }; - - const handleFilterChange = async ( - event: React.SyntheticEvent, - newValue: any - ) => { - setStatusValue(newValue); - setSelectedFilter(newValue); - setPageSize(Numbers.TEN); - setPageLimit(Numbers.TEN); - setPageOffset(Numbers.ZERO); - setPageCount(Numbers.ONE); - - if (newValue === Status.ACTIVE) { - setFilters((prevFilters: any) => ({ - ...prevFilters, - status: [Status.ACTIVE], - })); - } else if (newValue === Status.ARCHIVED) { - setFilters((prevFilters: any) => ({ - ...prevFilters, - status: [Status.ARCHIVED], - })); - } else if (newValue === Status.ALL_LABEL) { - setFilters((prevFilters: any) => ({ - ...prevFilters, - status: "", - })); - } else { - setFilters((prevFilters: any) => { - const { status, ...restFilters } = prevFilters; - return { - ...restFilters, - }; - }); - } - - await queryClient.invalidateQueries({ - queryKey: [QueryKeys.FIELD_OPTION_READ], - }); - queryClient.fetchQuery({ - queryKey: [QueryKeys.FIELD_OPTION_READ, newValue], - queryFn: () => getCohortList({ status: newValue }), - }); - }; - - const handleConfirmDelete = async () => { - if (selectedStateForDelete) { - try { - await deleteOption("blocks", selectedStateForDelete.value); - setStateData((prevStateData) => - prevStateData.filter( - (state) => state.value !== selectedStateForDelete.value - ) - ); - showToastMessage(t("COMMON.BLOCK_DELETED_SUCCESS"), "success"); - } catch (error) { - console.error("Error deleting state", error); - 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); - }; - - const handleChangePageSize = (event: SelectChangeEvent) => { - setPageSize(event.target.value); - setPageLimit(Number(event.target.value)); - }; - - const handlePaginationChange = ( - event: React.ChangeEvent, - value: number - ) => { - setPageOffset(value - 1); - }; - const PagesSelector = () => ( - - - - ); - - const PageSizeSelectorFunction = () => ( - - - - ); - - const handleAddNewBlock = () => { - setEditState(null); - setSelectedStateForEdit(null); - setModalOpen(true); - }; - - //create cohort - const handleCreateCohortSubmit = async ( - name: string, - value: string, - controllingField: string, - cohortId?: string, - DistrictId?: string, - extraArgument?: any - ) => { - const newDistrict = { - options: [ - { - controllingfieldfk: controllingField, - name, - value, - }, - ], - }; - - try { - const response = await createOrUpdateOption(blocksFieldId, newDistrict); - - if (response) { - await fetchBlocks(); - } - } catch (error) { - console.error("Error adding district:", error); - } - - const queryParameters = { - name: name, - type: CohortTypes.BLOCK, - status: Status.ACTIVE, - parentId: cohortId || "", - customFields: [ - { - fieldId: stateFieldId, // state fieldId - value: [stateCode], // state code - }, - - { - fieldId: districtFieldId, // district fieldId - value: [controllingField], // district code - }, - ], - }; - - try { - const cohortCreateResponse = await createCohort(queryParameters); - if (cohortCreateResponse) { - 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); - }; - - const handleUpdateCohortSubmit = async ( - name: string, - value: string, - controllingField: string, - DistrictId?: string, - extraArgument?: any - ) => { - const newDistrict = { - options: [ - { - controllingfieldfk: controllingField, - name, - value, - }, - ], - }; - try { - const response = await createOrUpdateOption(blocksFieldId, newDistrict); - - if (response) { - filteredCohortOptionData(); - } - } catch (error) { - console.error("Error adding district:", error); - } - - const queryParameters = { - name: name, - }; - - try { - const cohortCreateResponse = await updateCohort( - cohortIdForEdit, - queryParameters - ); - if (cohortCreateResponse) { - await fetchBlocks(); - await getCohortSearchBlock(selectedDistrict); - showToastMessage(t("COMMON.BLOCK_UPDATED_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); - }; - - const userProps = { - selectedFilter, - handleSearch: handleSearch, - showStateDropdown: false, - userType: t("MASTER.BLOCKS"), - searchPlaceHolder: t("MASTER.SEARCHBAR_PLACEHOLDER_BLOCK"), - showFilter: true, - showSort: true, - statusValue: statusValue, - setStatusValue: setStatusValue, - handleFilterChange: handleFilterChange, - selectedSort: selectedSort, - shouldFetchDistricts: false, - handleSortChange: handleSortChange, - handleAddUserClick: handleAddNewBlock, - }; - - return ( - - setModalOpen(false)} - onSubmit={( - name: string, - value: string, - controllingField: string, - cohortId?: string - ) => { - if (selectedStateForEdit) { - handleUpdateCohortSubmit( - name, - value, - controllingField, - blocksFieldId, - selectedStateForEdit.value - ); - } else { - handleCreateCohortSubmit( - name, - value, - controllingField, - cohortId, - blocksFieldId - ); - } - }} - fieldId={blocksFieldId} - initialValues={ - selectedStateForEdit - ? { - controllingField: selectedStateForEdit.selectedDistrict, - name: selectedStateForEdit.name, - value: selectedStateForEdit.value, - } - : {} - } - /> - 0 - ? t("COMMON.ARE_YOU_SURE_DELETE_BLOCK", { - centerCount: `${countOfCenter}`, - }) - : t("COMMON.NO_ACTIVE_CENTERS_DELETE") - } - handleAction={handleConfirmDelete} - buttonNames={{ - primary: t("COMMON.DELETE"), - secondary: t("COMMON.CANCEL"), - }} - disableDelete={countOfCenter > 0} - handleCloseModal={() => setConfirmationDialogOpen(false)} - /> - - - {loading ? ( - - - - ) : ( - <> - - - - - - - - {t("MASTER.DISTRICTS")} - - - - - - - {filteredCohortOptionData().length > 0 ? ( - = Numbers.FIVE} - PagesSelector={PagesSelector} - PageSizeSelector={PageSizeSelectorFunction} - pageSizes={pageSizeArray} - onEdit={handleEdit} - pagination={pagination} - onDelete={handleDelete} - extraActions={[]} - /> - ) : !loading && filteredCohortOptionData().length === 0 ? ( - - - {t("COMMON.BLOCKS_NOT_FOUND")} - - - ) : null} - - - )} - - - ); -}; - -export async function getStaticProps({ locale }: { locale: string }) { - return { - props: { - ...(await serverSideTranslations(locale, ["common"])), - }, - }; -} - -export default Block; diff --git a/src/pages/cohorts.tsx b/src/pages/cohorts.tsx index a140df35..e080bcee 100644 --- a/src/pages/cohorts.tsx +++ b/src/pages/cohorts.tsx @@ -1,4 +1,4 @@ -import React, { ChangeEvent, useState, useEffect } from "react"; +import React, { useState, useEffect } from "react"; import KaTableComponent from "../components/KaTableComponent"; import { serverSideTranslations } from "next-i18next/serverSideTranslations"; import HeaderComponent from "@/components/HeaderComponent"; @@ -14,15 +14,7 @@ import { updateCohortUpdate, userCreate, } from "@/services/CohortService/cohortService"; -import { - CohortTypes, - Numbers, - QueryKeys, - Role, - SORT, - Status, - Storage, -} from "@/utils/app.constant"; +import { CohortTypes, Numbers, SORT, Status } from "@/utils/app.constant"; import EditIcon from "@mui/icons-material/Edit"; import DeleteIcon from "@mui/icons-material/Delete"; @@ -40,7 +32,6 @@ import { IChangeEvent } from "@rjsf/core"; import { RJSFSchema } from "@rjsf/utils"; import DynamicForm from "@/components/DynamicForm"; import useSubmittedButtonStore from "@/utils/useSharedState"; -import { useQueryClient } from "@tanstack/react-query"; import { useRouter } from "next/router"; import cohortSchema from "./cohortSchema.json"; import AddIcon from "@mui/icons-material/Add"; @@ -72,18 +63,10 @@ const Center: React.FC = () => { const router = useRouter(); const { t } = useTranslation(); - const adminInformation = useSubmittedButtonStore( - (state: any) => state.adminInformation - ); - const state = adminInformation?.customFields?.find( - (item: any) => item?.label === "STATES" - ); // handle states const [cohortAdminSchema] = useState(cohortASchema); const [selectedTenant, setSelectedTenant] = React.useState([]); - const [selectedDistrict, setSelectedDistrict] = React.useState([]); - const [selectedBlock, setSelectedBlock] = React.useState([]); const [selectedSort, setSelectedSort] = useState("Sort"); const [selectedFilter, setSelectedFilter] = useState("Active"); const [cohortData, setCohortData] = useState([]); @@ -91,9 +74,6 @@ const Center: React.FC = () => { const [confirmationModalOpen, setConfirmationModalOpen] = React.useState(false); const [selectedCohortId, setSelectedCohortId] = React.useState(""); - const [editModelOpen, setIsEditModalOpen] = React.useState(false); - const [confirmButtonDisable, setConfirmButtonDisable] = - React.useState(false); const [inputName, setInputName] = React.useState(""); const [loading, setLoading] = useState(undefined); const [userId, setUserId] = useState(""); @@ -110,9 +90,6 @@ const Center: React.FC = () => { const [pageSizeArray, setPageSizeArray] = React.useState([]); const [pagination, setPagination] = useState(true); const [sortBy, setSortBy] = useState(["createdAt", "asc"]); - const [selectedStateCode, setSelectedStateCode] = useState(""); - const [selectedDistrictCode, setSelectedDistrictCode] = useState(""); - const [selectedBlockCode, setSelectedBlockCode] = useState(""); const [formdata, setFormData] = useState(); const [totalCount, setTotalCound] = useState(0); const [editFormData, setEditFormData] = useState([]); @@ -404,14 +381,7 @@ const Center: React.FC = () => { useEffect(() => { const fetchData = async () => { - if ( - selectedBlockCode !== "" || - (selectedDistrictCode !== "" && selectedBlockCode === "") - ) { - await fetchUserList(); - } await fetchUserList(); - // getFormData(); }; fetchData(); @@ -619,7 +589,6 @@ const Center: React.FC = () => { setIsEditForm(true); } setLoading(false); - setConfirmButtonDisable(false); }; const handleDelete = (rowData: any) => { @@ -660,7 +629,6 @@ const Center: React.FC = () => { ]; const onCloseEditMOdel = () => { - setIsEditModalOpen(false); setUpdateBtnDisabled(true); }; @@ -668,10 +636,6 @@ const Center: React.FC = () => { setIsEditForm(false); setUpdateBtnDisabled(true); }; - const handleInputName = (event: ChangeEvent) => { - const updatedName = event.target.value; - setInputName(updatedName); - }; const handleChangeForm = (event: IChangeEvent) => { setUpdateBtnDisabled(false); @@ -727,7 +691,6 @@ const Center: React.FC = () => { showToastMessage(errorMessage, "error"); } finally { setLoading(false); - setConfirmButtonDisable(false); onCloseEditMOdel(); fetchUserList(); setIsEditForm(false); @@ -816,7 +779,6 @@ const Center: React.FC = () => { const formData = data?.formData; try { setLoading(true); - setConfirmButtonDisable(true); interface UserCreateData { name: string; @@ -864,7 +826,6 @@ const Center: React.FC = () => { showToastMessage(errorMessage, "error"); } finally { setLoading(false); - setConfirmButtonDisable(false); handleAddmodal(); onCloseEditMOdel(); setError([]); @@ -910,7 +871,6 @@ const Center: React.FC = () => { try { setLoading(true); - setConfirmButtonDisable(true); const cohortAdminRole = roleList?.result.find( (item: any) => item.code === "cohort_admin" @@ -948,7 +908,6 @@ const Center: React.FC = () => { showToastMessage(errorMessage, "error"); } finally { setLoading(false); - setConfirmButtonDisable(false); handleCloseModal(); onCloseEditMOdel(); fetchUserList(); @@ -962,9 +921,6 @@ const Center: React.FC = () => { searchPlaceHolder: t("COHORTS.SEARCH_COHORT"), showTenantCohortDropDown: true, isTenantShow: true, - selectedStateCode: selectedStateCode, - selectedDistrict: selectedDistrict, - selectedBlock: selectedBlock, selectedSort: selectedSort, selectedFilter: selectedFilter, statusArchived: true, @@ -979,13 +935,6 @@ const Center: React.FC = () => { statusValue: statusValue, setStatusValue: setStatusValue, showSort: true, - selectedBlockCode: selectedBlockCode, - setSelectedBlockCode: setSelectedBlockCode, - selectedDistrictCode: selectedDistrictCode, - setSelectedDistrictCode: setSelectedDistrictCode, - setSelectedStateCode: setSelectedStateCode, - setSelectedDistrict: setSelectedDistrict, - setSelectedBlock: setSelectedBlock, }; return ( diff --git a/src/pages/course-planner/index.tsx b/src/pages/course-planner/index.tsx index 7602a9e3..fd08fdab 100644 --- a/src/pages/course-planner/index.tsx +++ b/src/pages/course-planner/index.tsx @@ -1,17 +1,6 @@ import React, { useState, useEffect } from "react"; -import { - Box, - Card, - Typography, - Button, - useMediaQuery, - useTheme, - Grid, -} from "@mui/material"; +import { Box, Typography, Button, useTheme, Grid } from "@mui/material"; import FolderOutlinedIcon from "@mui/icons-material/FolderOutlined"; -import InsertLinkOutlinedIcon from "@mui/icons-material/InsertLinkOutlined"; -import CustomStepper from "@/components/Steper"; -import FilterSearchBar from "@/components/FilterSearchBar"; import { useRouter } from "next/router"; import { serverSideTranslations } from "next-i18next/serverSideTranslations"; import { useTranslation } from "next-i18next"; @@ -21,23 +10,13 @@ import Loader from "@/components/Loader"; import { getChannelDetails } from "@/services/coursePlanner"; import { getOptionsByCategory } from "@/utils/Helper"; import coursePlannerStore from "@/store/coursePlannerStore"; -import taxonomyStore from "@/store/tanonomyStore" +import taxonomyStore from "@/store/tanonomyStore"; const Foundation = () => { const router = useRouter(); const { t } = useTranslation(); - const theme = useTheme(); - const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm")); - const isMediumScreen = useMediaQuery(theme.breakpoints.between("sm", "md")); - const store = coursePlannerStore(); - const tStore = taxonomyStore(); - // State management const [selectedCardId, setSelectedCardId] = useState(null); - const [grade, setGrade] = useState(""); - const [medium, setMedium] = useState(""); - const [searchQuery, setSearchQuery] = useState(""); - const [selectedOption, setSelectedOption] = useState(""); - const [selectFilter, setSelectFilter] = useState(""); + const store = coursePlannerStore(); const [loading, setLoading] = useState(true); const [framework, setFramework] = useState([]); const setState = taxonomyStore((state) => state.setState); @@ -119,26 +98,6 @@ const Foundation = () => { router.push(`/stateDetails?cardId=${id}`); }; - const handleGradeChange = (event: any) => { - setGrade(event.target.value); - }; - - const handleMediumChange = (event: any) => { - setMedium(event.target.value); - }; - - const handleSearchChange = (event: any) => { - setSearchQuery(event.target.value); - }; - - const handleDropdownChange = (event: any) => { - setSelectedOption(event.target.value); - }; - - const handleFilter = (value: string) => { - setSelectFilter(value); - }; - const handleCopyLink = (state: string) => { const link = `${window.location.origin}/course-planner/${state}`; navigator.clipboard.writeText(link).then( @@ -227,8 +186,7 @@ const Foundation = () => { handleCopyLink(card.state); }} sx={{ minWidth: "auto", padding: 0 }} - > - + > diff --git a/src/pages/district.tsx b/src/pages/district.tsx deleted file mode 100644 index 26f6b671..00000000 --- a/src/pages/district.tsx +++ /dev/null @@ -1,729 +0,0 @@ -import AddDistrictModal from "@/components/AddDistrictModal"; -import ConfirmationModal from "@/components/ConfirmationModal"; -import HeaderComponent from "@/components/HeaderComponent"; -import Loader from "@/components/Loader"; -import PageSizeSelector from "@/components/PageSelector"; -import { showToastMessage } from "@/components/Toastify"; -import { getDistrictTableData } from "@/data/tableColumns"; -import { - createCohort, - getCohortList, -} from "@/services/CohortService/cohortService"; -import { getCohortList as getMyCohorts } from "@/services/GetCohortList"; -import { - createOrUpdateOption, - deleteOption, - getDistrictsForState, - updateCohort, -} from "@/services/MasterDataService"; -import { getUserDetailsInfo } from "@/services/UserList"; -import { - CohortTypes, - Numbers, - QueryKeys, - SORT, - Status, - Storage, -} from "@/utils/app.constant"; -import { transformLabel } from "@/utils/Helper"; -import { Pagination, Typography, useMediaQuery } from "@mui/material"; -import Box from "@mui/material/Box"; -import FormControl from "@mui/material/FormControl"; -import InputLabel from "@mui/material/InputLabel"; -import MenuItem from "@mui/material/MenuItem"; -import Select, { SelectChangeEvent } from "@mui/material/Select"; -import { Theme } from "@mui/system"; -import { useQueryClient } from "@tanstack/react-query"; -import { useTranslation } from "next-i18next"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import React, { useEffect, useState } from "react"; -import KaTableComponent from "../components/KaTableComponent"; - -type StateDetail = { - stateCode: string | undefined; - controllingField: string | undefined; - value: string; - label: string; -}; - -type DistrictDetail = { - status: Status; - cohortId(cohortId: any): unknown; - updatedBy: any; - createdBy: any; - updatedAt: any; - createdAt: any; - value: string; - label: string; - controllingField: string; -}; - -const District: React.FC = () => { - const { t } = useTranslation(); - const [districtData, setDistrictData] = useState([]); - const [modalOpen, setModalOpen] = useState(false); - const [selectedStateForEdit, setSelectedStateForEdit] = - useState(null); - const [selectedStateForDelete, setSelectedStateForDelete] = - useState(null); - const [confirmationDialogOpen, setConfirmationDialogOpen] = - useState(false); - const [districtFieldId, setDistrictFieldId] = useState("b61edfc6-3787-4079-86d3-37262bf23a9e"); - const [loading, setLoading] = useState(false); - const [selectedSort, setSelectedSort] = useState("Sort"); - const [pageCount, setPageCount] = useState(Numbers.ONE); - const [pageOffset, setPageOffset] = useState(Numbers.ZERO); - const [pageLimit, setPageLimit] = useState(Numbers.TEN); - const [pageSizeArray, setPageSizeArray] = useState([5, 10, 20, 50]); - const [sortBy, setSortBy] = useState<[string, string]>(["name", "asc"]); - const [searchKeyword, setSearchKeyword] = useState(""); - const [paginationCount, setPaginationCount] = useState(Numbers.ZERO); - const [stateCode, setStateCode] = useState(); - const [stateValue, setStateValue] = useState(""); - useState(""); - const [stateFieldId, setStateFieldId] = useState(""); - const [pagination, setPagination] = useState(true); - const [cohotIdForDelete, setCohortIdForDelete] = useState(""); - - const [districtsOptionRead, setDistrictsOptionRead] = useState([]); - const [districtCodeArr, setDistrictCodeArr] = useState([]); - const [districtNameArr, setDistrictNameArr] = useState([]); - const [cohortIdForEdit, setCohortIdForEdit] = useState(); - const [districtValueForDelete, setDistrictValueForDelete] = useState(""); - const [countOfBlocks, setCountOfBlocks] = useState(0); - const [cohortIdofState, setCohortIdofState] = useState(""); - const queryClient = useQueryClient(); - - const isMobile = useMediaQuery((theme: Theme) => - theme.breakpoints.down("sm") - ); - - useEffect(() => { - const fetchUserDetail = async () => { - let userId: any; - try { - if (typeof window !== "undefined" && window.localStorage) { - userId = localStorage.getItem(Storage.USER_ID); - } - - const response = await queryClient.fetchQuery({ - queryKey: [QueryKeys.USER_READ, userId, true], - queryFn: () => getUserDetailsInfo(userId, true), - }); - - const statesField = response.userData.customFields.find( - (field: { label: string }) => field.label === "STATES" - ); - - if (statesField) { - setStateValue(statesField.value); // state name - setStateCode(statesField.code); // state code - setStateFieldId(statesField?.fieldId); // field id of state - } - } catch (error) { - console.log(error); - } - }; - fetchUserDetail(); - }, []); - - const fetchDistricts = async () => { - try { - const data = await queryClient.fetchQuery({ - queryKey: [QueryKeys.FIELD_OPTION_READ, stateCode, "districts"], - queryFn: () => - getDistrictsForState({ - controllingfieldfk: stateCode, - 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 || "b61edfc6-3787-4079-86d3-37262bf23a9e"; - setDistrictFieldId(districtFieldID); - } catch (error) { - console.error("Error fetching districts", error); - } - }; - - useEffect(() => { - fetchDistricts(); - }, []); - // get cohort id of state - const getStatecohorts = async () => { - let userId: any; - try { - if (typeof window !== "undefined" && window.localStorage) { - userId = localStorage.getItem(Storage.USER_ID); - } - - const response = await queryClient.fetchQuery({ - queryKey: [QueryKeys.MY_COHORTS, userId], - queryFn: () => getMyCohorts(userId), - }); - - const cohortData = response?.result?.cohortData; - if (Array.isArray(cohortData)) { - const stateCohort = cohortData.find( - (cohort) => cohort.type === "STATE" - ); - - if (stateCohort) { - const cohortIdOfState = stateCohort.cohortId; - setCohortIdofState(cohortIdOfState); - } else { - console.error("No STATE type cohort found"); - } - } else { - console.error("cohortData is not an array or is undefined"); - } - } catch (error) { - console.error("Error fetching and filtering cohort districts", error); - setLoading(false); - } - }; - - useEffect(() => { - getStatecohorts(); - }, []); - - const getFilteredCohortData = async () => { - try { - setLoading(true); - - if (!districtsOptionRead.length || !districtNameArr.length) { - console.warn( - "districtsOptionRead or districtNameArr is empty, waiting for data..." - ); - setLoading(false); - return; - } - - const reqParams = { - limit: 0, - offset: 0, - filters: { - name: searchKeyword, - // states: stateCode, - // type: CohortTypes.DISTRICT, - }, - sort: sortBy, - }; - - // const response = await queryClient.fetchQuery({ - // queryKey: [ - // QueryKeys.FIELD_OPTION_READ, - // reqParams.limit, - // reqParams.offset, - // searchKeyword || "", - // stateCode, - // CohortTypes.DISTRICT, - // reqParams.sort.join(","), - // ], - // queryFn: () => getCohortList(reqParams), - // }); - - 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) - ); - - setDistrictData(filteredDistrictData); - - const totalCount = filteredDistrictData.length; - setPaginationCount(totalCount); - setPageCount(Math.ceil(totalCount / pageLimit)); - setLoading(false); - } catch (error) { - console.error("Error fetching and filtering cohort districts", error); - setLoading(false); - } - }; - - useEffect(() => { - if (districtsOptionRead.length && districtNameArr.length) { - getFilteredCohortData(); - } - }, [ - searchKeyword, - pageLimit, - pageOffset, - stateCode, - sortBy, - districtsOptionRead, - districtNameArr, - ]); - - const getBlockDataCohort = async () => { - try { - const reqParams = { - limit: 0, - offset: 0, - filters: { - // districts: districtValueForDelete, - // type: CohortTypes.BLOCK, - }, - sort: sortBy, - }; - // const response = await queryClient.fetchQuery({ - // queryKey: [ - // QueryKeys.FIELD_OPTION_READ, - // reqParams.limit, - // reqParams.offset, - // reqParams.filters.districts || "", - // CohortTypes.BLOCK, - // reqParams.sort.join(","), - // ], - // queryFn: () => getCohortList(reqParams), - // }); - - const response= await getCohortList(reqParams) - const activeBlocks = response?.results?.cohortDetails || []; - - const activeBlocksCount = activeBlocks.filter( - (block: { status: string }) => block.status === "active" - ).length; - setCountOfBlocks(activeBlocksCount); - } catch (error) { - console.error("Error fetching and filtering cohort districts", error); - setLoading(false); - } - }; - - useEffect(() => { - if (districtValueForDelete) { - getBlockDataCohort(); - } - }, [districtValueForDelete]); - - const handleEdit = (rowData: DistrictDetail) => { - setModalOpen(true); - - const cohortIdForEDIT = rowData.cohortId; - setCohortIdForEdit(cohortIdForEDIT); - - const updatedRowData = { - ...rowData, - stateCode: stateCode, - cohortId: cohortIdForEDIT, - }; - setSelectedStateForEdit(updatedRowData); - }; - const handleDelete = (rowData: DistrictDetail) => { - setSelectedStateForDelete(rowData); - const districtValue = rowData.value; - setDistrictValueForDelete(districtValue); - setCohortIdForDelete(rowData.cohortId); - setConfirmationDialogOpen(true); - }; - const handleSearch = (keyword: string) => { - setPageOffset(Numbers.ZERO); - setPageCount(Numbers.ONE); - setSearchKeyword(keyword); - }; - - const handleConfirmDelete = async () => { - if (selectedStateForDelete) { - try { - await deleteOption("districts", selectedStateForDelete.value); - setDistrictData((prev) => - prev.filter( - (district) => district.value !== selectedStateForDelete.value - ) - ); - showToastMessage(t("COMMON.DISTRICT_DELETED_SUCCESS"), "success"); - } catch (error) { - showToastMessage(t("COMMON.DISTRICT_DELETED_FAILURE"), "error"); - } - } - - //delete cohort - if (cohotIdForDelete) { - let cohortDetails = { - status: Status.ARCHIVED, - }; - const resp = await updateCohort(cohotIdForDelete, cohortDetails); - if (resp?.responseCode === 200) { - const cohort = filteredCohortOptionData()?.find( - (item: any) => item.cohortId == cohotIdForDelete - ); - if (cohort) { - cohort.status = Status.ARCHIVED; - } - } else { - console.log("Cohort Not Archived"); - } - setCohortIdForDelete(""); - } else { - console.log("No Cohort Selected"); - setCohortIdForDelete(""); - } - - setConfirmationDialogOpen(false); - }; - - //create cohort - const handleCreateCohortSubmit = async ( - name: string, - value: string, - controllingField: string, - DistrictId?: string, - extraArgument?: any - ) => { - const newDistrict = { - options: [ - { - controllingfieldfk: controllingField, - name, - value, - }, - ], - }; - try { - const response = await createOrUpdateOption(districtFieldId, newDistrict); - - if (response) { - queryClient.invalidateQueries({ - queryKey: [QueryKeys.FIELD_OPTION_READ, stateCode || "", "districts"], - }); - await fetchDistricts(); - } - } catch (error) { - console.error("Error adding district:", error); - } - - const queryParameters = { - name: name, - type: CohortTypes.DISTRICT, - status: Status.ACTIVE, - parentId: cohortIdofState, - customFields: [ - { - fieldId: stateFieldId, - value: [stateCode], - }, - ], - }; - - try { - const cohortCreateResponse = await createCohort(queryParameters); - if (cohortCreateResponse) { - filteredCohortOptionData(); - showToastMessage(t("COMMON.DISTRICT_ADDED_SUCCESS"), "success"); - } else if (cohortCreateResponse?.responseCode === 409) { - showToastMessage(t("COMMON.DISTRICT_DUPLICATION_FAILURE"), "error"); - } - } catch (error) { - console.error("Error creating cohort:", error); - showToastMessage(t("COMMON.DISTRICT_DUPLICATION_FAILURE"), "error"); - } - setModalOpen(false); - setSelectedStateForEdit(null); - }; - - //update cohort - const handleUpdateCohortSubmit = async ( - name: string, - value: string, - controllingField: string, - DistrictId?: string, - extraArgument?: any - ) => { - const newDistrict = { - options: [ - { - controllingfieldfk: controllingField, - name, - value, - }, - ], - }; - - try { - const response = await createOrUpdateOption(districtFieldId, newDistrict); - - if (response) { - setDistrictsOptionRead((prevDistricts: any[]) => - prevDistricts.map((district: { value: string | undefined; }) => - district.value === DistrictId - ? { ...district, name, value } - : district - ) - ); - queryClient.invalidateQueries({ - queryKey: [QueryKeys.FIELD_OPTION_READ, stateCode, "districts"], - }); - } - } catch (error) { - console.error("Error adding district:", error); - } - - const queryParameters = { - name: name, - }; - - try { - const cohortCreateResponse = await updateCohort( - cohortIdForEdit, - queryParameters - ); - - if (cohortCreateResponse) { - queryClient.invalidateQueries({ - queryKey: [QueryKeys.FIELD_OPTION_READ, stateCode, "districts"], - }); - - showToastMessage(t("COMMON.DISTRICT_UPDATED_SUCCESS"), "success"); - } else if (cohortCreateResponse.responseCode === 409) { - showToastMessage(t("COMMON.DISTRICT_DUPLICATION_FAILURE"), "error"); - } - } catch (error) { - console.error("Error creating cohort:", error); - showToastMessage(t("COMMON.DISTRICT_DUPLICATION_FAILURE"), "error"); - } - - setModalOpen(false); - setSelectedStateForEdit(null); - }; - - const handleChangePageSize = (event: SelectChangeEvent) => { - const newSize = Number(event.target.value); - setPageSizeArray((prev) => - prev.includes(newSize) ? prev : [...prev, newSize] - ); - setPageLimit(newSize); - }; - const handleSortChange = async (event: SelectChangeEvent) => { - const sortOrder = - event.target.value === "Z-A" ? SORT.DESCENDING : SORT.ASCENDING; - setSortBy(["name", sortOrder]); - setSelectedSort(event.target.value); - }; - - const handlePaginationChange = ( - event: React.ChangeEvent, - value: number - ) => { - setPageOffset(value - 1); - }; - - 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 = districtData.map((item) => ({ - ...item, - label: transformLabels(item.label), - })); - - return transformedData.slice(startIndex, endIndex); - }; - const PagesSelector = () => ( - - - - ); - - const PageSizeSelectorFunction = () => ( - - - - ); - - return ( - <> - setModalOpen(false)} - onSubmit={(name, value, controllingField) => { - if (selectedStateForEdit) { - handleUpdateCohortSubmit( - name, - value, - controllingField, - districtFieldId, - selectedStateForEdit?.value - ); - } else { - handleCreateCohortSubmit( - name, - value, - controllingField, - districtFieldId - ); - } - }} - fieldId={districtFieldId} - initialValues={ - selectedStateForEdit - ? { - name: selectedStateForEdit.label, - value: selectedStateForEdit.value, - controllingField: selectedStateForEdit.stateCode, - } - : {} - } - /> - 0 - ? t("COMMON.ARE_YOU_SURE_DELETE", { - block: `${countOfBlocks}`, - }) - : t("COMMON.NO_ACTIVE_BLOCKS_DELETE") - } - handleAction={handleConfirmDelete} - buttonNames={{ - primary: t("COMMON.DELETE"), - secondary: t("COMMON.CANCEL"), - }} - disableDelete={countOfBlocks > 0} - handleCloseModal={() => setConfirmationDialogOpen(false)} - /> - { - setModalOpen(true); - setSelectedStateForEdit(null); - }} - > - {loading ? ( - - - - ) : ( - <> - - - {stateValue} - - - - - {filteredCohortOptionData().length > 0 ? ( - = Numbers.FIVE} - PagesSelector={PagesSelector} - PageSizeSelector={PageSizeSelectorFunction} - pageSizes={pageSizeArray} - pagination={pagination} - onEdit={handleEdit} - onDelete={handleDelete} - extraActions={[]} - noDataMessage={t("COMMON.DISTRICT_NOT_FOUND")} - /> - ) : ( - !loading && ( - - - {t("COMMON.DISTRICT_NOT_FOUND")} - - - ) - )} - - )} - - - ); -}; - -export default District; - -export const getServerSideProps = async (context: any) => { - return { - props: { - ...(await serverSideTranslations(context.locale, ["common", "master"])), - }, - }; -}; diff --git a/src/pages/faciliator.tsx b/src/pages/faciliator.tsx deleted file mode 100644 index 88e6c8e3..00000000 --- a/src/pages/faciliator.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import React from "react"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import UserTable from "@/components/UserTable"; -import { useTranslation } from "next-i18next"; -import { Role, FormContextType } from "@/utils/app.constant"; -import CommonUserModal from "@/components/CommonUserModal"; -import useSubmittedButtonStore from "@/utils/useSharedState"; - -const Faciliator: React.FC = () => { - const { t } = useTranslation(); - const [openAddFacilitatorModal, setOpenAddFacilitatorModal] = - React.useState(false); - const [submitValue, setSubmitValue] = React.useState(false); - const setSubmittedButtonStatus = useSubmittedButtonStore( - (state: any) => state.setSubmittedButtonStatus - ); - - const handleOpenAddFacilitatorModal = () => { - setOpenAddFacilitatorModal(true); - }; - const handleModalSubmit = (value: boolean) => { - setSubmitValue(true); - }; - const handleCloseAddFacilitatorModal = () => { - setSubmittedButtonStatus(false); - setOpenAddFacilitatorModal(false); - }; - - const handleAddFaciliatorClick = () => { - handleOpenAddFacilitatorModal(); - }; - return ( - <> - - {/* */} - - ); -}; - -export async function getStaticProps({ locale }: any) { - return { - props: { - ...(await serverSideTranslations(locale, ["common"])), - }, - }; -} - -export default Faciliator; diff --git a/src/pages/facilitator.tsx b/src/pages/facilitator.tsx deleted file mode 100644 index 472268f6..00000000 --- a/src/pages/facilitator.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import React from "react"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import UserTable from "@/components/UserTable"; -import { useTranslation } from "next-i18next"; -import { Role, FormContextType } from "@/utils/app.constant"; -import CommonUserModal from "@/components/CommonUserModal"; -import useSubmittedButtonStore from "@/utils/useSharedState"; - -const Facilitator: React.FC = () => { - const { t } = useTranslation(); - const [openAddFacilitatorModal, setOpenAddFacilitatorModal] = - React.useState(false); - const [submitValue, setSubmitValue] = React.useState(false); - const setSubmittedButtonStatus = useSubmittedButtonStore( - (state: any) => state.setSubmittedButtonStatus - ); - - const handleOpenAddFacilitatorModal = () => { - setOpenAddFacilitatorModal(true); - }; - const handleModalSubmit = (value: boolean) => { - setSubmitValue(true); - }; - const handleCloseAddFacilitatorModal = () => { - setSubmittedButtonStatus(false); - setOpenAddFacilitatorModal(false); - }; - - const handleAddFaciliatorClick = () => { - handleOpenAddFacilitatorModal(); - }; - return ( - <> - - {/* */} - - ); -}; - -export async function getStaticProps({ locale }: any) { - return { - props: { - ...(await serverSideTranslations(locale, ["common"])), - }, - }; -} - -export default Facilitator; diff --git a/src/pages/mainCourse.tsx b/src/pages/mainCourse.tsx deleted file mode 100644 index 0b3cfff5..00000000 --- a/src/pages/mainCourse.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import { useTranslation } from "next-i18next"; -import ProtectedRoute from "../components/ProtectedRoute"; -import HeaderComponent from "@/components/HeaderComponent"; - -const MainCourse = () => { - const { t } = useTranslation(); - return ( - - <> -

{t("SIDEBAR.MAIN_COURSE")}

- - -
- ); -}; - -export default MainCourse; -export async function getStaticProps({ locale }: any) { - return { - props: { - ...(await serverSideTranslations(locale, ["common"])), - }, - }; -} diff --git a/src/pages/resourceList.tsx b/src/pages/resourceList.tsx deleted file mode 100644 index a06ae5d0..00000000 --- a/src/pages/resourceList.tsx +++ /dev/null @@ -1,130 +0,0 @@ -import React, { useEffect, useState } from "react"; -import { Grid, Typography, Box, IconButton } from "@mui/material"; -import ArrowBackIcon from "@mui/icons-material/ArrowBack"; // Import the back arrow icon -import ResourceCard from "../components/ResourceCard"; -import taxonomyStore from "@/store/tanonomyStore"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import { ResourceType } from "@/utils/app.constant"; -import { useTranslation } from "next-i18next"; - -const ResourceList = () => { - const [learnersPreReq, setLearnersPreReq] = useState([]); - const [learnersPostReq, setLearnersPostReq] = useState([]); - const [facilitatorsPreReq, setFacilitatorsPreReq] = useState([]); - - const tstore = taxonomyStore(); - const { t } = useTranslation(); - - useEffect(() => { - const fetchData = async () => { - const resources = tstore.resources; - - const fetchedLearningResources = resources.learningResources || []; - - const preReqs = fetchedLearningResources.filter( - (item: any) => item.type === ResourceType.PREREQUISITE - ); - const postReqs = fetchedLearningResources.filter( - (item: any) => item.type === ResourceType.POSTREQUISITE - ); - const facilitatorsReqs = fetchedLearningResources.filter( - (item: any) => !item.type - ); - - setLearnersPreReq(preReqs); - setLearnersPostReq(postReqs); - setFacilitatorsPreReq(facilitatorsReqs); - }; - - fetchData(); - }, [tstore.resources]); - - return ( - - {tstore.taxonomyType} - - window.history.back()}> - - - - {/* Course Name */} - - {tstore?.resources?.name} - - - - - - {t("COURSE_PLANNER.LEARNERS_PREREQISITE")} - - {learnersPreReq.length > 0 ? ( - - {learnersPreReq.map((item, index) => ( - - - - ))} - - ) : ( - - {t("COURSE_PLANNER.NO_DATA_PRE")} - - )} - - - {t("COURSE_PLANNER.LEARNERS_POSTREQISITE")} - - {learnersPostReq.length > 0 ? ( - - {learnersPostReq.map((item, index) => ( - - - - ))} - - ) : ( - - {t("COURSE_PLANNER.NO_DATA_POST")} - - )} - - - {t("COURSE_PLANNER.FACILITATORS")} - - {facilitatorsPreReq.length > 0 ? ( - - {facilitatorsPreReq.map((item, index) => ( - - - - ))} - - ) : ( - {t("COURSE_PLANNER.NO_DATA")} - )} - - - ); -}; - -export default ResourceList; - -export async function getStaticProps({ locale }: { locale: string }) { - return { - props: { - ...(await serverSideTranslations(locale, ["common"])), - }, - }; -} diff --git a/src/pages/state.tsx b/src/pages/state.tsx deleted file mode 100644 index 4bae39c4..00000000 --- a/src/pages/state.tsx +++ /dev/null @@ -1,358 +0,0 @@ -import HeaderComponent from "@/components/HeaderComponent"; -import PageSizeSelector from "@/components/PageSelector"; -import { showToastMessage } from "@/components/Toastify"; -import { - createCohort, - getCohortList, -} from "@/services/CohortService/cohortService"; -import { - createOrUpdateOption, - deleteOption, - getStateBlockDistrictList, -} from "@/services/MasterDataService"; -import { Numbers, QueryKeys, SORT } from "@/utils/app.constant"; -import { transformLabel } from "@/utils/Helper"; -import { - Box, - Pagination, - SelectChangeEvent, - Typography, - useMediaQuery, -} from "@mui/material"; -import { useTranslation } from "next-i18next"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import React, { useEffect, useState } from "react"; -import KaTableComponent from "../components/KaTableComponent"; -import { useQueryClient } from "@tanstack/react-query"; -import { getStateDataMaster } from "@/data/tableColumns"; -import { Theme } from "@mui/system"; -import Loader from "@/components/Loader"; - -export interface StateDetail { - updatedAt: any; - createdAt: any; - createdBy: string; - updatedBy: string; - label: string | undefined; - name: string; - value: string; -} - -const State: React.FC = () => { - const { t } = useTranslation(); - const [stateData, setStateData] = useState([]); - const [loading, setLoading] = useState(false); - const [confirmationDialogOpen, setConfirmationDialogOpen] = - useState(false); - const [addStateModalOpen, setAddStateModalOpen] = useState(false); - const [selectedStateForDelete, setSelectedStateForDelete] = - useState(null); - const [selectedStateForEdit, setSelectedStateForEdit] = - useState(null); - const [searchKeyword, setSearchKeyword] = useState(""); - const [fieldId, setFieldId] = useState(""); - const [sortBy, setSortBy] = useState<[string, string]>(["name", "asc"]); - const [pageCount, setPageCount] = useState(Numbers.ONE); - const [pageOffset, setPageOffset] = useState(Numbers.ZERO); - const [pageLimit, setPageLimit] = useState(Numbers.TEN); - const [pageSizeArray, setPageSizeArray] = useState([5, 10]); - const [selectedSort, setSelectedSort] = useState("Sort"); - const [paginationCount, setPaginationCount] = useState(Numbers.ZERO); - const [pagination, setPagination] = useState(true); - const [stateDataOption, setStateDataOptinon] = useState([]); - const [stateCodArrray, setStateCodeArr] = useState([]); - const [stateNameArray, setStateNameArr] = useState([]); - const queryClient = useQueryClient(); - - const isMobile = useMediaQuery((theme: Theme) => - theme.breakpoints.down("sm") - ); - const fetchStateData = async () => { - try { - const limit = pageLimit; - const offset = pageOffset * limit; - const data = { - limit: limit, - offset: offset, - fieldName: "states", - optionName: searchKeyword || "", - sort: sortBy, - }; - - const resp = await queryClient.fetchQuery({ - queryKey: [ - QueryKeys.FIELD_OPTION_READ, - data.limit, - data.offset, - data.fieldName, - data.optionName, - data.sort.join(","), - ], - queryFn: () => getStateBlockDistrictList(data), - }); - - const states = resp?.result?.values || []; - setStateDataOptinon(states); - const stateNameArra = states.map((item: any) => item.label); - setStateNameArr(stateNameArra); - const stateCodeArra = states.map((item: any) => item.value); - setStateCodeArr(stateCodeArra); - if (resp?.result?.fieldId) { - setFieldId(resp.result.fieldId); - } else { - console.error("Unexpected fieldId:", resp?.result?.fieldId); - } - } catch (error) { - console.error("Error fetching state data", error); - } - }; - - useEffect(() => { - fetchStateData(); - }, []); - - const getStatecohorts = async () => { - try { - setLoading(true); - const reqParams = { - limit: 0, - offset: 0, - filters: { - name: searchKeyword, - type: "STATE", - }, - sort: sortBy, - }; - - const response = await queryClient.fetchQuery({ - queryKey: [ - QueryKeys.FIELD_OPTION_READ, - reqParams.limit, - reqParams.offset, - searchKeyword || "", - "STATE", - reqParams.sort.join(","), - ], - queryFn: () => getCohortList(reqParams), - }); - - const statecohortDetails = response?.results?.cohortDetails || []; - const filteredStateData = statecohortDetails - .map((stateDetail: any) => { - const transformedName = transformLabel(stateDetail.name); - const matchingState = stateDataOption.find( - (state: { label: string }) => state.label === transformedName - ); - return { - label: transformedName, - value: matchingState ? matchingState.value : null, - createdAt: stateDetail.createdAt, - updatedAt: stateDetail.updatedAt, - createdBy: stateDetail.createdBy, - updatedBy: stateDetail.updatedBy, - cohortId: stateDetail.cohortId, - }; - }) - .filter((state: { label: any }) => - stateNameArray.includes(state.label) - ); - setStateData(filteredStateData); - setLoading(false); - } catch (error) { - console.error("Error fetching and filtering cohort states", error); - } finally { - setLoading(false); - } - }; - - useEffect(() => { - if (stateDataOption.length > 0 && stateNameArray.length > 0) { - getStatecohorts(); - } - }, [ - stateDataOption, - stateNameArray, - searchKeyword, - pageLimit, - pageOffset, - sortBy, - ]); - - const handleEdit = (rowData: StateDetail) => { - setSelectedStateForEdit(rowData); - setAddStateModalOpen(true); - }; - const handleDelete = (rowData: StateDetail) => { - setSelectedStateForDelete(rowData); - setConfirmationDialogOpen(true); - }; - const handleSortChange = async (event: SelectChangeEvent) => { - const sortOrder = - event.target.value === "Z-A" ? SORT.DESCENDING : SORT.ASCENDING; - setSortBy(["name", sortOrder]); - setSelectedSort(event.target.value); - }; - const handleConfirmDelete = async () => { - if (selectedStateForDelete) { - try { - await deleteOption("states", selectedStateForDelete.value); - setStateData((prevStateData) => - prevStateData.filter( - (state) => state.value !== selectedStateForDelete.value - ) - ); - showToastMessage(t("COMMON.STATE_DELETED_SUCCESS"), "success"); - } catch (error) { - console.error("Error deleting state", error); - showToastMessage(t("COMMON.STATE_DELETED_FAILURE"), "error"); - } - setConfirmationDialogOpen(false); - } - }; - const handleSearch = (keyword: string) => { - setSearchKeyword(keyword); - }; - const handleAddStateClick = () => { - setSelectedStateForEdit(null); - setAddStateModalOpen(true); - }; - const handleAddStateSubmit = async ( - name: string, - value: string, - selectedState: any - ) => { - const newState = { - options: [{ name, value }], - }; - try { - if (fieldId) { - const isUpdating = selectedState !== null; - const response = await createOrUpdateOption(fieldId, newState); - const queryParameters = { - name: name, - type: "STATE", - status: "active", - parentId: null, - customFields: [], - }; - if (!isUpdating) { - await createCohort(queryParameters); - } - if (response) { - await fetchStateData(); - const successMessage = isUpdating - ? t("COMMON.STATE_UPDATED_SUCCESS") - : t("COMMON.STATE_ADDED_SUCCESS"); - showToastMessage(successMessage, "success"); - } else { - console.error("Failed to create/update state:", response); - showToastMessage(t("COMMON.STATE_OPERATION_FAILURE"), "error"); - } - } - } catch (error) { - console.error("Error creating/updating state:", error); - showToastMessage(t("COMMON.STATE_OPERATION_FAILURE"), "error"); - } - setAddStateModalOpen(false); - }; - const handleChangePageSize = (event: SelectChangeEvent) => { - const newSize = Number(event.target.value); - setPageSizeArray((prev) => - prev.includes(newSize) ? prev : [...prev, newSize] - ); - setPageLimit(newSize); - }; - const handlePaginationChange = ( - event: React.ChangeEvent, - value: number - ) => { - setPageOffset(value - 1); - }; - const PagesSelector = () => ( - - - - ); - const PageSizeSelectorFunction = () => ( - - - - ); - return ( - - {loading ? ( - - - - ) : ( -
- {stateData.length > 0 ? ( - = Numbers.FIVE} - PagesSelector={PagesSelector} - pagination={pagination} - PageSizeSelector={PageSizeSelectorFunction} - pageSizes={pageSizeArray} - onEdit={handleEdit} - extraActions={[]} - /> - ) : ( - !loading && ( - - - {t("COMMON.STATE_NOT_FOUND")} - - - ) - )} -
- )} -
- ); -}; -export default State; -export const getServerSideProps = async ({ locale }: { locale: string }) => { - return { - props: { - ...(await serverSideTranslations(locale, ["common", "master"])), - }, - }; -}; diff --git a/src/pages/stateDetails.tsx b/src/pages/stateDetails.tsx deleted file mode 100644 index bdacb80d..00000000 --- a/src/pages/stateDetails.tsx +++ /dev/null @@ -1,184 +0,0 @@ -import React, { useState, useEffect } from "react"; -import { - Box, - Card, - Typography, - Button, - IconButton, - useTheme, - useMediaQuery, - Grid, -} from "@mui/material"; -import FolderOutlinedIcon from "@mui/icons-material/FolderOutlined"; -import InsertLinkOutlinedIcon from "@mui/icons-material/InsertLinkOutlined"; -import ArrowBackIcon from "@mui/icons-material/ArrowBack"; -import cardData from "@/data/cardData"; -import { useRouter } from "next/router"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import FilterSearchBar from "@/components/FilterSearchBar"; -import CustomStepper from "@/components/Steper"; -import { useTranslation } from "next-i18next"; -import Loader from "@/components/Loader"; -import { CircularProgressbar, buildStyles } from "react-circular-progressbar"; -import coursePlannerStore from "@/store/coursePlannerStore"; -import taxonomyStore from "@/store/tanonomyStore"; - -const StateDetails = () => { - const router = useRouter(); - const { boardId, cardId } = router.query; - const { t } = useTranslation(); - const theme = useTheme(); - const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm")); - const store = coursePlannerStore(); - const tStore = taxonomyStore(); - // State management - const [loading, setLoading] = useState(true); - const [grade, setGrade] = useState(""); - const [medium, setMedium] = useState(""); - const [searchQuery, setSearchQuery] = useState(""); - const [selectedOption, setSelectedOption] = useState(""); - const [card, setCard] = useState(null); - const [boards, setBoards] = useState([]); - const setBoard = taxonomyStore((state) => state.setBoard); - - useEffect(() => { - const fetchData = async () => { - setTimeout(() => { - const foundCard = cardData.find((c) => c.id === cardId); - setCard(foundCard); - - const channel = store?.boards; - setBoards(channel); - localStorage.removeItem("overallCommonSubjects") - setLoading(false); - }, 1000); - }; - - fetchData(); - }, [cardId]); - - const handleBackClick = () => { - router.back(); - }; - - const handleGradeChange = (event: any) => { - setGrade(event.target.value); - }; - - const handleMediumChange = (event: any) => { - setMedium(event.target.value); - }; - - const handleSearchChange = (event: any) => { - setSearchQuery(event.target.value); - }; - - const handleDropdownChange = (event: any) => { - setSelectedOption(event.target.value); - }; - - const handleBoardClick = (board: string, boardName: string) => { - setBoard(boardName); - router.push({ - pathname: "/subjectDetails", - query: { boardDetails: board, boardName: boardName }, - }); - }; - - const handleCopyLink = (state: string) => { - const link = `${window.location.origin}/course-planner/foundation/${state}`; - navigator.clipboard.writeText(link).then( - () => { - alert("Link copied to clipboard"); - }, - (err) => { - console.error("Failed to copy link: ", err); - } - ); - }; - - if (loading) { - return ; - } - - if (!card) { - return {t("COURSE_PLANNER.DATA_NOT_FOUND")}; - } - - return ( - - - - - - - {tStore.state} - - - - - {boards.map((board: any, index: number) => ( - - { - handleBoardClick(board, board?.name); - }} - > - - - - - {board?.name} - - - - - - - - - - - ))} - - - ); -}; - -export default StateDetails; - -export async function getStaticProps({ locale }: { locale: string }) { - return { - props: { - ...(await serverSideTranslations(locale, ["common"])), - }, - }; -} diff --git a/src/pages/subjectDetails.tsx b/src/pages/subjectDetails.tsx deleted file mode 100644 index abd73e7b..00000000 --- a/src/pages/subjectDetails.tsx +++ /dev/null @@ -1,563 +0,0 @@ -import React, { useState, useEffect, MouseEvent } from "react"; -import { useRouter } from "next/router"; -import { - Box, - Card as MuiCard, - Typography, - Button, - CircularProgress, - IconButton, - MenuItem, - Select, -} from "@mui/material"; -import FolderOutlinedIcon from "@mui/icons-material/FolderOutlined"; -import InsertLinkOutlinedIcon from "@mui/icons-material/InsertLinkOutlined"; -import ArrowBackIcon from "@mui/icons-material/ArrowBack"; -import cardData from "@/data/cardData"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import FilterSearchBar from "@/components/FilterSearchBar"; -import Loader from "@/components/Loader"; -import { CircularProgressbar, buildStyles } from "react-circular-progressbar"; -import { getFrameworkDetails } from "@/services/coursePlanner"; -import coursePlannerStore from "@/store/coursePlannerStore"; -import taxonomyStore from "@/store/tanonomyStore"; -import { - filterAndMapAssociations, - findCommonAssociations, - getAssociationsByCodeNew, - getOptionsByCategory, -} from "@/utils/Helper"; - -// Define Card interface -interface Card { - id: number; - state: string; - boardsUploaded: number; - totalBoards: number; - boards: string[]; - subjects: string[]; -} - -interface FoundCard { - id: string; - state: string; - boardsUploaded: number; - totalBoards: number; - details: string; - boards: string[]; - subjects: string[]; -} - -const SubjectDetails = () => { - const router = useRouter(); - const { boardDetails, boardName } = router.query as { - boardDetails?: any; - boardName?: any; - }; - const tStore = taxonomyStore(); - const store = coursePlannerStore(); - const [loading, setLoading] = useState(true); - const [card, setCard] = useState(null); - const [subject, setSubject] = useState(); - const [boardAssociations, setBoardAssociations] = useState([]); - const [medium, setMedium] = useState([]); - const [mediumOptions, setMediumOptions] = useState([]); - const [selectedmedium, setSelectedmedium] = useState(); - const [mediumAssociations, setMediumAssociations] = useState([]); - const [gradeAssociations, setGradeAssociations] = useState([]); - const [typeAssociations, setTypeAssociations] = useState([]); - const [grade, setGrade] = useState([]); - const [selectedgrade, setSelectedgrade] = useState(); - const [gradeOptions, setGradeOptions] = useState([]); - const [typeOptions, setTypeOptions] = useState([]); - const [type, setType] = useState([]); - const [selectedtype, setSelectedtype] = useState(); - const setTaxanomySubject = coursePlannerStore( - (state) => state.setTaxanomySubject - ); - const setTaxonomyMedium = taxonomyStore((state) => state.setTaxonomyMedium); - const setTaxonomyGrade = taxonomyStore((state) => state.setTaxonomyGrade); - const setTaxonomyType = taxonomyStore((state) => state.setTaxonomyType); - const setTaxonomySubject = taxonomyStore((state) => state.setTaxonomySubject); - - useEffect(() => { - const subjects = localStorage.getItem('overallCommonSubjects'); - - if (subjects) { - try { - const parsedData = JSON.parse(subjects); - setSubject(parsedData); - } catch (error) { - console.error("Failed to parse subjects from localStorage:", error); - } - } else { - console.log("No subjects found in localStorage."); - setSubject([]); - } - }, []); - - - - useEffect(() => { - const fetchFrameworkDetails = async () => { - if (typeof boardDetails === "string") { - try { - const getMedium = await getOptionsByCategory( - store?.framedata, - "medium" - ); - const boardAssociations = await getAssociationsByCodeNew( - store?.boards, - boardName - ); - setBoardAssociations(boardAssociations); - const commonMediumInState = getMedium - .filter((item1: { code: string }) => - store?.stateassociations.some( - (item2: { code: string; category: string }) => - item2.code === item1.code && item2.category === "medium" - ) - ) - .map( - (item1: { name: string; code: string; associations: any[] }) => ({ - name: item1.name, - code: item1.code, - associations: item1.associations, - }) - ); - - const commonMediumInBoard = getMedium - .filter((item1: { code: any }) => - boardAssociations.some( - (item2: { code: any; category: string }) => - item2.code === item1.code && item2.category === "medium" - ) - ) - .map((item1: { name: any; code: any; associations: any }) => ({ - name: item1.name, - code: item1.code, - associations: item1.associations, - })); - console.log(`commonMediumInState`, commonMediumInState); - console.log(`commonMediumInBoard`, commonMediumInBoard); - - const commonMediumData = findCommonAssociations( - commonMediumInState, - commonMediumInBoard - ); - setMediumOptions(commonMediumData); - setMedium(commonMediumInState); - } catch (err) { - console.error("Failed to fetch framework details"); - } finally { - setLoading(false); - } - } else { - console.error("Invalid boardId"); - setLoading(false); - } - }; - - fetchFrameworkDetails(); - }, [boardName]); - - if (loading) { - return ; - } - - const handleBackClick = () => { - router.back(); - }; - - const handleCopyLink = (subject: any) => {}; - - const handleCardClick = (subject: any) => { - setTaxonomySubject(subject?.name) - router.push(`/importCsv?subject=${encodeURIComponent(subject?.name)}`); - - setTaxanomySubject(subject?.name); - }; - - const handleMediumChange = (event: any) => { - const medium = event.target.value; - setSelectedmedium(medium); - setTaxonomyMedium(medium); - setSelectedgrade([null]); - setSelectedtype([null]); - setSubject([null]); - - if (medium) { - const getGrades = getOptionsByCategory(store?.framedata, "gradeLevel"); - const mediumAssociations = getAssociationsByCodeNew(mediumOptions, medium); - setMediumAssociations(mediumAssociations); - - console.log(getGrades); - - const commonGradeInState = filterAndMapAssociations( - "gradeLevel", - getGrades, - store?.stateassociations, - "code" - ); - const commonGradeInBoard = filterAndMapAssociations( - "gradeLevel", - getGrades, - boardAssociations, - "code" - ); - const commonGradeInMedium = filterAndMapAssociations( - "gradeLevel", - getGrades, - mediumAssociations, - "code" - ); - - const commonGradeInStateBoard = findCommonAssociations( - commonGradeInState, - commonGradeInBoard - ); - const overAllCommonGrade = findCommonAssociations( - commonGradeInStateBoard, - commonGradeInMedium - ); - - setGrade(overAllCommonGrade); - setGradeOptions(overAllCommonGrade); - } - }; - - const handleGradeChange = (event: any) => { - const grade = event.target.value; - setTaxonomyGrade(grade); - setSelectedgrade(grade); - if (grade) { - const gradeAssociations = getAssociationsByCodeNew(gradeOptions, grade); - setGradeAssociations(gradeAssociations); - const type = getOptionsByCategory(store?.framedata, "courseType"); - console.log(type); - - const commonTypeInState = filterAndMapAssociations( - "courseType", - type, - store?.stateassociations, - "code" - ); - const commonTypeInBoard = filterAndMapAssociations( - "courseType", - type, - boardAssociations, - "code" - ); - const commonTypeInMedium = filterAndMapAssociations( - "courseType", - type, - mediumAssociations, - "code" - ); - const commonTypeInGrade = filterAndMapAssociations( - "courseType", - type, - gradeAssociations, - "code" - ); - - const commonTypeData = findCommonAssociations( - commonTypeInState, - commonTypeInBoard - ); - const commonType2Data = findCommonAssociations( - commonTypeInMedium, - commonTypeInGrade - ); - const commonType3Data = findCommonAssociations( - commonTypeData, - commonType2Data - ); - - console.log(`commonTypeOverall`, commonType3Data); - setTypeOptions(commonType3Data); - setType(commonType3Data); - } - }; - - const handleTypeChange = (event: any) => { - const type = event.target.value; - setTaxonomyType(type); - setSelectedtype(type); - - if (type) { - const typeAssociations = getAssociationsByCodeNew(typeOptions, type); - setTypeAssociations(typeAssociations); - const subject = getOptionsByCategory(store?.framedata, "subject"); - - console.log(subject); - - const commonTypeInState = filterAndMapAssociations( - "subject", - subject, - store?.stateassociations, - "code" - ); - const commonTypeInBoard = filterAndMapAssociations( - "subject", - type, - boardAssociations, - "code" - ); - const commonTypeInMedium = filterAndMapAssociations( - "subject", - subject, - mediumAssociations, - "code" - ); - const commonTypeInGrade = filterAndMapAssociations( - "subject", - subject, - gradeAssociations, - "code" - ); - const commonTypeInType = filterAndMapAssociations( - "subject", - subject, - typeAssociations, - "code" - ); - - const findCommonAssociations = (array1: any[], array2: any[]) => { - return array1.filter((item1: { code: any }) => - array2.some((item2: { code: any }) => item1.code === item2.code) - ); - }; - - const findOverallCommonSubjects = (arrays: any[]) => { - const nonEmptyArrays = arrays.filter( - (array: string | any[]) => array && array.length > 0 - ); - - if (nonEmptyArrays.length === 0) return []; - - let commonSubjects = nonEmptyArrays[0]; - - for (let i = 1; i < nonEmptyArrays.length; i++) { - commonSubjects = findCommonAssociations( - commonSubjects, - nonEmptyArrays[i] - ); - - if (commonSubjects.length === 0) return []; - } - - return commonSubjects; - }; - - const arrays = [ - commonTypeInState, - commonTypeInBoard, - commonTypeInMedium, - commonTypeInGrade, - commonTypeInType, - ]; - - const overallCommonSubjects = findOverallCommonSubjects(arrays); - - setSubject(overallCommonSubjects); - localStorage.setItem("overallCommonSubjects", JSON.stringify(overallCommonSubjects)) - } - }; - - return ( - - - - - - - - - - - - - - - - - - - {boardName} - - - - - {subject && subject.length > 1 ? ( - subject.map((subj: any, index: any) => ( - handleCardClick(subj)} - > - - - {subj?.name} - - - - - {/* {subj.uploaded} / {subj.total} {"topics uploaded"} */} - - - - - - - )) - ) : ( - - Select Medium, Grade and Type - - )} - - - ); -}; - -export default SubjectDetails; - -export async function getStaticProps({ locale }: { locale: string }) { - return { - props: { - ...(await serverSideTranslations(locale, ["common"])), - }, - }; -} diff --git a/src/pages/team-leader.tsx b/src/pages/team-leader.tsx deleted file mode 100644 index 017acdc1..00000000 --- a/src/pages/team-leader.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import React from "react"; -import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import UserTable from "@/components/UserTable"; -import { useTranslation } from "next-i18next"; -import { Role, FormContextType } from "@/utils/app.constant"; -import CommonUserModal from "@/components/CommonUserModal"; -import useSubmittedButtonStore from "@/utils/useSharedState"; - -const TeamLeader: React.FC = () => { - const { t } = useTranslation(); - const handleAddTeamLeaderClick = () => { - handleOpenAddTeamLeaderModal(); - }; - const [submitValue, setSubmitValue] = React.useState(false); - const setSubmittedButtonStatus = useSubmittedButtonStore( - (state: any) => state.setSubmittedButtonStatus - ); - - const [openAddTeamLeaderModal, setOpenAddTeamLeaderModal] = - React.useState(false); - const handleOpenAddTeamLeaderModal = () => { - setOpenAddTeamLeaderModal(true); - }; - const handleModalSubmit = (value: boolean) => { - setSubmitValue(true); - }; - const handleCloseAddTeamLeaderModal = () => { - setSubmittedButtonStatus(false); - - setOpenAddTeamLeaderModal(false); - }; - - return ( - <> - - - {/* */} - - ); -}; - -export async function getStaticProps({ locale }: any) { - return { - props: { - ...(await serverSideTranslations(locale, ["common"])), - }, - }; -} - -export default TeamLeader; diff --git a/src/pages/tenant.tsx b/src/pages/tenant.tsx index c55d5fa0..31593c90 100644 --- a/src/pages/tenant.tsx +++ b/src/pages/tenant.tsx @@ -4,52 +4,30 @@ import { serverSideTranslations } from "next-i18next/serverSideTranslations"; import HeaderComponent from "@/components/HeaderComponent"; import { useTranslation } from "next-i18next"; import Pagination from "@mui/material/Pagination"; -import Select, { SelectChangeEvent } from "@mui/material/Select"; +import { SelectChangeEvent } from "@mui/material/Select"; import PageSizeSelector from "@/components/PageSelector"; import { cohortCreate, createUser, deleteTenant, - fetchCohortMemberList, - getCohortList, roleCreate, rolesList, - updateCohortUpdate, updateTenant, } from "@/services/CohortService/cohortService"; -import { - CohortTypes, - Numbers, - QueryKeys, - Role, - SORT, - Status, - Storage, -} from "@/utils/app.constant"; +import { CohortTypes, Numbers, Role, SORT, Status } from "@/utils/app.constant"; import EditIcon from "@mui/icons-material/Edit"; import AddIcon from "@mui/icons-material/Add"; import DeleteIcon from "@mui/icons-material/Delete"; import ConfirmationModal from "@/components/ConfirmationModal"; -import { - Box, - Button, - MenuItem, - Typography, - useMediaQuery, -} from "@mui/material"; +import { Box, Button, Typography, useMediaQuery } from "@mui/material"; import Loader from "@/components/Loader"; import { customFields } from "@/components/GeneratedSchemas"; -import { CustomField } from "@/utils/Interfaces"; import { showToastMessage } from "@/components/Toastify"; import AddNewTenant from "@/components/AddNewTenant"; import { getTenantTableData } from "@/data/tableColumns"; import { Theme } from "@mui/system"; -import { - firstLetterInUpperCase, - mapFields, - transformLabel, -} from "@/utils/Helper"; +import { mapFields } from "@/utils/Helper"; import SimpleModal from "@/components/SimpleModal"; import { IChangeEvent } from "@rjsf/core"; import { RJSFSchema } from "@rjsf/utils"; @@ -61,6 +39,7 @@ import tenantSchema from "../components/TenantSchema.json"; import { getTenantLists } from "@/services/CohortService/cohortService"; import cohortSchemajson from "./cohortSchema.json"; import userJsonSchema from "./tenantAdminSchema.json"; +import ProtectedRoute from "@/components/ProtectedRoute"; type cohortFilterDetails = { type?: string; @@ -73,15 +52,6 @@ type cohortFilterDetails = { archivedMembers?: string; }; -interface centerData { - name?: string; - status?: string; - updatedBy?: string; - createdBy?: string; - createdAt?: string; - updatedAt?: string; - customFieldValues?: string; -} interface TenantData { name: string; status: string; @@ -96,20 +66,6 @@ interface RowData { totalActiveMembers: number; [key: string]: any; } -interface Schema { - properties: { - [key: string]: { - title?: string; - type: string; - }; - }; -} - -interface Field { - name: string; - label: string; - type: string; -} const Tenant: React.FC = () => { // use hooks @@ -127,8 +83,6 @@ const Tenant: React.FC = () => { const stateCode = state ? state?.code : null; // handle states const [selectedTenant, setSelectedTenant] = React.useState([]); - const [selectedDistrict, setSelectedDistrict] = React.useState([]); - const [selectedBlock, setSelectedBlock] = React.useState([]); const [selectedSort, setSelectedSort] = useState("Sort"); const [selectedFilter, setSelectedFilter] = useState("Active"); const [cohortData, setCohortData] = useState([]); @@ -153,9 +107,6 @@ const Tenant: React.FC = () => { const [pageSizeArray, setPageSizeArray] = React.useState([]); const [pagination, setPagination] = useState(true); const [sortBy, setSortBy] = useState(["createdAt", "asc"]); - const [selectedStateCode, setSelectedStateCode] = useState(""); - const [selectedDistrictCode, setSelectedDistrictCode] = useState(""); - const [selectedBlockCode, setSelectedBlockCode] = useState(""); const [formdata, setFormData] = useState(); const [editFormData, setEditFormData] = useState([]); const [isEditForm, setIsEditForm] = useState(false); @@ -264,27 +215,10 @@ const Tenant: React.FC = () => { }, }; - const selectedBlockStore = useSubmittedButtonStore( - (state: any) => state.selectedBlockStore - ); - const setSelectedBlockStore = useSubmittedButtonStore( - (state: any) => state.setSelectedBlockStore - ); - const selectedDistrictStore = useSubmittedButtonStore( - (state: any) => state.selectedDistrictStore - ); - const setSelectedDistrictStore = useSubmittedButtonStore( - (state: any) => state.setSelectedDistrictStore - ); - const setSubmittedButtonStatus = useSubmittedButtonStore( (state: any) => state.setSubmittedButtonStatus ); - const setAdminInformation = useSubmittedButtonStore( - (state: any) => state.setAdminInformation - ); - const [filters, setFilters] = useState({ type: CohortTypes.COHORT, states: "", @@ -516,186 +450,6 @@ const Tenant: React.FC = () => { ); - const handleStateChange = async (selected: string[], code: string[]) => { - const newQuery = { ...router.query }; - - if (newQuery.center) { - delete newQuery.center; - } - if (newQuery.district) { - delete newQuery.district; - } - if (newQuery.block) { - delete newQuery.block; - } - router.replace({ - pathname: router.pathname, - query: { - ...newQuery, - state: "", - }, - }); - // setSelectedDistrict([]); - // setSelectedBlock([]); - // setSelectedState(selected); - - // setSelectedCenterCode([]) - - setSelectedBlockCode(""); - setSelectedDistrictCode(""); - - if (selected[0] === "") { - if (filters.status) - setFilters({ type: "COHORT", status: filters.status }); - // else setFilters({ role: role }); - } else { - const stateCodes = code?.join(","); - setSelectedStateCode(stateCodes); - if (filters.status) - setFilters({ - type: "COHORT", - states: "", - status: filters.status, - }); - else setFilters({ type: "COHORT", states: "" }); - } - }; - - const handleDistrictChange = (selected: string[], code: string[]) => { - const newQuery = { ...router.query }; - if (newQuery.center) { - delete newQuery.center; - } - if (newQuery.block) { - delete newQuery.block; - } - setSelectedBlock([]); - setSelectedDistrict(selected); - setSelectedBlockCode(""); - // localStorage.setItem('selectedDistrict', selected[0]) - - setSelectedDistrictStore(selected[0]); - if (selected[0] === "" || selected[0] === t("COMMON.ALL_DISTRICTS")) { - if (filters.status) { - setFilters({ - states: "", - status: filters.status, - type: "COHORT", - }); - } else { - setFilters({ - states: "", - type: "COHORT", - }); - } - if (newQuery.district) { - delete newQuery.district; - } - router.replace({ - pathname: router.pathname, - query: { - ...newQuery, - state: "", - }, - }); - } else { - router.replace({ - pathname: router.pathname, - query: { - ...newQuery, - // state: selectedStateCode, - // district: code?.join(",") - }, - }); - const districts = code?.join(","); - setSelectedDistrictCode(districts); - if (filters.status) { - setFilters({ - states: "", - districts: "", - status: filters.status, - //type:"COHORT", - }); - } else { - setFilters({ - states: "", - districts: "", - // type:"COHORT", - }); - } - } - setPageOffset(Numbers.ZERO); - // fetchUserList(); - }; - const handleBlockChange = (selected: string[], code: string[]) => { - setSelectedBlock(selected); - const newQuery = { ...router.query }; - if (newQuery.center) { - delete newQuery.center; - } - if (newQuery.block) { - delete newQuery.block; - } - - localStorage.setItem("selectedBlock", selected[0]); - setSelectedBlockStore(selected[0]); - if (selected[0] === "" || selected[0] === t("COMMON.ALL_BLOCKS")) { - if (newQuery.block) { - delete newQuery.block; - } - router.replace({ - pathname: router.pathname, - query: { - ...newQuery, - // state: selectedStateCode, - // district: selectedDistrictCode, - }, - }); - if (filters.status) { - setFilters({ - states: "", - districts: "", - status: filters.status, - type: "COHORT", - }); - } else { - setFilters({ - states: "", - districts: "", - type: "COHORT", - }); - } - } else { - router.replace({ - pathname: router.pathname, - query: { - ...newQuery, - // state: selectedStateCode, - // district: selectedDistrictCode, - // block: code?.join(",") - }, - }); - // const blocks = code?.join(","); - // setSelectedBlockCode(blocks); - if (filters.status) { - setFilters({ - states: "", - districts: "", - blocks: "", - status: filters.status, - type: "COHORT", - }); - } else { - setFilters({ - states: "", - districts: "", - blocks: "", - type: "COHORT", - }); - } - } - }; - const handleCloseModal = () => { setConfirmationModalOpen(false); setUpdateBtnDisabled(true); @@ -1013,60 +767,60 @@ const Tenant: React.FC = () => { setAddFormData({}); }; - useEffect(() => { - const fetchData = () => { - try { - const object = { - // "limit": 20, - // "offset": 0, - fieldName: "states", - }; - // const response = await getStateBlockDistrictList(object); - // const result = response?.result?.values; - if (typeof window !== "undefined" && window.localStorage) { - const admin = localStorage.getItem("adminInfo"); - if (admin) { - const stateField = JSON.parse(admin).customFields?.find( - (field: any) => field?.label === "STATES" - ); - if (!stateField?.value?.includes(",")) { - // setSelectedState([stateField.value]); - setSelectedStateCode(stateField?.code); - if ( - selectedDistrictCode && - selectedDistrict.length !== 0 && - selectedDistrict[0] !== t("COMMON.ALL_DISTRICTS") - ) { - setFilters({ - states: "", - districts: "", - status: filters.status, - type: CohortTypes.COHORT, - }); - } - if ( - selectedBlockCode && - selectedBlock.length !== 0 && - selectedBlock[0] !== t("COMMON.ALL_BLOCKS") - ) { - setFilters({ - states: "", - districts: "", - blocks: "", - status: filters.status, - type: CohortTypes.COHORT, - }); - } - } - } - } - } catch (error) { - console.log(error); - } - }; + // useEffect(() => { + // const fetchData = () => { + // try { + // const object = { + // // "limit": 20, + // // "offset": 0, + // fieldName: "states", + // }; + // // const response = await getStateBlockDistrictList(object); + // // const result = response?.result?.values; + // if (typeof window !== "undefined" && window.localStorage) { + // const admin = localStorage.getItem("adminInfo"); + // if (admin) { + // const stateField = JSON.parse(admin).customFields?.find( + // (field: any) => field?.label === "STATES" + // ); + // if (!stateField?.value?.includes(",")) { + // // setSelectedState([stateField.value]); + // setSelectedStateCode(stateField?.code); + // if ( + // selectedDistrictCode && + // selectedDistrict.length !== 0 && + // selectedDistrict[0] !== t("COMMON.ALL_DISTRICTS") + // ) { + // setFilters({ + // states: "", + // districts: "", + // status: filters.status, + // type: CohortTypes.COHORT, + // }); + // } + // if ( + // selectedBlockCode && + // selectedBlock.length !== 0 && + // selectedBlock[0] !== t("COMMON.ALL_BLOCKS") + // ) { + // setFilters({ + // states: "", + // districts: "", + // blocks: "", + // status: filters.status, + // type: CohortTypes.COHORT, + // }); + // } + // } + // } + // } + // } catch (error) { + // console.log(error); + // } + // }; - fetchData(); - }, [selectedBlockCode, selectedDistrictCode]); + // fetchData(); + // }, [selectedBlockCode, selectedDistrictCode]); const handleMemberClick = async ( type: "active" | "archived", @@ -1245,18 +999,9 @@ const Tenant: React.FC = () => { const userProps = { userType: t("TENANT.TENANT"), searchPlaceHolder: t("TENANT.SEARCH"), - // selectedState: selectedState, selectedTenant: selectedTenant, - selectedStateCode: selectedStateCode, - selectedDistrict: selectedDistrict, - // selectedDistrictCode: selectedDistrictCode, - // selectedBlockCode: selectedBlockCode, - selectedBlock: selectedBlock, selectedSort: selectedSort, selectedFilter: selectedFilter, - handleStateChange: handleStateChange, - handleDistrictChange: handleDistrictChange, - handleBlockChange: handleBlockChange, handleSortChange: handleSortChange, handleFilterChange: handleFilterChange, handleSearch: handleSearch, @@ -1268,17 +1013,10 @@ const Tenant: React.FC = () => { statusValue: statusValue, setStatusValue: setStatusValue, showSort: false, - selectedBlockCode: selectedBlockCode, - setSelectedBlockCode: setSelectedBlockCode, - selectedDistrictCode: selectedDistrictCode, - setSelectedDistrictCode: setSelectedDistrictCode, - setSelectedStateCode: setSelectedStateCode, - setSelectedDistrict: setSelectedDistrict, - setSelectedBlock: setSelectedBlock, }; return ( - <> + { )} - + ); }; diff --git a/src/services/Interceptor.ts b/src/services/Interceptor.ts index 3eaa391b..f1e43df4 100644 --- a/src/services/Interceptor.ts +++ b/src/services/Interceptor.ts @@ -1,4 +1,3 @@ -import { tenantId } from './../../app.config'; import axios from "axios"; import { refresh } from "./LoginService";