Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] add delete-result functionality #35

Merged
merged 2 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions app/actions/sustainabilityReport/deleteResult.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import axios from 'axios';

interface IParams {
userId: string;
projectId: string;
attributeId: string;
}

export const deleteResult = async ({ userId, projectId, attributeId }: IParams) => {
console.log('Deleting result...', userId, projectId, attributeId);
return await axios
.delete(process.env.NEXT_PUBLIC_PORTFOLIO_INSIGHT_API_URL + '/delete-result', {
params: {
userId: userId,
projectId: projectId,
attributeId: attributeId,
},
})
.then((response) => {
return response.data;
})
.catch((error) => {
console.error('Error deleting result. Please try again.');
throw error;
});
};
32 changes: 32 additions & 0 deletions app/components/SustainabilityReport/ResultContainer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import useSustainabilityReportDeleteModal from '@/app/hooks/sustainabilityReport/useSustainabilityReportDeleteModal';
import { X } from '@phosphor-icons/react';

interface ResultContainerProps {
result: string;
projectId: string;
attributeId: string;
}

const ResultContainer = ({ result, projectId, attributeId }: ResultContainerProps) => {
const sustainabilityReportDeleteModal = useSustainabilityReportDeleteModal();

const handleDeleteResult = () => {
console.log('Deleting result for attribute:', attributeId);
sustainabilityReportDeleteModal.setProjectId(projectId);
sustainabilityReportDeleteModal.setAttributeId(attributeId);
sustainabilityReportDeleteModal.onOpen();
};
return (
<div className="relative px-2 py-1 w-full overflow-hidden flex items-center justify-center group">
<div className="max-h-[300px] overflow-y-auto">{result}</div>
<div
onClick={handleDeleteResult}
className="absolute bg-blue-gray-50 right-2 top-2 p-2 rounded-md cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity duration-300 hover:bg-blue-gray-100"
>
<X size={16} />
</div>
</div>
);
};

export default ResultContainer;
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,21 @@ import { deleteAttribute } from '@/app/actions/sustainabilityReport/deleteAttrib
import { deleteReports } from '@/app/actions/sustainabilityReport/deleteReports';
import useFetchSustainabilityData from '@/app/hooks/sustainabilityReport/useFetchSustainabilityData';
import { deleteProjects } from '@/app/actions/sustainabilityReport/deleteProjects';
import { deleteResult } from '@/app/actions/sustainabilityReport/deleteResult';

const SustainabilityReportDeleteModal = () => {
const SustainabilityReportDeleteModal = useSustainabilityReportDeleteModal();
const [isLoading, setIsLoading] = useState(false);
const { userId, deleteStoreAttribute, deleteStoreProject, deleteStoreReport } = useSustainabilityStore();
const { userId, deleteStoreAttribute, deleteStoreProject, deleteStoreReport, deleteAttributeForProject } =
useSustainabilityStore();
const { fetchAttributesThenProjects } = useFetchSustainabilityData();
const { handleSubmit, reset } = useForm<FieldValues>({});

const onSubmit: SubmitHandler<FieldValues> = async () => {
try {
setIsLoading(true);
const deleteItemId = SustainabilityReportDeleteModal.deleteItem?.id;
const deleteItemId =
SustainabilityReportDeleteModal.deleteItem?.id || SustainabilityReportDeleteModal.attributeId;
console.log('DELETING', deleteItemId);
if (!deleteItemId) {
throw new Error('Delete ID is missing');
Expand All @@ -50,9 +53,13 @@ const SustainabilityReportDeleteModal = () => {
console.log('deleting attribute');
await deleteAttribute({ userId, attributeId: deleteItemId });
deleteStoreAttribute(deleteItemId);
} else {
console.log('deleting result');
const attributeId = SustainabilityReportDeleteModal.attributeId;
await deleteResult({ userId, projectId: SustainabilityReportDeleteModal.projectId, attributeId });
deleteAttributeForProject(attributeId);
}
SustainabilityReportDeleteModal.onClose();
fetch;
} catch (error) {
toast.error('Delete deleteItem failed. Please try again.');
} finally {
Expand All @@ -68,12 +75,18 @@ const SustainabilityReportDeleteModal = () => {
SustainabilityReportDeleteModal.onClose();
};

const getName = () => {
return (
SustainabilityReportDeleteModal.deleteItem?.name || SustainabilityReportDeleteModal.attributeId.split('_')[0]
);
};

const bodyContent = (
<>
<div className="flex flex-col gap-4 items-center">
<Heading title={`Delete ${SustainabilityReportDeleteModal.deleteItem?.name}`} subtitle="" center />
<Heading title={`Delete ${getName()}`} subtitle="" center />
<Typography color="gray" variant="h5">
{`Are you sure you want to delete ${SustainabilityReportDeleteModal.deleteItem?.name}?`}
{`Are you sure you want to delete ${getName()}?`}
</Typography>
</div>
</>
Expand Down
11 changes: 11 additions & 0 deletions app/hooks/sustainabilityReport/sustainabilityReportStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ interface SustainabilityStoreState {
deleteStoreAttribute: (attributeId: string) => void;
deleteStoreReport: (reportId: string) => void;
deleteStoreProject: (projectId: string) => void;
deleteAttributeForProject: (attributeId: string) => void;
addReportsToAdd: (newReports: File[]) => void;
setReportsToAdd: (newReports: File[]) => void;
updateStatus: (projectId: string, status: GenerationStatus) => void;
Expand Down Expand Up @@ -67,6 +68,16 @@ const useSustainabilityStore = create<SustainabilityStoreState>((set) => ({
set((state) => ({
reports: state.reports.filter((report) => report.id !== reportId),
})),
deleteAttributeForProject: (attributeId: string) => {
set((state: { projects: Project[] }) => ({
projects: state.projects.map((project) => ({
...project,
projectResults: Object.fromEntries(
Object.entries(project.projectResults).filter(([key]) => key !== attributeId)
),
})),
}));
},
updateResults: (projectId, results) =>
set((state) => ({
projects: state.projects.map((project) =>
Expand Down
61 changes: 36 additions & 25 deletions app/hooks/sustainabilityReport/useFetchSustainabilityData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,41 +42,52 @@ const useFetchSustainabilityData = () => {
const getProjectsResponse = await getProjects({ userId });
const { projects: rawProjects }: { projects: Project[] } = getProjectsResponse;

const existingProjectIds = new Set(projects.map((project) => project.id));
const newProjects: Project[] = rawProjects
.filter((rawProject) => !existingProjectIds.has(rawProject.id))
.map((rawProject) => ({
...rawProject,
reports: [
...rawProject.reports.map((report) => ({
// Create a Map for easier lookup of existing projects by ID
const existingProjectsMap = new Map(projects.map((project) => [project.id, project]));

// Prepare updated projects by iterating through rawProjects
const updatedProjects: Project[] = rawProjects.map((rawProject) => {
const existingProject = existingProjectsMap.get(rawProject.id);

if (existingProject) {
// If the project already exists, merge the content (e.g., update reports)
return {
...existingProject,
...rawProject,
reports: rawProject.reports.map((report) => ({
...report,
status: GenerationStatus.READY,
})),
],
}));
};
} else {
// If the project is new, add it as a new project
return {
...rawProject,
reports: rawProject.reports.map((report) => ({
...report,
status: GenerationStatus.READY,
})),
};
}
});

// Filter out projects that haven't changed (optional, if needed)
const changedProjects = updatedProjects.filter((updatedProject) => {
const existingProject = existingProjectsMap.get(updatedProject.id);
return !existingProject || JSON.stringify(existingProject) !== JSON.stringify(updatedProject);
});

// if (attributes.length > 0) {
// newProjects.forEach((report) => {
// Object.keys(report.reportResults).forEach((key) => {
// const isKeyInAttributes = attributes.some((attribute) => attribute.name === key);
// if (!isKeyInAttributes) {
// console.log('Deleting key:', key);
// delete report.reportResults[key];
// }
// });
// });
// }

if (newProjects.length > 0) {
console.log('Adding projects:', newProjects);
addProjects(newProjects);
if (changedProjects.length > 0) {
console.log('Updating projects:', changedProjects);
addProjects(changedProjects);
}
} catch (error) {
console.error('Error fetching or adding reports:', error);
console.error('Error fetching or updating reports:', error);
}
}, [userId, addReports, reports, attributes, fetchAttributes, attributesFetched]);

const fetchAttributesThenProjects = useCallback(async () => {
console.log('Fetching attributes then projects');
await fetchAttributes();
await fetchProjects();
}, [fetchAttributes, fetchProjects]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,22 @@ interface SustainabilityReportDeleteModalStore {
isOpen: boolean;
deleteItem: Attribute | Report | Project | null;
projectId: string;
attributeId: string;
onOpen: () => void;
onClose: () => void;
setDeleteItem: (deleteItem: Attribute | Report | Project) => void;
setProjectId: (projectId: string) => void;
setAttributeId: (attributeId: string) => void;
}

const useSustainabilityReportDeleteModal = create<SustainabilityReportDeleteModalStore>((set) => ({
isOpen: false,
deleteItem: null,
projectId: '',
attributeId: '',
onOpen: () => set({ isOpen: true }),
onClose: () => set({ isOpen: false }),
setAttributeId: (attributeId: string) => set({ attributeId }),
setDeleteItem: (deleteItem: Attribute | Report | Project) => set({ deleteItem }),
setProjectId: (projectId: string) => set({ projectId }),
}));
Expand Down
7 changes: 6 additions & 1 deletion app/pages/sustainabilityreports/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import useSustainabilityReportDeleteModal from '@/app/hooks/sustainabilityReport
import SustainabilityReportAddFileModal from '@/app/components/modals/sustainabilityReport/SustainabilityReportAddFileModal';
import FilesContainer from '@/app/components/SustainabilityReport/FilesContainer';
import ProjectContainer from '@/app/components/SustainabilityReport/ProjectContainer';
import ResultContainer from '@/app/components/SustainabilityReport/ResultContainer';

function Page() {
const { projects, attributes, isLoading, setIsLoading, updateResults, updateStatus, userId, setUserId } =
Expand Down Expand Up @@ -304,7 +305,11 @@ function Page() {
{attributes.map((attribute: Attribute, index: number) => (
<td className={`${classes} max-h-[300px] overflow-y-auto`} key={index + project.name}>
{attribute.id in project.projectResults && isNotEmpty(project.projectResults[attribute.id]) ? (
<div className="max-h-[300px] overflow-y-auto">{project.projectResults[attribute.id]}</div>
<ResultContainer
result={project.projectResults[attribute.id]}
projectId={project.id}
attributeId={attribute.id}
/>
) : (
<div
className={`w-full h-[32px] rounded-lg bg-gray-300 flex justify-center items-center text-gray-600 ${
Expand Down
Loading