Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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
10 changes: 10 additions & 0 deletions src/api/workspace/org.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ICommonResponse } from "@/types/common/common";
import {
type TAcceptInvitationResponse,
Comment thread
jjjsun marked this conversation as resolved.
Resolved
type TCreateOrgRequest,
type TCreateOrgResponse,
type TDeleteWorkspaceMemberResponse,
Expand Down Expand Up @@ -154,3 +155,12 @@ export const getSavedWorkspace = async () => {
export const saveSelectedWorkspace = async (orgId: number): Promise<void> => {
await axiosInstance.post(`/api/org/${orgId}/workspace`);
};

export const acceptInvitaton = async (
token: string,
): Promise<TAcceptInvitationResponse> => {
const { data } = await axiosInstance.post<
ICommonResponse<TAcceptInvitationResponse>
>(`/api/org/invitations/${token}`);
return data.data;
};
20 changes: 15 additions & 5 deletions src/components/common/error/ErrorLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type ReactNode } from "react";
import { Fragment, type ReactNode } from "react";
import { motion, useReducedMotion } from "framer-motion";

import WarningIcon from "@/assets/icon/ai/warning.svg?react";
Expand All @@ -10,6 +10,16 @@ interface IErrorLayoutProps {
actions: ReactNode;
}

function renderMultilineText(text: string) {
// 실제 개행과 문자 그대로의 "\n" 둘 다 줄바꿈으로 처리
return text.split(/\r?\n|\\n/).map((line, index) => (
<Fragment key={index}>
{index > 0 && <br />}
{line}
</Fragment>
));
}

function ErrorLayout({ title, description, actions }: IErrorLayoutProps) {
const reduceMotion = useReducedMotion();

Expand All @@ -32,19 +42,19 @@ function ErrorLayout({ title, description, actions }: IErrorLayoutProps) {
</motion.div>

<motion.h1
className="mb-4 text-balance font-heading1 text-text-title"
className="mb-4 break-keep font-heading1 text-text-title"
variants={itemVariants}
custom={!!reduceMotion}
>
{title}
{renderMultilineText(title)}
</motion.h1>

<motion.p
className="whitespace-pre-line break-keep font-body1 leading-relaxed text-text-auth-sub"
className="break-keep font-body1 leading-relaxed text-text-auth-sub"
variants={itemVariants}
custom={!!reduceMotion}
>
{description}
{renderMultilineText(description)}
</motion.p>

<motion.div
Expand Down
220 changes: 220 additions & 0 deletions src/pages/workspace/InviteAcceptPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
import { useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";

import type { IApiErrorResponse } from "@/types/common/common";
import type { TAcceptInvitationResponse } from "@/types/workspace/workspace";

import { buildPathWithReturnUrl } from "@/utils/auth/returnUrl";

import { useCoreMutation } from "@/hooks/customQuery";

import Button from "@/components/common/button/Button";
import ErrorLayout from "@/components/common/error/ErrorLayout";

import { acceptInvitaton, saveSelectedWorkspace } from "@/api/workspace/org";
import { QUERY_KEYS } from "@/lib/queryKeys";
import useAuthStore from "@/store/useAuthStore";
import useWorkspaceStore from "@/store/useWorkspaceStore";

type TInviteUiStatus =
| "loading"
| "needLogin"
| "invalidToken"
| "error"
| "success";

const LOGIN_REDIRECT_SECONDS = 3;

function getInviteErrorCopy(error: IApiErrorResponse | null): {
title: string;
description: string;
} {
const message = error?.message ?? "";
const code = error?.code ?? "";

if (
code.includes("EXPIRED") ||
code.includes("ORG_INVITATION_400") ||
message.includes("만료") ||
message.includes("유효하지 않") ||
message.toLowerCase().includes("expired") ||
message.toLowerCase().includes("invalid")
) {
return {
title: "초대 링크가 만료되었거나\n유효하지 않습니다",
description:
"초대 링크가 만료되었거나 더 이상 사용할 수 없습니다.\n워크스페이스 관리자에게 다시 초대를 요청해 주세요",
};
}
if (
code.includes("ALREADY") ||
message.includes("이미") ||
message.toLowerCase().includes("already")
) {
return {
title: "이미 완료된 초대입니다",
description: "이미 이 워크스페이스에 참여중이거나 초대 완료한 상태입니다",
};
}
if (
code.includes("EMAIL") ||
message.includes("이메일") ||
message.toLowerCase().includes("email")
) {
return {
title: "초대 이메일이\n일치하지 않습니다",
description:
"초대받은 이메일 계정으로 로그인한 뒤\n다시 링크를 열어주세요",
};
}

return {
title: "초대를 수락할 수 없습니다",
description:
message ||
"초대 처리 중 오류가 발생했습니다.\n잠시 후 다시 시도해 주세요",
};
}

export default function InviteAcceptPage() {
const { token } = useParams<{ token: string }>();
const nav = useNavigate();

const isLoggedIn = useAuthStore((s) => s.isLoggedIn);
const isTokenInitialized = useAuthStore((s) => s.isTokenInitialized);
const setSelectedOrgId = useWorkspaceStore((s) => s.setSelectedOrgId);

const [uiStatus, setUiStatus] = useState<TInviteUiStatus>("loading");
const [acceptError, setAcceptError] = useState<IApiErrorResponse | null>(
null,
);
const [countdown, setCountdown] = useState(LOGIN_REDIRECT_SECONDS);
const processedRef = useRef<string | null>(null);

const { mutate: acceptInvite } = useCoreMutation(acceptInvitaton, {
invalidateKeys: [QUERY_KEYS.workspace.list(), QUERY_KEYS.workspace.saved()],
userOnSuccess: async (data: TAcceptInvitationResponse) => {
await saveSelectedWorkspace(data.orgId);
Comment thread
jjjsun marked this conversation as resolved.
Resolved
setSelectedOrgId(data.orgId);
toast.success(data.message || "초대를 수락했습니다");
setUiStatus("success");
nav("/dashboard", { replace: true });
},
userOnError: (err) => {
setAcceptError(err);
setUiStatus("error");
},
});
Comment thread
jjjsun marked this conversation as resolved.
Resolved

const acceptInviteRef = useRef(acceptInvite);
acceptInviteRef.current = acceptInvite;

useEffect(() => {
if (!isTokenInitialized) return;

if (!token) {
setUiStatus("invalidToken");
return;
}

if (!isLoggedIn) {
setUiStatus("needLogin");
return;
}

if (processedRef.current === token) return;
processedRef.current = token;
setAcceptError(null);
setUiStatus("loading");
acceptInviteRef.current(token);
}, [isTokenInitialized, isLoggedIn, token]);

useEffect(() => {
if (uiStatus !== "needLogin" || !token) return;

setCountdown(LOGIN_REDIRECT_SECONDS);

const interval = window.setInterval(() => {
setCountdown((prev) => Math.max(prev - 1, 0));
}, 1000);

const timer = window.setTimeout(() => {
nav(buildPathWithReturnUrl("/login", `/invite/${token}`), {
replace: true,
});
}, LOGIN_REDIRECT_SECONDS * 1000);

return () => {
window.clearInterval(interval);
window.clearTimeout(timer);
};
}, [uiStatus, token, nav]);

const invalidTokenError: IApiErrorResponse = {
status: "error",
code: "INVALID_TOKEN",
message: "유효하지 않은 초대 링크입니다",
method: "POST",
requestURI: "/api/org/invitations",
};

if (uiStatus === "invalidToken" || uiStatus === "error") {
const copy = getInviteErrorCopy(
uiStatus === "invalidToken" ? invalidTokenError : acceptError,
);
return (
<ErrorLayout
title={copy.title}
description={copy.description}
actions={
<>
<Button
size="big"
variant="primary"
fullWidth
onClick={() => nav("/login", { replace: true })}
>
로그인으로 이동
</Button>
<Button
size="big"
variant="secondary"
fullWidth
onClick={() => nav("/", { replace: true })}
>
홈으로 이동
</Button>
</>
}
/>
);
}

if (uiStatus === "needLogin") {
return (
<div className="relative flex h-screen w-full flex-col items-center justify-center gap-5 bg-surface-100">
<span
className="h-12 w-12 animate-spin rounded-full border-4 border-primary-400 border-t-transparent"
aria-hidden
/>
<p className="text-center font-heading3 text-text-title">
로그인이 필요합니다
</p>
<p className="text-center font-body1 text-text-muted">
{countdown}초 후 로그인 페이지로 이동합니다
</p>
</div>
);
}

return (
<div className="relative flex h-screen w-full items-center justify-center bg-surface-100">
<p className="animate-pulse font-body1 text-text-muted">
{uiStatus === "success"
? "워크스페이스로 이동 중..."
: "초대를 확인하는 중..."}
</p>
</div>
);
}
9 changes: 9 additions & 0 deletions src/routes/AuthRoutes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ const RedirectPage = loadable(

const Signup = lazy(() => import("@/pages/auth/Signup"));

const InviteAcceptPage = loadable(
lazy(() => import("@/pages/workspace/InviteAcceptPage")),
<AuthFormSkeleton />,
);

function SignupPage() {
const location = useLocation();
const step = location.state?.step;
Expand Down Expand Up @@ -69,6 +74,10 @@ const AuthRoutes: RouteObject[] = [
path: "oauth2/meta/result",
element: <MetaOAuthResultPage />,
},
{
path: "invite/:token",
element: <InviteAcceptPage />,
},
];

export default AuthRoutes;
6 changes: 6 additions & 0 deletions src/types/workspace/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,9 @@ export type TPendingMemberData = {
export type TPendingMemberResponse = {
pendingMembers: TPendingMemberData[];
};

export type TAcceptInvitationResponse = {
orgId: number;
message: string;
email: string;
};
Comment thread
jjjsun marked this conversation as resolved.
Resolved
Loading