Skip to content

Commit

Permalink
Merge pull request #72 from Aar-if/reassignFacilitatorAPI
Browse files Browse the repository at this point in the history
Issue #PS-1451 feat: API integration for re-assign Facilitators
  • Loading branch information
itsvick authored Aug 1, 2024
2 parents 763cb3a + ab14636 commit c673dca
Show file tree
Hide file tree
Showing 6 changed files with 169 additions and 66 deletions.
56 changes: 44 additions & 12 deletions src/components/ManageUser.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
Button,
Grid,
Typography
} from '@mui/material';
import { Button, Grid, Typography } from '@mui/material';
import React, { useState } from 'react';

import BottomDrawer from '@/components/BottomDrawer';
Expand Down Expand Up @@ -32,6 +28,7 @@ import AddFacilitatorModal from './AddFacilitator';
import ReassignModal from './ReassignModal';
import DeleteUserModal from './DeleteUserModal';
import SimpleModal from './SimpleModal';
import reassignLearnerStore from '@/store/reassignLearnerStore';

interface Cohort {
cohortId: string;
Expand Down Expand Up @@ -98,14 +95,15 @@ const manageUsers: React.FC<ManageUsersProps> = ({
});
const [confirmationModalOpen, setConfirmationModalOpen] =
React.useState<boolean>(false);
const [reassignModalOpen, setReassignModalOpen] =
const [reassignModalOpen, setReassignModalOpen] =
React.useState<boolean>(false);
const [learnerData, setLearnerData] = React.useState<LearnerDataProps[]>();
const [reassignBlockRequestModalOpen, setReassignBlockRequestModalOpen] =
React.useState<boolean>(false);
const [openDeleteUserModal, setOpenDeleteUserModal] = React.useState(false);
const [openRemoveUserModal, setOpenRemoveUserModal] = React.useState(false);
const [removeCohortNames, setRemoveCohortNames] = React.useState('');
const [reassignCohortNames, setReassignCohortNames] = React.useState('');
const [userId, setUserId] = React.useState('');
const CustomLink = styled(Link)(({ theme }) => ({
textDecoration: 'underline',
Expand All @@ -115,6 +113,7 @@ const manageUsers: React.FC<ManageUsersProps> = ({
const setCohortDeleteId = manageUserStore((state) => state.setCohortDeleteId);
const [openAddFacilitatorModal, setOpenFacilitatorModal] =
React.useState(false);
const setReassignFacilitatorUserId = reassignLearnerStore((state) => state.setReassignFacilitatorUserId);

useEffect(() => {
const getFacilitator = async () => {
Expand All @@ -134,7 +133,7 @@ const manageUsers: React.FC<ManageUsersProps> = ({
districts: 'PN',
blocks: 'BA',
role: 'Teacher',
status: 'active',
status: ['active'],
};
const fields = ['age'];

Expand Down Expand Up @@ -334,16 +333,44 @@ const manageUsers: React.FC<ManageUsersProps> = ({
// console.log(error);
// showToastMessage(t('COMMON.SOMETHING_WENT_WRONG'), 'error');
// }
}if (name === 'reassign-block') {
}
if (name === 'reassign-block') {

const reassignuserId = selectedUser?.userId ;


setReassignFacilitatorUserId(selectedUser?.userId)

const fetchCohortList = async () => {
if (!selectedUser?.userId) {
console.warn('User ID is undefined');
return;
}

try {
const cohortList = await getCohortList(selectedUser.userId);
console.log('Cohort List:', cohortList);
if (cohortList && cohortList?.length > 0) {
const cohortDetails = cohortList?.map((cohort: { cohortName: any, cohortId: any }) => ({
name: cohort?.cohortName,
id: cohort?.cohortId
}));
setReassignCohortNames(cohortDetails);
}
} catch (error) {
console.error('Error fetching cohort list:', error);
}
};

fetchCohortList();
setReassignModalOpen(true);
getTeamLeadersCenters();
}
if (name === 'reassign-centers') {
setOpenCentersModal(true);
getTeamLeadersCenters();
}
if (name === 'reassign-block-request') {
setReassignModalOpen(true);
// setReassignModalOpen(true);
getTeamLeadersCenters();
}
};
Expand Down Expand Up @@ -604,7 +631,11 @@ const manageUsers: React.FC<ManageUsersProps> = ({
<Box display="flex" alignItems="center" gap="5px">
<Image src={profileALT} alt="img" />
<Box>
<CustomLink className="word-break" href="#" onClick={(e) => e.preventDefault()}>
<CustomLink
className="word-break"
href="#"
onClick={(e) => e.preventDefault()}
>
<Typography
onClick={() => {
handleTeacherFullProfile(user.userId!);
Expand Down Expand Up @@ -775,7 +806,8 @@ const manageUsers: React.FC<ManageUsersProps> = ({
handleCloseModal={handleCloseModal}
modalOpen={confirmationModalOpen}
/>
<ReassignModal
<ReassignModal
cohortNames={reassignCohortNames}
message={t('COMMON.REASSIGN_BLOCKS')}
handleAction={handleRequestBlockAction}
handleCloseReassignModal={handleCloseReassignModal}
Expand Down
171 changes: 120 additions & 51 deletions src/components/ReassignModal.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import { Divider, TextField, Checkbox, InputAdornment, IconButton } from '@mui/material';
import {
Divider,
TextField,
Checkbox,
InputAdornment,
IconButton,
} from '@mui/material';
import Modal from '@mui/material/Modal';
import { useTheme } from '@mui/material/styles';
import useStore from '@/store/store';
import SearchIcon from '@mui/icons-material/Search';
import CloseIcon from '@mui/icons-material/Close';
import { useTranslation } from 'next-i18next';

import { useEffect } from 'react';
import reassignLearnerStore from '@/store/reassignLearnerStore';
import { BulkCreateCohortMembersRequest } from '@/utils/Interfaces';
import { bulkCreateCohortMembers } from '@/services/CohortServices';
import { showToastMessage } from './Toastify';

interface ReassignModalProps {
cohortNames?: any;
message: string;
handleAction?: () => void;
buttonNames?: ButtonNames;
Expand All @@ -24,6 +35,7 @@ interface ButtonNames {
}

const ReassignModal: React.FC<ReassignModalProps> = ({
cohortNames,
modalOpen,
message,
handleAction,
Expand All @@ -34,12 +46,28 @@ const ReassignModal: React.FC<ReassignModalProps> = ({
const { t } = useTranslation();
const store = useStore();
const cohorts = store.cohorts;
const centerList = cohorts.map((cohort: { name: string }) => cohort.name);

const centerList = cohorts?.map((cohort: { cohortId: any; name: string }) => ({
name: cohort.name,
id: cohort.cohortId,
}));
const reStore = reassignLearnerStore();
const [searchInput, setSearchInput] = React.useState('');
const [selectedData, setSelectedData] = React.useState('');
const [unSelectedData, setUnSelectedData] = React.useState('');
const [checkedCenters, setCheckedCenters] = React.useState<string[]>([]);

const handleSearchInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
useEffect(() => {
if (cohortNames) {
const initialCheckedCenters = cohortNames?.map(
(cohort: { name: any }) => cohort?.name
);
setCheckedCenters(initialCheckedCenters);
}
}, [cohortNames]);

const handleSearchInputChange = (
event: React.ChangeEvent<HTMLInputElement>
) => {
setSearchInput(event.target.value);
};

Expand All @@ -54,13 +82,58 @@ const ReassignModal: React.FC<ReassignModalProps> = ({
} else {
newChecked.push(name);
}

const checkedCenterIds = centerList
.filter((center: { name: string }) => newChecked.includes(center?.name))
.map((center: { id: any }) => center.id);
const uncheckedCenterIds = centerList
.filter((center: { name: string }) => !newChecked.includes(center?.name))
.map((center: { id: any }) => center.id);

setSelectedData(checkedCenterIds);

setUnSelectedData(uncheckedCenterIds);
return newChecked;
});
};

const filteredCenters = centerList.filter((center: string) =>
center.toLowerCase().includes(searchInput.toLowerCase())
);
const filteredCenters = centerList
.filter((center: { name: string }) =>
center.name.toLowerCase().includes(searchInput.toLowerCase())
)
.sort((a: { name: string }, b: { name: string }) => {
const aChecked = checkedCenters.includes(a.name);
const bChecked = checkedCenters.includes(b.name);
if (aChecked === bChecked) {
return 0;
}
return aChecked ? -1 : 1;
});

const handleReassign = async () => {
console.log('USER ID', reStore.reassignFacilitatorUserId);
console.log('Checked Center IDs:', selectedData);
console.log('Unchecked Center IDs:', unSelectedData);

const payload = {
userId: [reStore?.reassignFacilitatorUserId],
cohortId: selectedData,
removeCohortId: unSelectedData,
};

try {
const response = await bulkCreateCohortMembers(payload);
console.log('Cohort members created successfully', response);

showToastMessage(
t('MANAGE_USERS.CENTERS_REQUESTED_SUCCESSFULLY'),
'success'
);
} catch (error) {
console.error('Error creating cohort members', error);
showToastMessage(t('MANAGE_USERS.CENTERS_REQUEST_FAILED'), 'error');
}
};

const style = {
position: 'absolute',
Expand All @@ -85,12 +158,12 @@ const ReassignModal: React.FC<ReassignModalProps> = ({
>
<Box sx={style}>
<Box
sx={{
p: 3,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}
sx={{
p: 3,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
id="confirmation-modal-title"
>
<span>{message}</span>
Expand All @@ -104,21 +177,21 @@ const ReassignModal: React.FC<ReassignModalProps> = ({
</IconButton>
</Box>
<Divider />
<Box sx={{ p: 3}}>
<Box sx={{ p: 3 }}>
<TextField
sx={{
backgroundColor: theme.palette.warning['A700'],
borderRadius: 8,
'& .MuiOutlinedInput-root': {
'& fieldset': {
border: 'none',
},
},
'& .MuiOutlinedInput-input': {
sx={{
backgroundColor: theme.palette.warning['A700'],
borderRadius: 8,
},
}}
placeholder={t('CENTERS.SEARCH_CENTERS')}
'& .MuiOutlinedInput-root': {
'& fieldset': {
border: 'none',
},
},
'& .MuiOutlinedInput-input': {
borderRadius: 8,
},
}}
placeholder={t('CENTERS.SEARCH_CENTERS')}
value={searchInput}
onChange={handleSearchInputChange}
fullWidth
Expand All @@ -132,23 +205,25 @@ const ReassignModal: React.FC<ReassignModalProps> = ({
/>
</Box>
<Box sx={{ p: 3, maxHeight: '300px', overflowY: 'auto' }}>
{filteredCenters.map((center: string, index: number) => (
<Box
key={index}
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
mb: 2,
}}
>
<span>{center}</span>
<Checkbox
checked={checkedCenters.includes(center)}
onChange={() => handleToggle(center)}
/>
</Box>
))}
{filteredCenters.map(
(center: { name: string; id: string }, index: number) => (
<Box
key={index}
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
mb: 2,
}}
>
<span>{center.name}</span>
<Checkbox
checked={checkedCenters.includes(center.name)}
onChange={() => handleToggle(center.name)}
/>
</Box>
)
)}
</Box>
<Divider />
<Box
Expand All @@ -169,17 +244,11 @@ const ReassignModal: React.FC<ReassignModalProps> = ({
variant="contained"
color="primary"
onClick={() => {
if (handleAction !== undefined) {
handleAction();
handleCloseReassignModal();
} else {
handleCloseReassignModal();
}
handleReassign();
}}
>
{buttonNames?.primary || 'Re-assign'}
</Button>

</Box>
</Box>
</Modal>
Expand Down
2 changes: 1 addition & 1 deletion src/services/CohortServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export const getCohortList = async (
};

export const bulkCreateCohortMembers = async (
payload: BulkCreateCohortMembersRequest
payload: any
): Promise<any> => {
const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/cohortmember/bulkCreate`;
try {
Expand Down
2 changes: 1 addition & 1 deletion src/services/MyClassDetailsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const getMyUserList = async ({
try {
const response = await post(apiUrl, {
limit,
page,
offset: page,
filters,
fields,
});
Expand Down
Loading

0 comments on commit c673dca

Please sign in to comment.