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

refactor: remove unnecessary teams recoil state #1327

Merged
merged 6 commits into from
Mar 31, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ describe('GetTeamService', () => {
expect(getTeamUserServiceMock.getAllTeamsOfUser).toHaveBeenCalled();
expect(teamRepositoryMock.getTeamsWithUsers).toHaveBeenCalled();
expect(getBoardServiceMock.getAllMainBoards).toHaveBeenCalled();
expect(result).toEqual(expectedResult);
expect(result).toHaveLength(expectedResult.length);
});
});

Expand Down
7 changes: 4 additions & 3 deletions frontend/src/components/Boards/MyBoards/ListBoards/index.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import React from 'react';
import { useRecoilValue } from 'recoil';
import BoardType from '@/types/board/board';
import LoadingPage from '@/components/Primitives/Loading/Page/Page';
import CardBody from '@/components/CardBoard/CardBody/CardBody';
import Flex from '@/components/Primitives/Layout/Flex/Flex';
import Text from '@/components/Primitives/Text/Text';
import Icon from '@/components/Primitives/Icons/Icon/Icon';
import { teamsListState } from '@/store/team/atom/team.atom';
import { Team } from '@/types/team/team';
import Link from 'next/link';
import { TeamUserRoles } from '@/utils/enums/team.user.roles';
import Button from '@/components/Primitives/Inputs/Button/Button';
import useTeams from '@/hooks/teams/useTeams';
import { ScrollableContent } from '../styles';
import TeamHeader from '../../TeamHeader';

Expand All @@ -30,7 +29,9 @@ interface ListBoardsProps {
const ListBoards = React.memo<ListBoardsProps>(
({ userId, isSuperAdmin, dataByTeamAndDate, scrollRef, onScroll, filter, isLoading }) => {
const currentDate = new Date().toDateString();
const allTeamsList = useRecoilValue(teamsListState);
const teamsQuery = useTeams(isSuperAdmin);
const allTeamsList = teamsQuery.data ?? [];

const isTeamAdmin = (boards: Map<string, BoardType[]>) => {
const { team } = Array.from(boards)[0][1][0];
if (!team) return false;
Expand Down
27 changes: 15 additions & 12 deletions frontend/src/components/Boards/MyBoards/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import React, { useEffect, useMemo, useRef } from 'react';
import { useRecoilState, useRecoilValue } from 'recoil';
import { useRecoilState } from 'recoil';

import EmptyBoards from '@/components/Dashboard/RecentRetros/partials/EmptyBoards';
import BoardType from '@/types/board/board';
import { Team } from '@/types/team/team';
import isEmpty from '@/utils/isEmpty';
import { useRouter } from 'next/router';
import { teamsListState } from '@/store/team/atom/team.atom';
import { filterTeamBoardsState } from '@/store/board/atoms/board.atom';
import useBoard from '@/hooks/useBoard';
import useTeams from '@/hooks/teams/useTeams';
import useCurrentSession from '@/hooks/useCurrentSession';
import FilterBoards from '../Filters/FilterBoards';
import ListBoardsByTeam from './ListBoardsByTeam';
import ListBoards from './ListBoards';
Expand All @@ -25,15 +26,17 @@ export interface OptionType {
}

const MyBoards = ({ userId, isSuperAdmin }: MyBoardsProps) => {
const [filterState, setFilterState] = useRecoilState(filterTeamBoardsState);
const scrollRef = useRef<HTMLDivElement>(null);
const router = useRouter();
const { isSAdmin } = useCurrentSession();
const scrollRef = useRef<HTMLDivElement>(null);
const routerTeam = router.query.team as string;
const userTeamsList = useRecoilValue(teamsListState);

const { fetchBoards } = useBoard({ autoFetchBoards: true });
const [filterState, setFilterState] = useRecoilState(filterTeamBoardsState);

const { data, isLoading } = fetchBoards;
const teamsQuery = useTeams(isSAdmin);
const userTeamsList = teamsQuery.data ?? [];
const { fetchBoards } = useBoard({ autoFetchBoards: true });
const { data: paginatedBoards, isLoading } = fetchBoards;

useEffect(() => {
if (routerTeam) setFilterState(routerTeam);
Expand All @@ -44,7 +47,7 @@ const MyBoards = ({ userId, isSuperAdmin }: MyBoardsProps) => {
const teams = new Map<string, Team>();
const boardsTeamAndDate = new Map<string, Map<string, BoardType[]>>();

data?.pages.forEach((page) => {
paginatedBoards?.pages.forEach((page) => {
page.boards?.forEach((board) => {
const boardsOfTeam = boardsTeamAndDate.get(`${board.team?.id ?? `personal`}`);
const date = new Date(board.updatedAt).toDateString();
Expand All @@ -62,7 +65,7 @@ const MyBoards = ({ userId, isSuperAdmin }: MyBoardsProps) => {
});
});
return { boardsTeamAndDate, teams };
}, [data?.pages]);
}, [paginatedBoards?.pages]);

const onScroll = () => {
if (scrollRef.current) {
Expand All @@ -73,14 +76,14 @@ const MyBoards = ({ userId, isSuperAdmin }: MyBoardsProps) => {
}
};

if (filterState === 'all' && isEmpty(dataByTeamAndDate.boardsTeamAndDate.size) && !isLoading)
return <EmptyBoards />;

const teamNames: OptionType[] = userTeamsList.map((team) => ({
value: team.id,
label: team.name,
}));

if (filterState === 'all' && isEmpty(dataByTeamAndDate.boardsTeamAndDate.size) && !isLoading)
return <EmptyBoards />;

const filteredTeam: Team | undefined = userTeamsList.find((team) => team.id === filterState);

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useRouter } from 'next/router';
import React, { useCallback, useEffect, useMemo } from 'react';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { useRecoilState, useSetRecoilState } from 'recoil';

import Icon from '@/components/Primitives/Icons/Icon/Icon';
import {
Expand All @@ -14,32 +14,41 @@ import Flex from '@/components/Primitives/Layout/Flex/Flex';
import Text from '@/components/Primitives/Text/Text';
import useCreateBoard from '@/hooks/useCreateBoard';
import { createBoardTeam } from '@/store/createBoard/atoms/create-board.atom';
import { teamsOfUser, usersListState } from '@/store/team/atom/team.atom';
import { usersListState } from '@/store/team/atom/team.atom';
import { BoardUserRoles } from '@/utils/enums/board.user.roles';
import { TeamUserRoles } from '@/utils/enums/team.user.roles';
import useCurrentSession from '@/hooks/useCurrentSession';
import { UserList } from '@/types/team/userList';
import useTeams from '@/hooks/teams/useTeams';
import { Team } from '@/types/team/team';

const SelectTeam = () => {
const { userId } = useCurrentSession();
const { userId, isSAdmin } = useCurrentSession();
const router = useRouter();
const routerTeam = router.query.team as string;

// Recoil Atoms and Hooks
const [selectedTeam, setSelectedTeam] = useRecoilState(createBoardTeam);
const setUsersList = useSetRecoilState(usersListState);
const teams = useRecoilValue(teamsOfUser);
const { setCreateBoardData } = useCreateBoard(selectedTeam);
const teamsQuery = useTeams(isSAdmin);
const teams = teamsQuery.data ?? [];

const numberOfTeams = teams?.length ?? 0;
const hasPermissions = (team: Team) =>
isSAdmin ||
team.users.find(
(teamUser) =>
teamUser.user._id === userId &&
[TeamUserRoles.ADMIN, TeamUserRoles.STAKEHOLDER].includes(teamUser.role),
);
const availableTeams = teams.filter((team) => hasPermissions(team));

const teamsNames = useMemo(
() =>
teams.map((team) => ({
availableTeams.map((team) => ({
label: `${team.name} (${team.users.length} members)`,
value: team.id,
})),
[teams],
[availableTeams],
);

const createBoard = useCallback(() => {
Expand Down Expand Up @@ -80,14 +89,14 @@ const SelectTeam = () => {
}, [selectedTeam, userId, setCreateBoardData]);

const handleTeamChange = (value: string) => {
const foundTeam = teams.find((team) => team.id === value);
const foundTeam = availableTeams.find((team) => team.id === value);

setSelectedTeam(foundTeam);
};

useEffect(() => {
if (routerTeam) {
const foundTeam = teams.find((team) => team.id === routerTeam);
const foundTeam = availableTeams.find((team) => team.id === routerTeam);
setSelectedTeam(foundTeam);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -102,7 +111,7 @@ const SelectTeam = () => {
return (
<Flex direction="column" css={{ flex: 1 }}>
<Select
disabled={numberOfTeams === 0}
disabled={availableTeams.length === 0}
defaultValue={teamsNames.find((option) => option.value === selectedTeam?.id)?.value}
onValueChange={(selectedOption: string) => {
handleTeamChange(selectedOption);
Expand All @@ -112,7 +121,7 @@ const SelectTeam = () => {
<SelectTrigger css={{ padding: '$24' }}>
<Flex direction="column">
<Text size={selectedTeam ? 'sm' : 'md'} color="primary300">
{numberOfTeams === 0 ? 'No teams available' : 'Select Team'}
{availableTeams.length === 0 ? 'No teams available' : 'Select Team'}
</Text>
<SelectValue />
</Flex>
Expand All @@ -122,7 +131,7 @@ const SelectTeam = () => {
</SelectTrigger>
<SelectContent options={teamsNames} />
</Select>
{numberOfTeams === 0 && (
{availableTeams.length === 0 && (
<Flex justify="start" align="center" gap="4" css={{ mt: '$8', color: '$dangerBase' }}>
<Icon size={16} name="info" />
<Text hint color="dangerBase">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useRouter } from 'next/router';
import React, { useCallback, useEffect, useMemo } from 'react';
import { useFormContext } from 'react-hook-form';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { useRecoilState, useSetRecoilState } from 'recoil';

import Icon from '@/components/Primitives/Icons/Icon/Icon';
import {
Expand All @@ -16,12 +16,12 @@ import Text from '@/components/Primitives/Text/Text';
import useCreateBoard from '@/hooks/useCreateBoard';
import useCurrentSession from '@/hooks/useCurrentSession';
import { createBoardError, createBoardTeam } from '@/store/createBoard/atoms/create-board.atom';
import { teamsOfUser } from '@/store/team/atom/team.atom';
import { Team } from '@/types/team/team';
import { MIN_MEMBERS } from '@/utils/constants';
import { BoardUserRoles } from '@/utils/enums/board.user.roles';
import { TeamUserRoles } from '@/utils/enums/team.user.roles';
import isEmpty from '@/utils/isEmpty';
import useTeams from '@/hooks/teams/useTeams';

type SelectTeamProps = {
previousTeam?: string;
Expand All @@ -32,11 +32,11 @@ const SelectTeam = ({ previousTeam }: SelectTeamProps) => {
const router = useRouter();
const routerTeam = router.query.team as string;

// Recoil Atoms and Hooks
const [selectedTeam, setSelectedTeam] = useRecoilState(createBoardTeam);
const teams = useRecoilValue(teamsOfUser);
const setHaveError = useSetRecoilState(createBoardError);
const { handleSplitBoards, setCreateBoardData, teamMembers } = useCreateBoard(selectedTeam);
const teamsQuery = useTeams(isSAdmin);
const teams = teamsQuery.data ?? [];

const {
setValue,
Expand All @@ -46,16 +46,17 @@ const SelectTeam = ({ previousTeam }: SelectTeamProps) => {
} = useFormContext();

const hasPermissions = (team: Team) =>
!!team.users?.find(
isSAdmin ||
team.users.find(
(teamUser) =>
teamUser.user._id === userId &&
[TeamUserRoles.ADMIN, TeamUserRoles.STAKEHOLDER].includes(teamUser.role),
) || isSAdmin;
);
const availableTeams = teams.filter((team) => hasPermissions(team));

const teamMembersCount = teamMembers?.length ?? 0;
const numberOfTeams = teams?.filter((team) => hasPermissions(team)).length ?? 0;
const message =
numberOfTeams === 0
availableTeams.length === 0
? ' In order to create a team board, you must be team-admin or stakeholder of at least one team.'
: (errors.team?.message as string);
const isHelperEmpty = isEmpty(message);
Expand All @@ -73,38 +74,35 @@ const SelectTeam = ({ previousTeam }: SelectTeamProps) => {
clearErrors();
const foundTeam = teams.find((team) => team.id === value);

setValue('team', foundTeam?.id);
if (!foundTeam) return;

setValue('team', foundTeam.id);
setSelectedTeam(foundTeam);
};

const teamsNames = useMemo(
() =>
teams
.filter((team) => hasPermissions(team))
.map((team) => ({
label: `${team.name} (${team.users.length} members)`,
value: team.id,
})),
[teams],
availableTeams.map((team) => ({
label: `${team.name} (${team.users.length} members)`,
value: team.id,
})),
[availableTeams],
);

const verifyIfCanCreateBoard = useCallback(() => {
const verifyIfCanCreateBoard = () => {
if (!selectedTeam) {
return true;
return false;
}

const haveMinMembers = !!(
selectedTeam.users?.filter((user) => user.role !== TeamUserRoles.STAKEHOLDER).length >=
MIN_MEMBERS
);
const haveMinMembers =
selectedTeam.users.filter((user) => user.role !== TeamUserRoles.STAKEHOLDER).length >=
MIN_MEMBERS;

return !haveMinMembers || !hasPermissions(selectedTeam);
}, [selectedTeam, userId, isSAdmin]);
return haveMinMembers;
};

const createBoard = useCallback(() => {
if (!selectedTeam) {
return;
}
if (!selectedTeam) return;

const maxUsersCount = Math.ceil(teamMembersCount / 2);
const teamsCount = Math.ceil(teamMembersCount / maxUsersCount);
Expand Down Expand Up @@ -135,31 +133,30 @@ const SelectTeam = ({ previousTeam }: SelectTeamProps) => {
}
}, [handleSplitBoards, previousTeam, selectedTeam, setCreateBoardData, teamMembersCount]);

useEffect(() => {
if (routerTeam) {
setValue('team', routerTeam);
}

setHaveError(numberOfTeams <= 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [numberOfTeams]);

useEffect(() => {
if (selectedTeam) {
const canNotCreateBoard = verifyIfCanCreateBoard();

setHaveError(canNotCreateBoard);
const canCreateBoard = verifyIfCanCreateBoard();
setHaveError(!canCreateBoard);

if (!canNotCreateBoard) {
if (canCreateBoard) {
createBoard();
}
}
}, [routerTeam, createBoard, selectedTeam, setHaveError, verifyIfCanCreateBoard]);
}, [routerTeam, selectedTeam, verifyIfCanCreateBoard, createBoard]);

useEffect(() => {
if (routerTeam) {
setValue('team', routerTeam);
}

setHaveError(availableTeams.length <= 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return (
<Flex direction="column" css={{ flex: 1 }}>
<Select
disabled={numberOfTeams === 0}
disabled={availableTeams.length === 0}
hasError={currentSelectTeamState === 'error'}
defaultValue={teamsNames.find((option) => option.value === selectedTeam?.id)?.value}
onValueChange={(selectedOption: string) => {
Expand All @@ -170,7 +167,7 @@ const SelectTeam = ({ previousTeam }: SelectTeamProps) => {
<SelectTrigger css={{ padding: '$24' }}>
<Flex direction="column">
<Text size={selectedTeam ? 'sm' : 'md'} color="primary300">
{numberOfTeams === 0 ? 'No teams available' : 'Select Team'}
{availableTeams.length === 0 ? 'No teams available' : 'Select Team'}
</Text>
<SelectValue />
</Flex>
Expand Down
Loading