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

#110 fix : 헤더 진행률 & 알람 종류 추가 #111

Merged
merged 2 commits into from
Nov 13, 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
5 changes: 3 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import ProfileEdit from './components/ProfileEdit';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
import { useSSE } from './hooks/useSSE';
import ProtectedRoute from './components/ProtectedRoute';
import Error404Page from './pages/Error404Page';
import Error403Page from './pages/Error403Page';
Expand All @@ -33,16 +32,17 @@ import { MobileDisplay } from './styles/ErrorPageStyled';
import RouteChangeTracker from './components/RouteChangeTracker';
import PersonalDashboard from './components/PersonalDashboard';
import TeamDashBoard from './components/TeamDashboard';
import { useSSE } from './hooks/useSSE';
import ConnectionsPage from './pages/ConnectionsPage/ConnectionsPage';
import ConnectionsSearchPage from './pages/ConnectionsSearchPage/ConnectionsSearchPage';


const queryClient = new QueryClient();

const useAuth = () => {
const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(true);

useSSE();
useEffect(() => {
const refreshToken = localStorage.getItem('refreshToken');
if (refreshToken) {
Expand All @@ -56,6 +56,7 @@ const useAuth = () => {
};

const App = () => {
useSSE();
const isMobile = useMediaQuery({ query: '(max-width: 1000px)' });
const { isLoggedIn, loading } = useAuth();

Expand Down
10 changes: 10 additions & 0 deletions src/api/MyPageApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,13 @@ export const updateAlarmIsRead = async () => {
console.error('Error fetching data :', error);
}
};

// * 친구 요청 알람 수락
export const acceptFriendAlarm = async (followId: string) => {
try {
const response = await axiosInstance.post(`/member/follow/accept/${followId}`);
console.log(response);
} catch (error) {
console.error('Error fetching data :', error);
}
};
53 changes: 42 additions & 11 deletions src/components/AlarmBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,52 @@ import { postTeamDashboard } from '../api/TeamDashBoardApi';
import { customErrToast } from '../utils/customErrorToast';
import { useAtom } from 'jotai';
import { navbarUpdateTriggerAtom } from '../contexts/atoms';
import { acceptFriendAlarm } from '../api/MyPageApi';

type Props = {
message: string;
isRead: boolean;
};
const AlarmBlock = ({ message, isRead }: Props) => {
const modifiedMessage = message.replace(/^[^:]+: /, '');
let modifiedMessage = '';
let followerIdMatch: string = '';

if (message.includes('followerId')) {
const matchResult = message.match(/followerId(\d+)/);
followerIdMatch = matchResult ? matchResult[1] : '';
} else if (message.includes('teamdashbord')) {
const matchResult = message.match(/teamdashbord(\d+)/);
modifiedMessage = matchResult ? matchResult[1] : '';
}

let nameMatch;
let dashboardMatch;
let description;
let wordsBeforeLastDashboard: string;

if (message.includes('팀 대시보드 초대')) {
nameMatch = modifiedMessage.split('님')[0];
dashboardMatch = modifiedMessage.match(/\s(.+?)\s대시보드/);
description = `${dashboardMatch ? dashboardMatch[1] : ''} 대시보드 초대`;
nameMatch = message.match(/([a-zA-Z가-힣]+)님/)?.[1] + '님이' || '';
const trimmedMessage = message.trim();
const dashboardIndex = trimmedMessage.lastIndexOf('대시보드');
const nameEndIndex = trimmedMessage.indexOf('님');
wordsBeforeLastDashboard = trimmedMessage.slice(nameEndIndex + 2, dashboardIndex);
description = `${wordsBeforeLastDashboard} 대시보드에 초대했어요!`;
} else if (message.includes('팀 초대 수락')) {
nameMatch = modifiedMessage.split('님')[0];
description = `초대를 수락하였습니다`;
const colonIndex = message.indexOf(':');
const nameEndIndex = message.indexOf('님');
nameMatch = `${message.slice(colonIndex + 2, nameEndIndex)}님이`;
description = `초대를 수락했어요`;
} else if (message.includes('챌린지 블록이 생성되었습니다')) {
const index = modifiedMessage.indexOf('챌린지 블록이 생성되었습니다');
const index = message.indexOf('챌린지 블록이 생성되었습니다');
nameMatch = message.slice(0, index).trim();
description = '챌린지 블록이 생성되었습니다';
description = '챌린지 블록이 생성됐어요';
} else if (message.includes('친구 신청을 보냈습니다.')) {
nameMatch = `${message.split('님')[0]}님이`;
description = `친구 요청을 보냈어요!`;
} else {
nameMatch = `반가워요! ${modifiedMessage.split('님')[0]}님이`;
description = `챌린지에 참여했습니다`;
const index = message.indexOf('님');
nameMatch = `반가워요! ${message.slice(message.indexOf(' ') + 5, index)}님이`;
description = `챌린지에 참여했어요`;
}
const numberMatch = modifiedMessage.match(/\d+$/);

Expand All @@ -41,11 +62,16 @@ const AlarmBlock = ({ message, isRead }: Props) => {
const onAcceptHandler = async () => {
const response = await postTeamDashboard(number);
if (response) {
customErrToast(`${dashboard} 초대를 수락했습니다.`);
customErrToast(`${wordsBeforeLastDashboard}대시보드 초대를 수락했어요!`);
}
setUpdate(prev => !prev);
};

const onAcceptFriend = async () => {
await acceptFriendAlarm(followerIdMatch);
customErrToast(`${message.split('님')[0]}님의 친구요청을 수락했어요!`);
};

return (
<AlarmContainer isRead={isRead}>
<Flex alignItems="center">
Expand All @@ -54,6 +80,11 @@ const AlarmBlock = ({ message, isRead }: Props) => {
<p>{description}</p>
</UserInfoContainer>
{number !== '' ? <button onClick={onAcceptHandler}>수락</button> : ''}
{message.includes('친구 신청을 보냈습니다.') === true ? (
<button onClick={onAcceptFriend}>수락</button>
) : (
''
)}
</Flex>
</AlarmContainer>
);
Expand Down
19 changes: 14 additions & 5 deletions src/components/Graph.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
import { useState } from 'react';
import axios from 'axios';
import { getPersonalDashboard } from '../api/BoardApi';
import * as S from '../styles/DashboardStyled';
import Flex from './Flex';
import { DashboardItem } from '../types/PersonalDashBoard';
import { axiosInstance } from '../utils/apiConfig';
import useItems from '../hooks/useItems';
import { TPages } from '../utils/columnsConfig';

type GraphProps = {
blockProgress: number;
blockTotal: TPages;
};

const Graph = ({ blockProgress }: GraphProps) => {
const Graph = ({ blockTotal }: GraphProps) => {
let progress =
(blockTotal.completed / (blockTotal.todo + blockTotal.doing + blockTotal.completed)) * 100;

if (Number.isNaN(progress)) progress = 0;
return (
<S.GraphContainer>
<Flex>
<S.GraphWrapper>
<S.GraphProgress blockProgress={blockProgress}></S.GraphProgress>
<S.GraphProgress blockProgress={progress.toFixed(1)}></S.GraphProgress>
</S.GraphWrapper>
<span>{blockProgress}%</span>
<span>{progress.toFixed(1)}%</span>
Comment on lines +23 to +25
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파라미터로 1은 왜 전달하는지 궁금합니다!~

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 저게 소수점 밑에 1자리 수로 나오게 하려고 전달한거에요~

</Flex>
</S.GraphContainer>
);
Expand Down
14 changes: 8 additions & 6 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@ import Flex from './Flex';
import setting from '../img/setting.png';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import * as S from '../styles/HeaderStyled';
import { useQuery } from '@tanstack/react-query';
import { getPersonalDashboard } from '../api/BoardApi';
import { TPages } from '../utils/columnsConfig';

type Props = {
mainTitle: string;
subTitle: string;
blockProgress: number;
mainTitle?: string;
subTitle?: string;
dashboardType?: boolean;
blockTotal?: TPages;
};

const Header = ({ mainTitle, subTitle, blockProgress, dashboardType }: Props) => {
const Header = ({ mainTitle, subTitle, dashboardType, blockTotal }: Props) => {
const navigate = useNavigate();
const location = useLocation();
const dashboardId = location.pathname.split('/')[2];
Expand Down Expand Up @@ -49,8 +52,7 @@ const Header = ({ mainTitle, subTitle, blockProgress, dashboardType }: Props) =>
</Flex>
</S.HeaderContentContainer>
<Flex>
<Graph blockProgress={blockProgress} />

{blockTotal && <Graph blockTotal={blockTotal} />}
{!dashboardType && (
<Link to={`/${dashboardId}/teamdocument`}>
<S.TeamDocButton>팀문서</S.TeamDocButton>
Expand Down
36 changes: 33 additions & 3 deletions src/components/PersonalDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import DeleteButton from './DeleteButton';
import { TItems, TItemStatus } from '../utils/columnsConfig';
import useItems from '../hooks/useItems';
import { BlockListResDto } from '../types/PersonalBlock';
import { useDebounce } from '../hooks/useDebounce';
import { useSSE } from '../hooks/useSSE';

type PageState = {
todo: number; // 할 일 페이지 번호
Expand Down Expand Up @@ -48,8 +48,9 @@ const PersonalDashBoard = () => {
hasMoreInProgress,
fetchNextCompleted,
hasMoreCompleted,
blockTotal,
setBlockTotal,
} = useItems(dashboardId, page, location.pathname);
// console.log(items);

const { data: PersonalDashboardInfo } = useQuery({
queryKey: ['PersonalDashboardInfo', dashboardId],
Expand Down Expand Up @@ -142,6 +143,35 @@ const PersonalDashBoard = () => {
updateState(destinationKey, sourceKey, targetItem);
}

//시작점 상태에서 종착지가 시작점 상태와는 다른 상태일때 그 아이템 개수 -1
if (source.droppableId === 'todo' && destination.droppableId !== 'todo')
setBlockTotal(prev => ({
...prev,
todo: blockTotal.todo - 1,
[destination.droppableId]:
blockTotal[destination.droppableId as keyof typeof blockTotal] + 1,
}));
else if (source.droppableId === 'doing' && destination.droppableId !== 'doing')
setBlockTotal(prev => ({
...prev,
doing: blockTotal.doing - 1,
[destination.droppableId]:
blockTotal[destination.droppableId as keyof typeof blockTotal] + 1,
}));
else if (source.droppableId === 'completed' && destination.droppableId !== 'completed')
setBlockTotal(prev => ({
...prev,
completed: blockTotal.completed - 1,
[destination.droppableId]:
blockTotal[destination.droppableId as keyof typeof blockTotal] + 1,
}));
else if (source.droppableId === 'delete' && destination.droppableId !== 'delete')
setBlockTotal(prev => ({
...prev,
delete: blockTotal.completed - 1,
[destination.droppableId]:
blockTotal[destination.droppableId as keyof typeof blockTotal] + 1,
}));
Comment on lines +146 to +174
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

function updateBlockTotal(sourceId: string, destinationId: string) {
    if (sourceId !== destinationId) {
        setBlockTotal(prev => ({
            ...prev,
            [sourceId]: blockTotal[sourceId as keyof typeof blockTotal] - 1,
            [destinationId]: blockTotal[destinationId as keyof typeof blockTotal] + 1,
        }));
    }
}

// 호출 부분
updateBlockTotal(source.droppableId, destination.droppableId);

위와 같이 중복되는 부분을 함수로 분리하면 더 간결하게 작성할 수 있을 것 같아요!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

조언 감사합니다!
추후에 수정할게요!

updateOrder(_items);
};

Expand All @@ -151,8 +181,8 @@ const PersonalDashBoard = () => {
<Header
mainTitle={PersonalDashboardInfo?.title || ''}
subTitle={PersonalDashboardInfo?.description || ''}
blockProgress={(Math.floor(PersonalDashboardInfo?.blockProgress ?? 0) * 10) / 10}
dashboardType={true}
blockTotal={blockTotal}
/>
<DragDropContext onDragEnd={onDragEnd}>
<S.CardContainer>
Expand Down
36 changes: 35 additions & 1 deletion src/components/TeamDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as S from '../styles/MainPageStyled';
import useItems from '../hooks/useItems';
import { BlockListResDto } from '../types/PersonalBlock';
import { TItems, TItemStatus } from '../utils/columnsConfig';
import { useSSE } from '../hooks/useSSE';

type PageState = {
todo: number; // 할 일 페이지 번호
Expand Down Expand Up @@ -47,6 +48,8 @@ const TeamDashBoard = () => {
hasMoreInProgress,
fetchNextCompleted,
hasMoreCompleted,
blockTotal,
setBlockTotal,
} = useItems(dashboardId, page, location.pathname);

const { data: TeamDashboardInfo } = useQuery({
Expand Down Expand Up @@ -134,6 +137,36 @@ const TeamDashBoard = () => {
updateState(destinationKey, targetItem);
}

//시작점 상태에서 종착지가 시작점 상태와는 다른 상태일때 그 아이템 개수 -1
if (source.droppableId === 'todo' && destination.droppableId !== 'todo')
setBlockTotal(prev => ({
...prev,
todo: blockTotal.todo - 1,
[destination.droppableId]:
blockTotal[destination.droppableId as keyof typeof blockTotal] + 1,
}));
else if (source.droppableId === 'doing' && destination.droppableId !== 'doing')
setBlockTotal(prev => ({
...prev,
doing: blockTotal.doing - 1,
[destination.droppableId]:
blockTotal[destination.droppableId as keyof typeof blockTotal] + 1,
}));
else if (source.droppableId === 'completed' && destination.droppableId !== 'completed')
setBlockTotal(prev => ({
...prev,
completed: blockTotal.completed - 1,
[destination.droppableId]:
blockTotal[destination.droppableId as keyof typeof blockTotal] + 1,
}));
else if (source.droppableId === 'delete' && destination.droppableId !== 'delete')
setBlockTotal(prev => ({
...prev,
delete: blockTotal.completed - 1,
[destination.droppableId]:
blockTotal[destination.droppableId as keyof typeof blockTotal] + 1,
}));

updateOrder(_items);
};
return (
Expand All @@ -142,7 +175,8 @@ const TeamDashBoard = () => {
<Header
mainTitle={TeamDashboardInfo?.title || ''}
subTitle={TeamDashboardInfo?.description || ''}
blockProgress={(Math.floor(TeamDashboardInfo?.blockProgress ?? 0) * 10) / 10}
dashboardType={false}
blockTotal={blockTotal}
/>
<DragDropContext onDragEnd={onDragEnd}>
<S.CardContainer>
Expand Down
Loading