Skip to content

Commit

Permalink
feat:delete study
Browse files Browse the repository at this point in the history
  • Loading branch information
MOUAD EL AZAAR committed Jan 7, 2025
1 parent fd063b0 commit 23a48da
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 8 deletions.
27 changes: 25 additions & 2 deletions src/pages/pegase/home/components/StudyTableDisplay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { StudyStatus } from '@/shared/types/common/StudyStatus.type';
import { useStudyTableDisplay } from './useStudyTableDisplay';
import { useTranslation } from 'react-i18next';
import StudyCreationModal from '../../studies/StudyCreationModal';
import { handleDelete } from '@/pages/pegase/home/components/studyService';
import {RdsButton} from "rte-design-system-react";

interface StudyTableDisplayProps {
Expand All @@ -31,6 +32,9 @@ const StudyTableDisplay = ({ searchStudy, projectId }: StudyTableDisplayProps) =
const { t } = useTranslation();
const [selectedStudy, setSelectedStudy] = useState<StudyDTO | null>(null);

// Reload trigger for re-fetching data
const [reloadStudies, setReloadStudies] = useState<boolean>(false);

const handleSort = (column: string) => {
const newSortOrder = sortByState[column] === 'asc' ? 'desc' : 'asc';
setSortByState({ [column]: newSortOrder });
Expand All @@ -52,10 +56,12 @@ const StudyTableDisplay = ({ searchStudy, projectId }: StudyTableDisplayProps) =
isHeaderHovered,
);

// Pass reloadTrigger to refresh data
const { rows, count, intervalSize, current, setPage } = useStudyTableDisplay({
searchStudy,
projectId,
sortBy: sortByState,
reloadStudies, // Key change here
});

const selectedRowId = Object.keys(rowSelection)[0];
Expand All @@ -69,6 +75,16 @@ const StudyTableDisplay = ({ searchStudy, projectId }: StudyTableDisplayProps) =
const selectedStudy = rows[Number.parseInt(selectedRowId || '-1')];
setSelectedStudy(selectedStudy);
toggleModal();
setReloadStudies(!reloadStudies); // Trigger reload after deleting
};

const handleDeleteClick = () => {
const selectedStudyId = rows[Number.parseInt(selectedRowId || '-1')]?.id;
if (selectedStudyId) {
handleDelete(selectedStudyId).then(() => {
setReloadStudies(!reloadStudies); // Trigger reload after deleting
});
}
};

return (
Expand Down Expand Up @@ -99,7 +115,7 @@ const StudyTableDisplay = ({ searchStudy, projectId }: StudyTableDisplayProps) =
<RdsButton label="Duplicate" onClick={handleDuplicate} variant="outlined" disabled={!isDuplicateActive} />
<RdsButton
label="Delete"
onClick={() => console.log('Delete')}
onClick={handleDeleteClick}
variant="outlined"
color="danger"
disabled={!isDeleteActive}
Expand All @@ -108,7 +124,14 @@ const StudyTableDisplay = ({ searchStudy, projectId }: StudyTableDisplayProps) =
) : (
<RdsButton label={t('home.@new_study')} onClick={toggleModal} />
)}
{isModalOpen && <StudyCreationModal isOpen={isModalOpen} onClose={toggleModal} study={selectedStudy} />}
{isModalOpen && (
<StudyCreationModal
isOpen={isModalOpen}
onClose={toggleModal}
study={selectedStudy}
setReloadStudies={setReloadStudies} // Pass setReloadStudies
/>
)}
</div>
<StudiesPagination count={count} intervalSize={intervalSize} current={current} onChange={setPage} />
</div>
Expand Down
21 changes: 21 additions & 0 deletions src/pages/pegase/home/components/studyService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,24 @@ export const fetchSuggestedKeywords = async (query: string): Promise<string[]> =
const data = await response.json();
return data;
};

export const handleDelete = async (id: number) => {
try {
const response = await fetch(`http://localhost:8093/v1/study/${id}`, {
method: 'DELETE',
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText);
}
notifyToast({
type: 'success',
message: 'Study deleted successfully',
});
} catch (error: any) {
notifyToast({
type: 'error',
message: `${error.message}`,
});
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ describe('useStudyTableDisplay', () => {
json: async () => mockResponse,
});

const { result } = renderHook(() => useStudyTableDisplay({ searchStudy: 'test', sortBy: { status: 'desc' } }));
const { result } = renderHook(() =>
useStudyTableDisplay({ searchStudy: 'test', sortBy: { status: 'desc' }, reloadStudies: true }),
);
await waitFor(() => {
expect(result.current.rows).toHaveLength(2);
expect(result.current.rows).toEqual(mockResponse.content);
Expand All @@ -52,7 +54,9 @@ describe('useStudyTableDisplay', () => {
it('handles fetch error correctly', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('Fetch error'));

const { result } = renderHook(() => useStudyTableDisplay({ searchStudy: 'test', sortBy: { status: 'desc' } }));
const { result } = renderHook(() =>
useStudyTableDisplay({ searchStudy: 'test', sortBy: { status: 'desc' }, reloadStudies: true }),
);

await waitFor(() => {
expect(result.current.rows).toEqual([]);
Expand Down Expand Up @@ -82,7 +86,9 @@ describe('useStudyTableDisplay', () => {
json: async () => mockResponse,
});

const { result } = renderHook(() => useStudyTableDisplay({ searchStudy: 'study1', sortBy: { status: 'desc' } }));
const { result } = renderHook(() =>
useStudyTableDisplay({ searchStudy: 'study1', sortBy: { status: 'desc' }, reloadStudies: true }),
);

await waitFor(() => {
expect(result.current.rows).toHaveLength(1);
Expand Down
6 changes: 4 additions & 2 deletions src/pages/pegase/home/components/useStudyTableDisplay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ interface UseStudyTableDisplayProps {
searchStudy: string | undefined;
projectId?: string;
sortBy: { [key: string]: 'asc' | 'desc' };
reloadStudies: boolean;
}

interface UseStudyTableDisplayReturn {
Expand All @@ -31,6 +32,7 @@ export const useStudyTableDisplay = ({
searchStudy,
projectId,
sortBy,
reloadStudies,
}: UseStudyTableDisplayProps): UseStudyTableDisplayReturn => {
const [rows, setRows] = useState<StudyDTO[]>([]);
const [count, setCount] = useState(0);
Expand All @@ -41,7 +43,7 @@ export const useStudyTableDisplay = ({
useEffect(() => {
setCurrent(PAGINATION_CURRENT);
setCount(PAGINATION_COUNT);
}, [searchStudy, projectId, sortBy]);
}, [searchStudy, projectId, sortBy, reloadStudies]);

useEffect(() => {
const [sortColumn, sortDirection] = Object.entries(sortBy)[0] || ['', ''];
Expand All @@ -55,7 +57,7 @@ export const useStudyTableDisplay = ({
setCount(json.totalElements);
})
.catch((error) => console.error(error));
}, [current, searchStudy, projectId, sortBy]);
}, [current, searchStudy, projectId, sortBy, reloadStudies]);

return { rows, count, intervalSize, current, setPage: setCurrent };
};
4 changes: 3 additions & 1 deletion src/pages/pegase/studies/StudyCreationModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ interface StudyCreationModalProps {
isOpen: boolean;
onClose: () => void;
study?: StudyDTO | null;
setReloadStudies: React.Dispatch<React.SetStateAction<boolean>>;
}

const StudyCreationModal: React.FC<StudyCreationModalProps> = ({ onClose, study }) => {
const StudyCreationModal: React.FC<StudyCreationModalProps> = ({ onClose, study, setReloadStudies }) => {
const { t } = useTranslation();
const [studyName, setStudyName] = useState<string>('');
const [horizon, setHorizon] = useState<string>('');
Expand All @@ -41,6 +42,7 @@ const StudyCreationModal: React.FC<StudyCreationModalProps> = ({ onClose, study

await saveStudy(studyData, onClose);
// Clear form fields
setReloadStudies((prev) => !prev); // Trigger reload after successful save
setStudyName('');
setProjectName('');
setHorizon('');
Expand Down

0 comments on commit 23a48da

Please sign in to comment.