Skip to content

Commit

Permalink
Merge pull request #26 from AntaresSimulatorTeam/feature/ANT_2344_del…
Browse files Browse the repository at this point in the history
…ete_project

feat: delete project
  • Loading branch information
melazaar authored Dec 20, 2024
2 parents 4326932 + 36a1c33 commit 6f3f8de
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 21 deletions.
6 changes: 4 additions & 2 deletions src/components/pegase/pegaseCard/useDropdownOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,27 @@ export const useDropdownOptions = () => {
const { t } = useTranslation();

const settingOption = useCallback(
(onClick: () => void, label?: string): StdDropdownOption => ({
(onClick: () => void, label?: string, disabled?: boolean): StdDropdownOption => ({
key: 'setting',
label: label || t('project.@setting'),
value: 'setting',
icon: StdIconId.Settings,
onItemClick: onClick,
extraClasses: NO_WRAP_CLASS,
disabled: disabled,
}),
[t],
);

const deleteOption = useCallback(
(onClick: () => void, label?: string): StdDropdownOption => ({
(onClick: () => void, label?: string, disabled?: boolean): StdDropdownOption => ({
key: 'delete',
label: label ?? t('project.@delete'),
value: 'delete',
icon: StdIconId.Delete,
onItemClick: onClick,
extraClasses: clsx(NO_WRAP_CLASS, '[&]:text-error-600 [&]:hover:text-error-600'),
disabled: disabled,
}),
[t],
);
Expand Down
7 changes: 6 additions & 1 deletion src/pages/pegase/home/pinnedProjects/PinnedProjectCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useDropdownOptions } from '@/components/pegase/pegaseCard/useDropdownOp
import { dismissToast, notifyToast } from '@/shared/notification/notification';
import { v4 as uuidv4 } from 'uuid';
import { useProjectNavigation } from '@/hooks/useProjectNavigation';
import { deleteProjectById } from '@/pages/pegase/projects/projectService';

export const PinnedProjectCards = ({
reloadPinnedProject,
Expand Down Expand Up @@ -114,12 +115,16 @@ export const PinnedProjectCards = ({
const handleCardClick = (projectId: string, projectName: string) => {
navigateToProject(projectId, projectName);
};
const deleteProject = async (projectId: string) => {
await deleteProjectById(projectId, isReloadPinnedProject);
await loadPinnedProjects();
};

return projects.map((project, index) => {
const dropdownItems = [
pinOption(project.pinned ?? false, () => handleUnpin(project.id)), // Toggle pin/unpin
settingOption(() => {}, t('project.@setting')),
deleteOption(() => {}, t('project.@delete')), // Empty function for delete - does nothing
deleteOption(() => deleteProject(project.id), t('project.@delete'), project.studies?.length > 0),
];

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe('handleUnpin test', () => {
creationDate: new Date(),
path: '',
tags: ['tag1', 'tag2'],
studies: [],
},
{
id: '2',
Expand All @@ -29,6 +30,7 @@ describe('handleUnpin test', () => {
creationDate: new Date(),
path: '',
tags: ['tag3', 'tag4'],
studies: [],
},
];
updatedProjects = callback(prevProjects);
Expand All @@ -52,6 +54,7 @@ describe('handleUnpin test', () => {
creationDate: expect.any(Date),
path: '',
tags: ['tag3', 'tag4'],
studies: [],
},
]);
});
Expand Down
16 changes: 10 additions & 6 deletions src/pages/pegase/projects/ProjectContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import StudiesPagination from '@/pages/pegase/home/components/StudiesPagination'
import { useDropdownOptions } from '@/components/pegase/pegaseCard/useDropdownOptions';

import { useProjectNavigation } from '@/hooks/useProjectNavigation';
import { pinProject, useFetchProjects } from './projectService';
import { deleteProjectById, pinProject, useFetchProjects } from './projectService';

interface ProjectContentProps {
isReloadPinnedProject: (value: boolean) => void;
Expand All @@ -30,7 +30,7 @@ const ProjectContent = ({ isReloadPinnedProject }: ProjectContentProps) => {
const [activeChip, setActiveChip] = useState<boolean | null>(false);
const userName = 'mouad'; // Replace with actual user name
const [current, setCurrent] = useState(0);
const { projects, count } = useFetchProjects(searchTerm || '', current, intervalSize);
const { projects, count, refetch } = useFetchProjects(searchTerm || '', current, intervalSize);

const { navigateToProject } = useProjectNavigation();

Expand All @@ -52,6 +52,11 @@ const ProjectContent = ({ isReloadPinnedProject }: ProjectContentProps) => {
pinProject(projectId, isReloadPinnedProject);
};

const deleteProject = async (projectId: string) => {
await deleteProjectById(projectId, isReloadPinnedProject);
refetch(); // Actualiser les projets après suppression
};

const handleCardClick = (projectId: string, projectName: string) => {
navigateToProject(projectId, projectName);
};
Expand All @@ -73,9 +78,8 @@ const ProjectContent = ({ isReloadPinnedProject }: ProjectContentProps) => {
const dropdownItems = [
pinOption(false, () => handlePinProject(project.id)),
settingOption(() => {}, t('project.@setting')),
deleteOption(() => {}, t('project.@delete')),
deleteOption(() => deleteProject(project.id), t('project.@delete'), project.studies?.length > 0),
];

return (
<PegaseCard
key={project.id}
Expand All @@ -94,9 +98,9 @@ const ProjectContent = ({ isReloadPinnedProject }: ProjectContentProps) => {
</div>
<div className="flex items-center gap-x-0.5 pt-2.5">
<div className="font-sans text-body-xs font-light">
{t('project.created')} :{' '}
{t('project.@created')} :{' '}
<span className="text-body-xs font-bold">{formatDateToDDMMYYYY(project.creationDate)} </span>{' '}
{t('project.by')} :
{t('project.@by')} :
</div>
<StdAvatar
size="es"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const ProjectDetails = () => {
pinned: false,
path: '',
tags: data.tags,
studies: [],
});
} catch (error) {
console.error(`Error retrieving project details: ${projectId}`, error);
Expand Down
52 changes: 41 additions & 11 deletions src/pages/pegase/projects/projectService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,49 @@ export const useFetchProjects = (searchTerm: string, current: number, intervalSi
const [count, setCount] = useState(0);
const BASE_URL = getEnvVariables('VITE_BACK_END_BASE_URL');

const fetchProjects = () => {
const url = `${BASE_URL}/v1/project/search?page=${current + 1}&size=${intervalSize}&search=${searchTerm || ''}`;
fetch(url)
.then((response) => response.json())
.then((json) => {
setProjects(json.content);
setCount(json.totalElements);
})
.catch((error) => console.error(error));
};

useEffect(() => {
const fetchProjects = () => {
const url = `${BASE_URL}/v1/project/search?page=${current + 1}&size=${intervalSize}&search=${searchTerm || ''}`;
fetch(url)
.then((response) => response.json())
.then((json) => {
setProjects(json.content);
setCount(json.totalElements);
})
.catch((error) => console.error(error));
};
fetchProjects();
}, [BASE_URL, current, searchTerm, intervalSize]);

return { projects, count };
return { projects, count, refetch: fetchProjects };
};

export const deleteProjectById = async (projectId: string, isReloadProjects: (value: boolean) => void) => {
const BASE_URL = getEnvVariables('VITE_BACK_END_BASE_URL');

try {
const response = await fetch(`${BASE_URL}/v1/project/${projectId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
});

if (!response.ok) {
const errorText = await response.text();
const errorData = JSON.parse(errorText);
throw new Error(`${errorData.message || errorText}`);
}
notifyToast({
type: 'success',
message: 'Project deleted successfully',
});
isReloadProjects(true);
} catch (error: any) {
notifyToast({
type: 'error',
message: `${error.message}`,
});
}
};
1 change: 1 addition & 0 deletions src/shared/types/pegase/Project.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ export interface ProjectInfo {
pinned?: boolean;
path: string;
tags: string[];
studies: number[];
}
Loading

0 comments on commit 6f3f8de

Please sign in to comment.