From d5cbd7654a31fc3d7cb76871faaabfa6b7578e49 Mon Sep 17 00:00:00 2001 From: Arif-tekdi-technologies Date: Thu, 28 Nov 2024 01:16:53 +0530 Subject: [PATCH] Issue #000 Bug: Course Planner Fixes and improvements --- src/pages/course-planner/index.tsx | 593 ++++++++++++++++------------- src/utils/Helper.ts | 171 +++++---- 2 files changed, 426 insertions(+), 338 deletions(-) diff --git a/src/pages/course-planner/index.tsx b/src/pages/course-planner/index.tsx index 8dd06be9..d4b2fd02 100644 --- a/src/pages/course-planner/index.tsx +++ b/src/pages/course-planner/index.tsx @@ -32,6 +32,8 @@ import { useRouter } from 'next/router'; import React, { useEffect, useState } from 'react'; import { accessControl, frameworkId } from '../../../app.config'; import { useDirection } from '../../hooks/useDirection'; +import { types } from 'node:util'; +import axios from 'axios'; const CoursePlanner = () => { const [value, setValue] = React.useState(''); @@ -75,54 +77,6 @@ const CoursePlanner = () => { const [manipulatedCohortData, setManipulatedCohortData] = useState>(cohortsData); - const handleChange = (event: SelectChangeEvent) => { - const newValue = event.target.value as string; - if (newValue !== value) { - setValue(newValue); - setType(newValue); - } - const windowUrl = window.location.pathname; - const cleanedUrl = windowUrl.replace(/^\//, ''); - const env = cleanedUrl.split('/')[0]; - - const telemetryInteract = { - context: { - env: env, - cdata: [], - }, - edata: { - id: 'change-filter:' + event.target.value, - - type: Telemetry.CLICK, - subtype: '', - pageid: cleanedUrl, - }, - }; - telemetryFactory.interact(telemetryInteract); - }; - - const addQueryParams = (newParams: any) => { - // Merge existing query params with new ones - const updatedQuery = { ...router.query, ...newParams }; - - // Update the URL without reloading the page - router.push( - { - pathname: router.pathname, - query: updatedQuery, - }, - undefined, - { shallow: true } - ); - }; - - useEffect(() => { - if (classId) { - setSelectedValue(classId); - addQueryParams({ center: classId }); - } - }, [classId]); - useEffect(() => { const subjects = localStorage.getItem('overallCommonSubjects'); if (subjects) { @@ -136,105 +90,44 @@ const CoursePlanner = () => { console.log('No subjects found in localStorage.'); setSubjects([]); } - }, []); - - useEffect(() => { - if (store.cohorts.length > 0) { - const cohortId = router.query.center - ? router.query.center - : store.cohorts[0].cohortId; - - addQueryParams({ center: cohortId }); - setSelectedValue(cohortId); - } - }, [store.cohorts]); - - useEffect(() => { - const fetchCohortSearchResults = async () => { - setLoading(true); - setState(''); - setBoard(''); - setMedium(''); - setGrade(''); + const fetchTaxonomyResultsOne = async () => { try { - const data = await getCohortSearch({ - cohortId: selectedValue, - limit: 20, - offset: 0, - }); - - const cohortDetails = data?.result?.results?.cohortDetails?.[0]; - - if (cohortDetails) { - // const arrayFields = [ - // { label: CoursePlannerConstants.SUBJECT, setter: setSubject }, - // ]; - - const stringFields = [ - { label: CoursePlannerConstants.STATES, setter: setState }, - { label: CoursePlannerConstants.BOARD, setter: setBoard }, - { label: CoursePlannerConstants.MEDIUM, setter: setMedium }, - { label: CoursePlannerConstants.GRADE, setter: setGrade }, - ]; - - // arrayFields.forEach(({ label, setter }) => { - // const field = cohortDetails.customFields.find( - // (field: any) => field.label === label - // ); - - // if (field && field.value) { - // const valuesArray = field.value - // .split(',') - // .map((item: string) => item.trim()); - // setter(valuesArray); - // } else if (label === CoursePlannerConstants.SUBJECT) { - // setter([]); - // } - // }); - - stringFields.forEach(({ label, setter }) => { - const field = cohortDetails.customFields.find( - (field: any) => field.label === label - ); - - if (field && field.value) { - setter(field.value.trim()); - } - }); - } - - setLoading(false); - } catch (error) { - console.error('Failed to fetch cohort search results:', error); - } - }; + // Define the URL for the API + const url = `/api/framework/v1/read/${frameworkId}`; - if (selectedValue.length) { - fetchCohortSearchResults(); - } - }, [selectedValue]); + // Use axios to fetch data from the API + const response = await axios.get(url); + const boardData = response.data; - useEffect(() => { - const fetchTaxonomyResults = async () => { - try { - const url = `/api/framework/v1/read/${frameworkId}`; - const boardData = await fetch(url).then((res) => res.json()); console.log(boardData?.result?.framework); const frameworks = boardData?.result?.framework; + + // Get states options const getStates = getOptionsByCategory(frameworks, 'state'); + console.log(getStates); + + // Set the frameworks state setFramework(frameworks); + const matchingState = getStates.find( (state: any) => state.name === userStateName ); + if (matchingState) { + console.log(matchingState); + setStateOption([matchingState]); - setStateAssociations(matchingState.associations); + setStateAssociations(matchingState?.associations); + console.log('FIRST TIME API', matchingState); + // Get boards options const getBoards = await getOptionsByCategory(frameworks, 'board'); if (getBoards && matchingState) { - const commonBoards = getBoards + console.log('FIRST TIME API', getBoards); + + const commonBoards = await getBoards .filter((item1: { code: any }) => matchingState.associations.some( (item2: { code: any; category: string }) => @@ -246,20 +139,33 @@ const CoursePlanner = () => { code: item1.code, associations: item1.associations, })); + + console.log('FIRST TIME API', commonBoards); setBoardOptions(commonBoards); - const getMedium = await getOptionsByCategory(framework, 'medium'); - const boardAssociations = getAssociationsByCodeNew( - boardOptions, - tStore?.board - ); + // Fetch medium options + const getMedium = frameworks?.categories + ?.find((category: any) => category?.code === 'medium') + ?.terms?.map((term: any) => ({ + name: term?.name, + code: term?.code, + associations: term?.associations, + })); + + console.log('FIRST TIME API', commonBoards); + + const boardAssociations = + commonBoards?.find((item: any) => item?.name === tStore?.board) + ?.associations || []; setBoardAssociations(boardAssociations); + console.log('FIRST TIME API', boardAssociations); - const commonMediumInState = getMedium - .filter((item1: { code: string }) => - stateAssociations.some( + // Filter medium based on state + const commonMediumInState = await getMedium + ?.filter((item1: { code: string }) => + matchingState?.associations?.some( (item2: { code: string; category: string }) => - item2.code === item1.code && item2.category === 'medium' + item2?.code === item1?.code && item2?.category === 'medium' ) ) .map( @@ -268,24 +174,25 @@ const CoursePlanner = () => { code: string; associations: any[]; }) => ({ - name: item1.name, - code: item1.code, - associations: item1.associations, + name: item1?.name, + code: item1?.code, + associations: item1?.associations, }) ); const commonMediumInBoard = getMedium - .filter((item1: { code: any }) => - boardAssociations.some( + ?.filter((item1: { code: any }) => + boardAssociations?.some( (item2: { code: any; category: string }) => - item2.code === item1.code && item2.category === 'medium' + item2.code === item1?.code && item2?.category === 'medium' ) ) - .map((item1: { name: any; code: any; associations: any }) => ({ - name: item1.name, - code: item1.code, - associations: item1.associations, + ?.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); @@ -293,63 +200,80 @@ const CoursePlanner = () => { commonMediumInState, commonMediumInBoard ); + + console.log(commonMediumData); + setMediumOptions(commonMediumData); - const getGrades = await getOptionsByCategory( - framework, - 'gradeLevel' - ); - const mediumAssociations = getAssociationsByCodeNew( - mediumOptions, - tStore?.medium - ); - console.log('boardAssociations', stateAssociations); + // Fetch grades options + const getGrades = await frameworks?.categories + ?.find((category: any) => category?.code === 'gradeLevel') + ?.terms?.map((term: any) => ({ + name: term?.name, + code: term?.code, + associations: term?.associations, + })); + + console.log(getGrades); + + const mediumAssociations = frameworks?.categories + ?.find((category: any) => category?.code === 'medium') + ?.terms?.map((term: any) => ({ + name: term?.name, + code: term?.code, + associations: term?.associations, + })); + console.log('boardAssociations', mediumAssociations); setMediumAssociations(mediumAssociations); const commonGradeInState = await getGrades - .filter((item1: { code: string }) => - stateAssociations.some( + ?.filter((item1: { code: string }) => + matchingState?.associations?.some( (item2: { code: string; category: string }) => - item2.code === item1.code && item2.category === 'gradeLevel' + item2?.code === item1?.code && + item2?.category === 'gradeLevel' ) ) - .map( + ?.map( (item1: { name: string; code: string; associations: any[]; }) => ({ - name: item1.name, - code: item1.code, - associations: item1.associations, + name: item1?.name, + code: item1?.code, + associations: item1?.associations, }) ); const commonGradeInBoard = await getGrades - .filter((item1: { code: any }) => - boardAssociations.some( + ?.filter((item1: { code: any }) => + boardAssociations?.some( (item2: { code: any; category: string }) => - item2.code === item1.code && item2.category === 'gradeLevel' + item2?.code === item1?.code && + item2?.category === 'gradeLevel' ) ) .map((item1: { name: any; code: any; associations: any }) => ({ - name: item1.name, - code: item1.code, - associations: item1.associations, + name: item1?.name, + code: item1?.code, + associations: item1?.associations, })); const commonGradeInMedium = await getGrades - .filter((item1: { code: any }) => - mediumAssociations.some( + ?.filter((item1: { code: any }) => + mediumAssociations?.some( (item2: { code: any; category: string }) => - item2.code === item1.code && item2.category === 'gradeLevel' + item2?.code === item1?.code && + item2?.category === 'gradeLevel' ) ) .map((item1: { name: any; code: any; associations: any }) => ({ - name: item1.name, - code: item1.code, - associations: item1.associations, + name: item1?.name, + code: item1?.code, + associations: item1?.associations, })); + console.log(`commonGradeInBoards`, commonGradeInBoard); console.log(`commonGradeInState`, commonGradeInState); console.log(`commonGradeInMedium`, commonGradeInMedium); @@ -361,14 +285,27 @@ const CoursePlanner = () => { commonGradeInStateBoard, commonGradeInMedium ); + console.log(overAllCommonGrade); + setGradeOptions(overAllCommonGrade); const gradeAssociations = getAssociationsByCodeNew( - gradeOptions, + overAllCommonGrade, tStore?.grade ); + + console.log(gradeAssociations); + setGradeAssociations(gradeAssociations); - const type = await getOptionsByCategory(framework, 'courseType'); + + // Fetch course type options + const type = await frameworks?.categories + ?.find((category: any) => category?.code === 'courseType') + ?.terms?.map((term: any) => ({ + name: term?.name, + code: term?.code, + associations: term?.associations, + })); console.log(type); const commonTypeInState = filterAndMapAssociationsNew( @@ -411,104 +348,234 @@ const CoursePlanner = () => { console.log(`commonTypeOverall`, commonType3Data); setTypeOptions(commonType3Data); - // setType(commonType3Data); + } + } else { + setStateName(false); + } + } catch (error) { + console.error('Failed to fetch cohort search results:', error); + } + }; - const typeAssociations = getAssociationsByCodeNew( - typeOptions, - tStore?.type - ); - setTypeAssociations(typeAssociations); - const subject = await getOptionsByCategory(framework, 'subject'); + fetchTaxonomyResultsOne(); + }, []); - console.log(subject); + const addQueryParams = (newParams: any) => { + // Merge existing query params with new ones + const updatedQuery = { ...router.query, ...newParams }; - const commonSubjectInState = filterAndMapAssociationsNew( - 'subject', - subject, - stateAssociations, - 'code' - ); - const commonSubjectInBoard = filterAndMapAssociationsNew( - 'subject', - type, - boardAssociations, - 'code' - ); - const commonSubjectInMedium = filterAndMapAssociationsNew( - 'subject', - subject, - mediumAssociations, - 'code' - ); - const commonSubjectInGrade = filterAndMapAssociationsNew( - 'subject', - subject, - gradeAssociations, - 'code' - ); - const commonSubjectInType = filterAndMapAssociationsNew( - 'subject', - subject, - typeAssociations, - 'code' + // Update the URL without reloading the page + router.push( + { + pathname: router.pathname, + query: updatedQuery, + }, + undefined, + { shallow: true } + ); + }; + + useEffect(() => { + if (classId) { + setSelectedValue(classId); + addQueryParams({ center: classId }); + } + }, [classId]); + + // useEffect(() => { + // if (store.cohorts.length > 0) { + // const cohortId = router.query.center + // ? router.query.center + // : store.cohorts[0].cohortId; + + // addQueryParams({ center: cohortId }); + // setSelectedValue(cohortId); + // } + // }, [store.cohorts]); + + useEffect(() => { + const fetchCohortSearchResults = async () => { + setLoading(true); + setState(''); + setBoard(''); + setMedium(''); + setGrade(''); + + try { + const data = await getCohortSearch({ + cohortId: selectedValue, + limit: 20, + offset: 0, + }); + + const cohortDetails = data?.result?.results?.cohortDetails?.[0]; + + if (cohortDetails) { + // const arrayFields = [ + // { label: CoursePlannerConstants.SUBJECT, setter: setSubject }, + // ]; + + const stringFields = [ + { label: CoursePlannerConstants.STATES, setter: setState }, + { label: CoursePlannerConstants.BOARD, setter: setBoard }, + { label: CoursePlannerConstants.MEDIUM, setter: setMedium }, + { label: CoursePlannerConstants.GRADE, setter: setGrade }, + ]; + + // arrayFields.forEach(({ label, setter }) => { + // const field = cohortDetails.customFields.find( + // (field: any) => field.label === label + // ); + + // if (field && field.value) { + // const valuesArray = field.value + // .split(',') + // .map((item: string) => item.trim()); + // setter(valuesArray); + // } else if (label === CoursePlannerConstants.SUBJECT) { + // setter([]); + // } + // }); + + stringFields.forEach(({ label, setter }) => { + const field = cohortDetails.customFields.find( + (field: any) => field.label === label ); - const findCommonAssociationsNew = ( - array1: any[], - array2: any[] - ) => { - return array1.filter((item1: { code: any }) => - array2.some((item2: { code: any }) => item1.code === item2.code) - ); - }; + if (field && field.value) { + setter(field.value.trim()); + } + }); + } - const findOverallCommonSubjects = (arrays: any[]) => { - const nonEmptyArrays = arrays.filter( - (array: string | any[]) => array && array.length > 0 - ); + setLoading(false); + } catch (error) { + console.error('Failed to fetch cohort search results:', error); + } + }; - if (nonEmptyArrays.length === 0) return []; + if (selectedValue.length) { + fetchCohortSearchResults(); + } + }, [selectedValue]); - let commonSubjects = nonEmptyArrays[0]; + useEffect(() => { + const fetchTaxonomyResults = async () => { + try { + const typeAssociations = getAssociationsByCodeNew( + typeOptions, + tStore?.type + ); + setTypeAssociations(typeAssociations); + const subject = await getOptionsByCategory(framework, 'subject'); - for (let i = 1; i < nonEmptyArrays.length; i++) { - commonSubjects = findCommonAssociationsNew( - commonSubjects, - nonEmptyArrays[i] - ); + console.log(subject); - if (commonSubjects.length === 0) return []; - } + const commonSubjectInState = filterAndMapAssociationsNew( + 'subject', + subject, + stateAssociations, + 'code' + ); + const commonSubjectInBoard = filterAndMapAssociationsNew( + 'subject', + typeOptions, + boardAssociations, + 'code' + ); + const commonSubjectInMedium = filterAndMapAssociationsNew( + 'subject', + subject, + mediumAssociations, + 'code' + ); + const commonSubjectInGrade = filterAndMapAssociationsNew( + 'subject', + subject, + gradeAssociations, + 'code' + ); + const commonSubjectInType = filterAndMapAssociationsNew( + 'subject', + subject, + typeAssociations, + 'code' + ); + + const findCommonAssociationsNew = (array1: any[], array2: any[]) => { + return array1.filter((item1: { code: any }) => + array2.some((item2: { code: any }) => item1.code === item2.code) + ); + }; - return commonSubjects; - }; + const findOverallCommonSubjects = (arrays: any[]) => { + const nonEmptyArrays = arrays.filter( + (array: string | any[]) => array && array.length > 0 + ); - const arrays = [ - commonSubjectInState, - commonSubjectInBoard, - commonSubjectInMedium, - commonSubjectInGrade, - commonSubjectInType, - ]; + if (nonEmptyArrays.length === 0) return []; - const overallCommonSubjects = - await findOverallCommonSubjects(arrays); + let commonSubjects = nonEmptyArrays[0]; - localStorage.setItem( - 'overallCommonSubjects', - JSON.stringify(overallCommonSubjects) + for (let i = 1; i < nonEmptyArrays.length; i++) { + commonSubjects = findCommonAssociationsNew( + commonSubjects, + nonEmptyArrays[i] ); - setSubjects(overallCommonSubjects); + + if (commonSubjects.length === 0) return []; } - } else { - setStateName(false); - } + + return commonSubjects; + }; + + const arrays = [ + commonSubjectInState, + commonSubjectInBoard, + commonSubjectInMedium, + commonSubjectInGrade, + commonSubjectInType, + ]; + + const overallCommonSubjects = await findOverallCommonSubjects(arrays); + + localStorage.setItem( + 'overallCommonSubjects', + JSON.stringify(overallCommonSubjects) + ); + setSubjects(overallCommonSubjects); } catch (error) { console.error('Failed to fetch cohort search results:', error); } }; fetchTaxonomyResults(); - }, [value, subjects]); + }, [value]); + + const handleChange = (event: SelectChangeEvent) => { + const newValue = event.target.value as string; + if (newValue !== value) { + setValue(newValue); + setType(newValue); + } + const windowUrl = window.location.pathname; + const cleanedUrl = windowUrl.replace(/^\//, ''); + const env = cleanedUrl.split('/')[0]; + + const telemetryInteract = { + context: { + env: env, + cdata: [], + }, + edata: { + id: 'change-filter:' + event.target.value, + + type: Telemetry.CLICK, + subtype: '', + pageid: cleanedUrl, + }, + }; + telemetryFactory.interact(telemetryInteract); + }; const isStateEmpty = !tStore.state; const isBoardEmpty = !tStore.board; @@ -583,7 +650,7 @@ const CoursePlanner = () => { diff --git a/src/utils/Helper.ts b/src/utils/Helper.ts index 377c35bf..db9f87f0 100644 --- a/src/utils/Helper.ts +++ b/src/utils/Helper.ts @@ -2,7 +2,11 @@ import { Role, Status, labelsToExtractForMiniProfile } from './app.constant'; import dayjs from 'dayjs'; import utc from 'dayjs/plugin/utc'; import FingerprintJS from 'fingerprintjs2'; -import { BoardEnrollmentStageCounts, CustomField, UpdateCustomField } from './Interfaces'; +import { + BoardEnrollmentStageCounts, + CustomField, + UpdateCustomField, +} from './Interfaces'; dayjs.extend(utc); import { format, parseISO } from 'date-fns'; import manageUserStore from '@/store/manageUserStore'; @@ -31,16 +35,14 @@ export const MONTHS = [ ]; export const formatDate = (dateString: string) => { - if(dateString) - { + if (dateString) { const dateOnly = dateString?.split('T')[0]; - + const [year, monthIndex, day] = dateOnly.split('-'); const month = MONTHS[parseInt(monthIndex, 10) - 1]; - + return `${day} ${month}, ${year}`; } - }; export const formatToShowDateMonth = (date: Date) => { @@ -119,7 +121,10 @@ export const debounce = any>( ) => { let timeout: ReturnType | undefined; - const debounced = function (this: ThisParameterType, ...args: Parameters) { + const debounced = function ( + this: ThisParameterType, + ...args: Parameters + ) { const context = this; clearTimeout(timeout); @@ -140,7 +145,6 @@ export const debounce = any>( return debounced; }; - //Function to convert names in capitalize case export const toPascalCase = (name: string | any) => { if (typeof name !== 'string') { @@ -323,10 +327,13 @@ export const generateUsernameAndPassword = ( export const mapFieldIdToValue = ( fields: CustomField[] ): { [key: string]: string } => { - return fields?.reduce((acc: { [key: string]: string }, field: CustomField) => { - acc[field.fieldId] = field.value; - return acc; - }, {}); + return fields?.reduce( + (acc: { [key: string]: string }, field: CustomField) => { + acc[field.fieldId] = field.value; + return acc; + }, + {} + ); }; export const convertUTCToIST = (utcDateTime: string) => { @@ -370,13 +377,13 @@ export const convertLocalToUTC = (localDateTime: any) => { export const getCurrentYearPattern = () => { const currentYear = new Date().getFullYear(); - + // Build the dynamic part for the current century let regexPart = ''; if (currentYear >= 2000 && currentYear < 2100) { const lastDigit = currentYear % 10; const middleDigit = Math.floor((currentYear % 100) / 10); - + regexPart = `20[0-${middleDigit - 1}][0-9]|20${middleDigit}[0-${lastDigit}]`; } @@ -489,15 +496,15 @@ export const sortSessionsByTime = (sessionsArray: any) => { // Helper function to get options by category export const getOptionsByCategory = (frameworks: any, categoryCode: string) => { // Find the category by code - const category = frameworks.categories.find( - (category: any) => category.code === categoryCode + const category = frameworks?.categories?.find( + (category: any) => category?.code === categoryCode ); // Return the mapped terms - return category.terms.map((term: any) => ({ - name: term.name, - code: term.code, - associations: term.associations + return category?.terms?.map((term: any) => ({ + name: term?.name, + code: term?.code, + associations: term?.associations, })); }; @@ -515,55 +522,64 @@ interface DataItem { code: string; associations: Association[]; } -export const getAssociationsByName = (data: DataItem[], name: string): Association[] | [] => { - const foundItem = data.find(item => item.name === name); +export const getAssociationsByName = ( + data: DataItem[], + name: string +): Association[] | [] => { + const foundItem = data.find((item) => item.name === name); return foundItem ? foundItem.associations : []; }; - -export const getAssociationsByCodeNew = (data: DataItem[], code: string): Association[] | [] => { - const foundItem = data.find(item => item.name === code); - return foundItem ? foundItem.associations : []; +export const getAssociationsByCodeNew = ( + data: DataItem[], + code: string +): Association[] | [] => { + const foundItem = data?.find((item) => item?.name === code); + return foundItem ? foundItem?.associations : []; }; - - -export const getAssociationsByCode = (data: DataItem[], code: string): Association[] | [] => { - const foundItem = data.find(item => item.code === code); +export const getAssociationsByCode = ( + data: DataItem[], + code: string +): Association[] | [] => { + const foundItem = data.find((item) => item.code === code); return foundItem ? foundItem.associations : []; }; export const findCommonAssociations = (data1: any[], data2: any[]) => { - - if (!data1.length) return data2; - if (!data2.length) return data1; - - return data1.map((item1) => { - const item2 = data2.find((item) => item.code === item1.code); - if (item2) { - const commonAssociations = item1.associations.filter((assoc1: any) => - item2.associations.some((assoc2: any) => assoc1.identifier === assoc2.identifier) - ); - if (commonAssociations.length > 0) { - return { - name: item1.name, - code: item1.code, - associations: commonAssociations, - }; + if (!data1?.length) return data2; + if (!data2?.length) return data1; + + return data1 + ?.map((item1) => { + const item2 = data2?.find((item) => item?.code === item1?.code); + if (item2) { + const commonAssociations = item1?.associations?.filter((assoc1: any) => + item2?.associations?.some( + (assoc2: any) => assoc1?.identifier === assoc2?.identifier + ) + ); + if (commonAssociations?.length > 0) { + return { + name: item1?.name, + code: item1?.code, + associations: commonAssociations, + }; + } } - } - return null; - }).filter(Boolean); + return null; + }) + .filter(Boolean); }; export const filterAndMapAssociationsNew = ( category: string, options: any[], associationsList?: any[], - codeKey: string = "code" + codeKey: string = 'code' ) => { if (!Array.isArray(options)) { - console.error("Options is not an array:", options); + console.error('Options is not an array:', options); return []; } @@ -589,8 +605,10 @@ export const filterAndMapAssociationsNew = ( export const extractCategory = (data: any[] | any, category: string) => { const items = Array.isArray(data) ? data : [data]; return items.flatMap((item) => - item.associations - .filter((association: { category: string; }) => association.category === category) + item.associations + .filter( + (association: { category: string }) => association.category === category + ) .map( ({ name, @@ -624,7 +642,10 @@ export function deepClone(obj: T): T { return JSON.parse(JSON.stringify(obj)); } -export const updateStoreFromCohorts = (activeCohorts: any, blockObject: any) => { +export const updateStoreFromCohorts = ( + activeCohorts: any, + blockObject: any +) => { const setDistrictCode = manageUserStore.getState().setDistrictCode; const setDistrictId = manageUserStore.getState().setDistrictId; const setStateCode = manageUserStore.getState().setStateCode; @@ -635,14 +656,13 @@ export const updateStoreFromCohorts = (activeCohorts: any, blockObject: any) => const setDistrictName = manageUserStore.getState().setDistrictName; const setStateName = manageUserStore.getState().setStateName; - const district = activeCohorts?.[0]?.customField?.find( (item: any) => item?.label === 'DISTRICTS' ); if (district) { setDistrictCode(district?.code); setDistrictId(district?.fieldId); - setDistrictName(district?.value) + setDistrictName(district?.value); } const state = activeCohorts?.[0]?.customField?.find( @@ -662,35 +682,35 @@ export const updateStoreFromCohorts = (activeCohorts: any, blockObject: any) => } }; -export function formatEndDate({diffDays}: any) { +export function formatEndDate({ diffDays }: any) { // Check if structuredClone is available - if(diffDays) - { - let remainingTime = ''; + if (diffDays) { + let remainingTime = ''; if (diffDays >= 365) { const years = Math.floor(diffDays / 365); const remainingDays = diffDays % 365; - - const months = Math.floor(remainingDays / 30.44); + + const months = Math.floor(remainingDays / 30.44); const days = Math.round(remainingDays % 30.44); - + remainingTime = `${years} year(s)${months > 0 ? `, ${months} month(s)` : ''}${days > 0 ? `, ${days} day(s)` : ''}`; } else if (diffDays > 31) { - const months = Math.floor(diffDays / 30.44); + const months = Math.floor(diffDays / 30.44); const days = Math.round(diffDays % 30.44); - + remainingTime = `${months} month(s) ${days > 0 ? ` , ${days} day(s)` : ''}`; } else { remainingTime = `${diffDays} day(s)`; } return remainingTime; } - return ""; - + return ''; } //TODO: Modify Helper with correct logic -export const calculateStageCounts = (data: { completedStep: any; }[]): BoardEnrollmentStageCounts => { +export const calculateStageCounts = ( + data: { completedStep: any }[] +): BoardEnrollmentStageCounts => { const stagesCount: BoardEnrollmentStageCounts = { board: 0, subjects: 0, @@ -700,11 +720,11 @@ export const calculateStageCounts = (data: { completedStep: any; }[]): BoardEnro }; const stageKeys: Record = { - 0: "board", - 1: "subjects", - 2: "registration", - 3: "fees", - 4: "completed", + 0: 'board', + 1: 'subjects', + 2: 'registration', + 3: 'fees', + 4: 'completed', }; data.forEach(({ completedStep }) => { @@ -715,12 +735,11 @@ export const calculateStageCounts = (data: { completedStep: any; }[]): BoardEnro return stagesCount; }; - export function getCohortNameById( cohorts: { cohortId: string; name: string }[], cohortId: string ): string | null { - const cohort = cohorts.find(c => c.cohortId === cohortId); + const cohort = cohorts.find((c) => c.cohortId === cohortId); return cohort ? cohort.name : null; } // const isFieldFilled = (key: string, value: any): boolean => { @@ -734,4 +753,4 @@ export function getCohortNameById( // Object.entries(formData).reduce( // (count, [key, value]) => count + (isFieldFilled(key, value) ? 1 : 0), // 0 -// ); \ No newline at end of file +// );