import * as Yup from 'yup'; import { useFormik } from 'formik'; import { useMutation, useLazyQuery, useReactiveVar } from '@apollo/client'; import { useEffect, useState } from 'react'; import { Navigate, useNavigate, useLocation } from 'react-router'; import { roleVar } from '../../graphql/state'; import { Add, Delete, Edit, Empty } from '../../assets'; import { Box, Button, Spinner, Text, Modal, Input, Alert } from '../../components'; import { Wrapper } from './styles'; import { DeleteUserMutation, DeleteUserMutationVariables, GetAllUsersQuery, GetAllUsersQueryVariables, UserOutput, } from '../../graphql/types'; import { GET_ALL_USERS } from '../../graphql/admin.api'; import { DELETE_USER } from '../../graphql/auth.api'; const Users = () => { const role = useReactiveVar(roleVar); const navigate = useNavigate(); const location = useLocation(); const [users, setUsers] = useState>(); const [userToDelete, setUserToDelete] = useState(); const [error, setError] = useState(''); const [deleteAccountModal, setDeleteAccountModal] = useState(false); const [getUsers, { loading, error: usersError }] = useLazyQuery< GetAllUsersQuery, GetAllUsersQueryVariables >(GET_ALL_USERS, { onCompleted({ getAllUsers }) { const userRole = location.pathname === '/clients' ? 'Client' : location.pathname === '/product-owners' ? 'ProductOwner' : 'Developer'; setUsers(getAllUsers.filter((user) => user.role === userRole)); } }); useEffect(() => { getUsers(); }, [location.pathname]); const [deleteUser] = useMutation< DeleteUserMutation, DeleteUserMutationVariables >(DELETE_USER, { onCompleted() { setUsers(users?.filter((user) => user.id !== userToDelete?.id)); setUserToDelete(undefined); setDeleteAccountModal(false); }, onError({ graphQLErrors }) { setDeleteAccountModal(false); setError(graphQLErrors[0]?.extensions?.info as string); setTimeout(() => setError(''), 3000); }, }); const deleteAccountForm = useFormik({ initialValues: { password: '', }, validationSchema: Yup.object().shape({ password: Yup.string() .required('Password is required') .min(6, 'Password is 6 characters minimum'), }), onSubmit: ({ password }, { resetForm }) => { try { deleteUser({ variables: { id: userToDelete?.id!, password } }); } finally { resetForm(); } }, }); if (role !== 'admin') return ( ) if (loading) return ( ); if (usersError || !users) return ( ); return ( <> {deleteAccountModal && ( setDeleteAccountModal(false)} onConfirm={deleteAccountForm.handleSubmit} > )} {users && users.length > 0 ? ( {location.pathname === '/clients' ? 'Clients' : location.pathname === '/product-owners' ? 'Product Owners' : 'Developers'} {error && ( )}