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

partial upload board funtionality #159

Merged
merged 2 commits into from
Jul 3, 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
12 changes: 4 additions & 8 deletions client/src/components/DownloadTemplateComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import React, { useEffect, useState } from "react";
import { useBoard } from "../context/BoardContext";
import { Board } from "../types";
Expand All @@ -8,17 +7,14 @@ import { useTemplates } from "../context/TemplateContext";
const DownloadTemplateComponent = () => {
const { selectedBoard, handleDownloadTemplate } = useBoard();
const { setIsTemplate } = useTemplates();
const [templateToDownload, setTemplateToDownload] = useState<Board>(
selectedBoard!
);

const handlePressDownload = () => {
console.log(selectedBoard!.name);
setTemplateToDownload((prevBoard) => ({
...prevBoard,

handleDownloadTemplate({
...selectedBoard!,
uuid: uuidv4(),
}));
handleDownloadTemplate(templateToDownload);
});
setIsTemplate(false);
};
return (
Expand Down
60 changes: 43 additions & 17 deletions client/src/components/SearchGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,54 @@ const SearchGrid = () => {
const { getAllTemplates } = useGetAllTemplates();
const { getCardsFromTemplate } = useGetTemplateCards();

useEffect(() => {
const fetchTemplates = async () => {
const templatesFromAPI = await getAllTemplates();
// previous code
// useEffect(() => {
// const fetchTemplates = async () => {
// const templatesFromAPI = await getAllTemplates();

const updatedTemplates = await Promise.all(
templatesFromAPI.map(async (template) => {
const cardsFromAPI = await getCardsFromTemplate(template.uuid);
const updatedCards = [...cardsFromAPI, newCard];
return { ...template, cards: updatedCards };
})
);
setAllTemplates(updatedTemplates);
};
// const updatedTemplates = await Promise.all(
// templatesFromAPI.map(async (template) => {
// const cardsFromAPI = await getCardsFromTemplate(template.uuid);
// const updatedCards = [...cardsFromAPI, newCard];
// return { ...template, cards: updatedCards };
// })
// );
// setAllTemplates(updatedTemplates);
// };

// if (templates.length === 0) {
// // UNCOMMENT WHEN ROUTE IS UP FOR GET ALL TEMPLATES AND GET CARDS FROM TEMPLATE
// // fetchTemplates();
// }
// }, []);

if (templates.length === 0) {
// UNCOMMENT WHEN ROUTE IS UP FOR GET ALL TEMPLATES AND GET CARDS FROM TEMPLATE
// fetchTemplates();
// above code changed to this
const fetchTemplates = async () => {
try {
const templatesFromAPI = await getAllTemplates();
if (templatesFromAPI.length > 0) {
const updatedTemplates = await Promise.all(
templatesFromAPI.map(async (template) => {
const cardsFromAPI = await getCardsFromTemplate(template.uuid);
console.log("CARDS",cardsFromAPI)
const updatedCards = [...cardsFromAPI, newCard];
return { ...template, cards: updatedCards };
})
);
setAllTemplates(updatedTemplates);
}
} catch (error) {
console.error("Error fetching templates:", error);
}
};

useEffect(() => {

fetchTemplates();
}, []);

useEffect(() => {
console.log(templates);
console.log("TEMP",templates);
if (templateQuery) {
setTemplates(
allTemplates
Expand All @@ -60,7 +86,7 @@ const SearchGrid = () => {
} else {
setTemplates(allTemplates.sort((a, b) => b.downloads - a.downloads));
}
}, [templateQuery]);
}, [templateQuery, allTemplates]);

return (
<div className="text-center mt-12">
Expand Down
18 changes: 12 additions & 6 deletions client/src/context/BoardContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,20 @@ export const BoardProvider = ({ children }: { children: ReactNode }) => {

const handleDownloadTemplate = async (board: Board) => {
await postNewBoard(board);
const newBoards = [...userBoards, board];
setUserBoards(newBoards);

board.cards!.forEach((card) => {
postNewCard(card, board!.uuid!);
setUserBoards((prev) => [...prev, board]);

board.cards!.forEach(async (card) => {
if (card.id !== "0") {
console.log("POSTING", card.id);
const postResponse = await postNewCard(
{ ...card, id: uuidv4() },
board!.uuid!
);
console.log("POST RESPONSE", postResponse);
}
});

board.cards?.unshift(newCard);
setSelectedBoard(null);
};

Expand Down Expand Up @@ -211,7 +217,7 @@ export const BoardProvider = ({ children }: { children: ReactNode }) => {
searchInput,
setSearchInput,
searchedBoards,
setSearchedBoards
setSearchedBoards,
}}
>
{children}
Expand Down
36 changes: 28 additions & 8 deletions client/src/context/TemplateContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Board } from "../types";
import usePostNewTemplate from "../hooks/usePostNewTemplate";
import usePostTemplateCard from "../hooks/usePostTemplateCard";


// Define the context shape
interface TemplateContextType {
templateQuery: string;
Expand Down Expand Up @@ -42,14 +41,35 @@ export const TemplateProvider = ({ children }: { children: ReactNode }) => {
setIsSearching((prev) => !prev);
};

const handleUploadNewTemplate = (template: Board) => {
// UNCOMMENT WHEN ROUTE IS COMPLETED. MAY NEED ASYNC/AWAIT IF ISSUES UPLOADING ALL AT ONCE
postNewTemplate(template);
// template.cards!.forEach((card) => {
// postTemplateCard(card, template.uuid);
// });
// previous code
// const handleUploadNewTemplate = (template: Board) => {
// // UNCOMMENT WHEN ROUTE IS COMPLETED. MAY NEED ASYNC/AWAIT IF ISSUES UPLOADING ALL AT ONCE
// postNewTemplate(template);
// template.cards!.forEach((card) => {
// if (card.id !== "0") {
// postTemplateCard(card, template.uuid);
// }
// });

// setUploadedTemplateNames((prev) => [...prev, template.name]);
// };

// Above component set up with async/await
const handleUploadNewTemplate = async (template: Board) => {
console.log("CARDSSSS", template.cards);
try {
await postNewTemplate(template);

template.cards!.forEach(async (card) => {
if (card.id !== "0") {
await postTemplateCard(card, template.uuid);
}
});

setUploadedTemplateNames((prev) => [...prev, template.name]);
setUploadedTemplateNames((prev) => [...prev, template.name]);
} catch (error) {
console.error("Error uploadinig template cards:", error);
}
};

return (
Expand Down
13 changes: 8 additions & 5 deletions client/src/hooks/useGetTemplateCards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@ const useGetTemplateCards = () => {
const getCardsFromTemplate = async (boardId: string): Promise<Card[]> => {
setIsLoading(true);
setError(null);

console.log("BOARD ID ", boardId);
try {
const response = await axios.get(
`${import.meta.env.VITE_BACKEND_URL}/api/templates/${boardId}`
);
setIsLoading(false);

// inspect what's coming from the API
console.log("API Response Data:", response.data);

const cards = response.data.map((datapt: { [x: string]: any }) => {
let details = JSON.parse(datapt["details"]);
const cardDetails: CardDetails = {
Expand All @@ -25,10 +28,10 @@ const useGetTemplateCards = () => {
};

let card: Card = {
id: datapt["card_id"],
cardName: datapt["card_name"],
column: datapt["column_name"] as Columns,
creationDate: datapt["creation_date"] as Date,
id: datapt["id"],
cardName: datapt["cardName"],
column: datapt["column"] as Columns,
creationDate: datapt["creationDate"] as Date,
order: datapt["order"],
details: cardDetails,
};
Expand Down
25 changes: 16 additions & 9 deletions client/src/hooks/usePostNewCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,21 @@ const usePostNewCard = () => {
const postNewCard = async (card: Card, boardId: string) => {
setIsLoading(true);
setError(null);


const detailsStr = JSON.stringify(card.details);
const token = localStorage.getItem("jwt");
try {
const response = await axios.post(

console.log("CARDoasjidoaknsd", { card });
console.log("BOARDIDAsdjaolnsdk", boardId);
const detailsStr = JSON.stringify(card.details);
const token = localStorage.getItem("jwt");
const dateStr =
card.creationDate instanceof Date
? card.creationDate.toISOString()
: card.creationDate;
try {
const response = await axios.post(
`${import.meta.env.VITE_BACKEND_URL}/api/boards/${boardId}`,
{
cardId: card.id,
cardName: card.cardName,
creationDate: card.creationDate.toISOString(),
creationDate: dateStr,
order: card.order,
column: card.column,
details: detailsStr,
Expand All @@ -33,10 +36,14 @@ const usePostNewCard = () => {
}
);
setIsLoading(false);
console.log(`post response ${response}`);
console.log(`post response ${response.data}`);
return response.data;
} catch (err) {
if (err instanceof Error) {
console.log("ERR POSTING CARD", err);
}
// Error specific to board name already in use

if (axios.isAxiosError(err) && err.response?.status === 400) {
const errorMessage = err.response.data.error;
if (errorMessage) {
Expand Down