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

fix: voting updates #711

Merged
merged 3 commits into from
Dec 19, 2022
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
5 changes: 5 additions & 0 deletions backend/src/modules/votes/services/create.vote.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ export default class CreateVoteServiceImpl implements CreateVoteService {
new: true
}
)
.populate({
path: 'users',
select: 'user role votesCount -board',
populate: { path: 'user', select: 'firstName lastName _id' }
})
.lean()
.exec();

Expand Down
5 changes: 5 additions & 0 deletions backend/src/modules/votes/services/delete.vote.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,11 @@ export default class DeleteVoteServiceImpl implements DeleteVoteService {
new: true
}
)
.populate({
path: 'users',
select: 'user role votesCount -board',
populate: { path: 'user', select: 'firstName lastName _id' }
})
.lean()
.exec();

Expand Down
14 changes: 1 addition & 13 deletions frontend/src/api/boardService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,19 +166,7 @@ export const deleteVoteRequest = (voteDto: VoteDto): Promise<BoardType> =>
{ method: 'DELETE', data: voteDto },
);

export const handleVotes = (voteDto: {
cardId: string;

cardItemId?: string;

boardId: string;

socketId?: string;

isCardGroup: boolean;

count: number;
}) =>
export const handleVotes = (voteDto: VoteDto) =>
fetchData<BoardType>(
voteDto.isCardGroup
? `/boards/${voteDto.boardId}/card/${voteDto.cardId}/vote`
Expand Down
36 changes: 20 additions & 16 deletions frontend/src/components/Board/Column/Column.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import { Droppable } from '@hello-pangea/dnd';

import Flex from '@/components/Primitives/Flex';
Expand Down Expand Up @@ -33,12 +33,6 @@ const Column = React.memo<ColumnBoardType>(
const setFilteredColumns = useSetRecoilState(filteredColumnsState);

const filteredCards = useCallback(() => {
if (filter) {
setFilteredColumns((prev) => {
if (prev.includes(columnId)) return prev;
return [...prev, columnId];
});
}
switch (filter) {
case 'asc':
return [...cards].sort((a, b) => {
Expand All @@ -53,17 +47,27 @@ const Column = React.memo<ColumnBoardType>(
return votesB - votesA;
});
default:
setFilteredColumns((prev) => {
const newValues = [...prev];
const index = newValues.indexOf(columnId);
if (index > -1) {
newValues.splice(index, 1);
}
return newValues;
});
return cards;
}
}, [cards, columnId, filter, setFilteredColumns]);
}, [cards, filter]);

useEffect(() => {
if (filter) {
setFilteredColumns((prev) => {
if (prev.includes(columnId)) return prev;
return [...prev, columnId];
});
} else {
setFilteredColumns((prev) => {
const newValues = [...prev];
const index = newValues.indexOf(columnId);
if (index > -1) {
newValues.splice(index, 1);
}
return newValues;
});
}
}, [columnId, filter, setFilteredColumns]);

return (
<OuterContainer>
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/hooks/useBoard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const useBoard = ({ autoFetchBoard = false }: AutoFetchProps): UseBoardType => {

const updateBoard = useMutation(updateBoardRequest, {
onSuccess: () => {
queryClient.invalidateQueries('board');
queryClient.invalidateQueries(['board', { id: boardId }]);

setToastState({
open: true,
Expand All @@ -75,6 +75,7 @@ const useBoard = ({ autoFetchBoard = false }: AutoFetchProps): UseBoardType => {
});
},
onError: (error: AxiosError) => {
queryClient.invalidateQueries(['board', { id: boardId }]);
const errorMessage = error.response?.data.message.includes('max votes')
? error.response?.data.message
: 'Error updating the board';
Expand Down
83 changes: 46 additions & 37 deletions frontend/src/hooks/useVotes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ const useVotes = () => {

const getBoardQueryKey = (boardId = ''): QueryKeyType => ['board', { id: boardId }];

const setPreviousBoardQuery = (id: string, context: any) => {
queryClient.setQueryData(
getBoardQueryKey(id),
(context as { previousBoard: BoardType }).previousBoard,
);
};

const getFirstCardItemIndexWithVotes = (cardItems: CardItemType[]) =>
cardItems.findIndex((cardItem) => cardItem.votes.length > 0);

Expand Down Expand Up @@ -65,6 +72,17 @@ const useVotes = () => {
return newBoardData;
};

const updateBoardUser = (boardData: BoardType, action: Action) => {
boardData.users = boardData.users.map((boardUser) => {
if (boardUser.user._id !== userId) return boardUser;

return {
...boardUser,
votesCount: action === Action.Add ? boardUser.votesCount + 1 : boardUser.votesCount - 1,
};
});
};

const updateCardItemVoteOptimistic = (
prevBoardData: BoardType,
indexes: number[],
Expand Down Expand Up @@ -145,7 +163,7 @@ const useVotes = () => {
voteData: voteDto,
action: Action,
) => {
const { cardId, cardItemId, isCardGroup } = voteData;
const { cardId, cardItemId, isCardGroup, count } = voteData;

const [colIndex, cardIndex, cardItemIndex] = [-1, -1, -1];
let indexes = [colIndex, cardIndex, cardItemIndex];
Expand All @@ -165,7 +183,15 @@ const useVotes = () => {
);

if (foundCardItem) {
return updateCardOrCardIndexVotesOptimistic(prevBoardData, indexes, isCardGroup, action);
const newBoard = updateCardOrCardIndexVotesOptimistic(
prevBoardData,
indexes,
isCardGroup,
action,
);
updateBoardUser(newBoard, count > 0 ? Action.Add : Action.Remove);

return newBoard;
}

return prevBoardData;
Expand All @@ -185,11 +211,6 @@ const useVotes = () => {
return { newBoardData, prevBoardData };
};

const addVoteOptimistic = async (voteData: voteDto) => updateVoteOptimistic(Action.Add, voteData);

const removeVoteOptimistic = async (voteData: voteDto) =>
updateVoteOptimistic(Action.Remove, voteData);

const buildToastMessage = (
toastMessage: string,
toastStateType: ToastStateEnum,
Expand All @@ -209,39 +230,27 @@ const useVotes = () => {
}
};

const restoreBoardDataAndToastError = (
prevBoardData: BoardType | undefined,
{ boardId }: voteDto,
errorMessage: string,
) => {
queryClient.setQueryData(getBoardQueryKey(boardId), prevBoardData);

toastErrorMessage(errorMessage);
};

const invalidateQueriesAndToastMessage = (
boardDataFromApi: BoardType | undefined,
message: string,
) => {
queryClient.invalidateQueries(getBoardQueryKey(boardDataFromApi?._id));

toastRemainingVotesMessage(message, boardDataFromApi);
};

const handleVote = useMutation(handleVotes, {
onSuccess: (voteData, variables) => {
if (voteData.maxVotes) {
toastRemainingVotesMessage('', voteData);
onMutate: async (variables) => {
const { newBoardData, prevBoardData } = await updateVoteOptimistic(
variables.count > 0 ? Action.Add : Action.Remove,
variables,
);

if (newBoardData?.maxVotes && newBoardData) {
toastRemainingVotesMessage('', newBoardData);
}

return { previousBoard: prevBoardData, variables };
},
onSettled: (data, error, variables, context) => {
if (error) {
queryClient.invalidateQueries(['board', { id: data?._id }]);
}
queryClient.invalidateQueries(['board', { id: voteData?._id }]);
},
onError: (error, variables) => {
queryClient.invalidateQueries(['board', { id: variables.boardId }]);
setToastState({
open: true,
content: 'Error adding the vote',
type: ToastStateEnum.ERROR,
});
onError: (error, variables, context) => {
setPreviousBoardQuery(variables.boardId, context);
toastErrorMessage(`Error ${variables.count > 0 ? 'adding' : 'removing'} the vote`);
},
});

Expand Down
2 changes: 2 additions & 0 deletions frontend/src/types/vote/vote.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ export default interface VoteDto {
socketId?: string;

isCardGroup: boolean;

count: number;
}