;
+ totalWidth: number;
+ columns: ITimelineGridColumn[];
+ colWidth: number;
+ bars: ITimelineCampaignBar[];
+ maxRow: number;
+ viewUnit: TTimelineViewUnit;
+ hasNoVisibleBars: boolean;
+ selectedBarId: number | null;
+ isPanelOpen: boolean;
+ onBarClick: (bar: ITimelineCampaignBar) => void;
+ onEdit: (id: number) => void;
+ onDelete: (target: { id: number; name: string }) => void;
+}
+
+export default function TimelineCanvas({
+ scrollRef,
+ totalWidth,
+ columns,
+ colWidth,
+ bars,
+ maxRow,
+ viewUnit,
+ hasNoVisibleBars,
+ selectedBarId,
+ isPanelOpen,
+ onBarClick,
+ onEdit,
+ onDelete,
+}: ITimelineCanvasProps) {
+ return (
+
+
+
+ {hasNoVisibleBars ? (
+
+
+ 이 기간에 표시할 타임라인이 없어요
+
+
+ 다른 기간으로 이동하거나 보기 단위를 변경해 보세요
+
+
+ ) : (
+
+ {bars.map((bar) => (
+ onEdit(bar.id)}
+ onDelete={() => onDelete({ id: bar.id, name: bar.title })}
+ />
+ ))}
+
+ )}
+
+
+ );
+}
diff --git a/src/components/timeline/TimelineDeleteModal.tsx b/src/components/timeline/TimelineDeleteModal.tsx
new file mode 100644
index 00000000..009e7bd3
--- /dev/null
+++ b/src/components/timeline/TimelineDeleteModal.tsx
@@ -0,0 +1,41 @@
+import Modal from "../common/modal/Modal";
+import ModalContent from "../common/modal/ModalContent";
+
+import TrashIcon from "@/assets/icon/common/trash.svg?react";
+
+interface ITimelineDeleteModalProps {
+ target: { id: number; name: string } | null;
+ isDeleting: boolean;
+ onClose: () => void;
+ onConfirm: () => void;
+}
+
+export default function TimelineDeleteModal({
+ target,
+ isDeleting,
+ onClose,
+ onConfirm,
+}: ITimelineDeleteModalProps) {
+ return (
+
+ }
+ title="해당 타임라인을 삭제할까요?"
+ description={
+ target
+ ? `"${target.name}" 타임라인을 삭제하면 복구할 수 없습니다`
+ : ""
+ }
+ buttonText="삭제하기"
+ onConfirm={onConfirm}
+ isLoading={isDeleting}
+ variant="danger"
+ />
+
+ );
+}
diff --git a/src/components/timeline/TimelineToolbar.tsx b/src/components/timeline/TimelineToolbar.tsx
new file mode 100644
index 00000000..cb2e5b1e
--- /dev/null
+++ b/src/components/timeline/TimelineToolbar.tsx
@@ -0,0 +1,94 @@
+import { twMerge } from "tailwind-merge";
+
+import type { TTimelineSort } from "@/types/timeline/api";
+import type { TTimelineViewUnit } from "@/types/timeline/ui";
+import type { TTimelineStatusFilter } from "@/constants/timeline/filterSort";
+
+import TimelineFilterSortMenus from "./TimelineFilterSortMenus";
+import {
+ TimelinePeriodNav,
+ TimelineViewUnitSegment,
+} from "./TimelinePeriodSelector";
+import TimelineStatusLegend from "./TimelineStatusLegend";
+import Button from "../common/button/Button";
+
+import PlusIcon from "@/assets/icon/common/plus.svg?react";
+
+interface ITimelineToolbarProps {
+ viewUnit: TTimelineViewUnit;
+ periodLabel: string;
+ onViewUnitChange: (unit: TTimelineViewUnit) => void;
+ onPrevPeriod: () => void;
+ onNextPeriod: () => void;
+ onGoToToday: () => void;
+ statusFilter: TTimelineStatusFilter;
+ sort: TTimelineSort;
+ onStatusFilterChange: (value: TTimelineStatusFilter) => void;
+ onSortChange: (value: TTimelineSort) => void;
+ onCreate: () => void;
+}
+
+export default function TimelineToolbar({
+ viewUnit,
+ periodLabel,
+ onViewUnitChange,
+ onPrevPeriod,
+ onNextPeriod,
+ onGoToToday,
+ statusFilter,
+ sort,
+ onStatusFilterChange,
+ onSortChange,
+ onCreate,
+}: ITimelineToolbarProps) {
+ return (
+
+
+
+
+ }
+ className={twMerge(
+ "h-10 shrink-0 rounded-2xl px-4",
+ "bg-primary-400/20 text-primary-500",
+ "font-body2 shadow-Soft",
+ "transition-ui-smooth hover:bg-primary-500/30",
+ "tablet:w-full tablet:justify-center",
+ )}
+ >
+ 타임라인 생성
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/src/components/workspace/InviteMemberModal.tsx b/src/components/workspace/InviteMemberModal.tsx
index 3f6b5b45..9b05de94 100644
--- a/src/components/workspace/InviteMemberModal.tsx
+++ b/src/components/workspace/InviteMemberModal.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { toast } from "sonner";
import type {
@@ -10,13 +10,13 @@ import { emailSchema } from "@/utils/auth/validation";
import { useCoreMutation } from "@/hooks/customQuery";
-import Badge from "../common/badge/Badge";
-import Button from "../common/button/Button";
-import Input from "../common/input/Input";
-import Modal from "../common/modal/Modal";
+import Badge from "@/components/common/badge/Badge";
+import Button from "@/components/common/button/Button";
+import Input from "@/components/common/input/Input";
+import Modal from "@/components/common/modal/Modal";
import { postInviteEmail } from "@/api/workspace/org";
-import CopyIcon from "@/assets/icon/common/link.svg?react";
+import MailIcon from "@/assets/icon/common/mail.svg?react";
import UserIcon from "@/assets/icon/common/user.svg?react";
import { QUERY_KEYS } from "@/lib/queryKeys";
@@ -58,18 +58,6 @@ export default function InviteMemberModal({
const isInviteDisabled = !isValidEmail || inviteMutation.isPending;
- const inviteLink = useMemo(() => {
- return `${window.location.origin}/workspace/${orgId}/invite`;
- }, [orgId]);
- const handleCopyLink = async () => {
- try {
- await navigator.clipboard.writeText(inviteLink);
- toast.success("초대 링크가 복사되었습니다");
- } catch (error) {
- toast.error("초대 링크 복사에 실패했습니다. 다시 시도해주세요");
- console.log("초대 링크 복사 실패:", error);
- }
- };
const handleChangeEmail = (value: string) => {
setForm({ email: value });
};
@@ -99,18 +87,10 @@ export default function InviteMemberModal({
title="팀원 초대하기"
className="w-full max-w-190 overflow-hidden"
>
-
-
+
+
diff --git a/src/components/workspace/PermissionTable.tsx b/src/components/workspace/PermissionTable.tsx
index 6e2d96a3..47f846d7 100644
--- a/src/components/workspace/PermissionTable.tsx
+++ b/src/components/workspace/PermissionTable.tsx
@@ -1,120 +1,98 @@
-import { useMemo, useState } from "react";
-import { toast } from "sonner";
-
import type { TPermissionRow } from "@/types/workspace/workspace";
-import Button from "../common/button/Button";
import Card from "../common/card/Card";
-import Toggle from "../common/toggle/Toggle";
import CheckIcon from "@/assets/icon/common/check.svg?react";
+import CloseIcon from "@/assets/icon/common/close.svg?react";
const permissionRows: TPermissionRow[] = [
{
key: "campaignView",
- label: "광고/캠페인 조회",
+ label: "광고•캠페인 조회",
description: "광고 및 캠페인을 조회할 수 있습니다",
- defaultMemberEnabled: true,
+ memberAllowed: true,
+ },
+ {
+ key: "timelineManage",
+ label: "타임라인 조회•관리",
+ description: "성과 타임라인을 조회하고 생성/수정/삭제할 수 있습니다",
+ memberAllowed: true,
},
{
key: "billingManage",
label: "결제 관리",
description: "구독 플랜 변경 및 결제 수단을 관리합니다",
- defaultMemberEnabled: false,
+ memberAllowed: false,
},
{
key: "workspaceView",
label: "워크스페이스 조회",
description: "워크스페이스에 대한 정보를 조회할 수 있습니다",
- defaultMemberEnabled: true,
+ memberAllowed: true,
},
{
key: "memberInvite",
label: "멤버 초대",
description: "새로운 팀원을 워크스페이스에 초대할 수 있습니다",
- defaultMemberEnabled: true,
+ memberAllowed: false,
},
{
key: "memberRoleEdit",
label: "멤버 역할 변경",
description:
"워크스페이스에 소속되어있는 멤버들의 역할을 변경할 수 있습니다",
- defaultMemberEnabled: false,
+ memberAllowed: false,
},
{
key: "workspaceEdit",
label: "워크스페이스 설정 수정",
- description: "워크스페이스 이름, 로고 등 기본 정보를 수정합니다",
- defaultMemberEnabled: false,
+ description: "워크스페이스 이름/로고 등 기본 정보를 수정합니다",
+ memberAllowed: false,
},
{
key: "projectDelete",
label: "프로젝트 삭제",
description: "생성된 프로젝트를 영구적으로 삭제합니다",
- defaultMemberEnabled: false,
+ memberAllowed: false,
},
];
-type TMemberPermissionState = Record
;
-
-const initialMemberPermissionState: TMemberPermissionState =
- permissionRows.reduce((acc, row) => {
- acc[row.key] = row.defaultMemberEnabled;
- return acc;
- }, {} as TMemberPermissionState);
-
-function AdminCheckBadge() {
+function PermissionAllowedBadge() {
return (
-
-
- 가능
-
+
+
+
);
}
-
-export default function PermissionTable() {
- const [savedPermissionState, setSavedPermissionState] = useState(
- initialMemberPermissionState,
- );
- const [draftPermissionState, setDraftPermissionState] = useState(
- initialMemberPermissionState,
+function PermissionDeniedBadge() {
+ return (
+
+
+
);
- const [isSaving, setIsSaving] = useState(false);
- const hasChanges = useMemo(() => {
- return permissionRows.some(
- (row) => savedPermissionState[row.key] !== draftPermissionState[row.key],
- );
- }, [savedPermissionState, draftPermissionState]);
- const handleToggleMemberPermission = (key: TPermissionRow["key"]) => {
- setDraftPermissionState((prev) => ({
- ...prev,
- [key]: !prev[key],
- }));
- };
- const handleResetChange = () => {
- setDraftPermissionState(savedPermissionState);
- };
- const handleSaveChanges = async () => {
- if (!hasChanges || isSaving) return;
- setIsSaving(true);
- try {
- await new Promise((resolve) => setTimeout(resolve, 500));
- setSavedPermissionState(draftPermissionState);
- toast.success("권한 설정이 저장되었습니다");
- } catch (error) {
- toast.error("권한 설정 저장에 실패했습니다. 다시 시도해주세요");
- console.error("권한 설정 저장 실패", error);
- } finally {
- setIsSaving(false);
- }
- };
+}
+export default function PermissionTable() {
return (
@@ -151,16 +129,16 @@ export default function PermissionTable() {
|
- handleToggleMemberPermission(row.key)}
- ariaLabel={`${row.label} 권한 토글`}
- />
+ {row.memberAllowed ? (
+
+ ) : (
+
+ )}
|
@@ -170,44 +148,10 @@ export default function PermissionTable() {
- {hasChanges ? (
-
- 저장 필요
- ·
- 멤버 권한이 변경되었습니다. 반영하려면 저장을 눌러주세요. 취소하면
- 이전 설정으로 돌아갑니다.
-
- ) : (
-
- 멤버 열의 토글을 바꾼 뒤, 아래에서 저장하거나 변경을 취소할 수
- 있습니다.
-
- )}
-
-
-
-
+
+ 권한은 역할에 따라 고정됩니다. 멤버의 접근 범위를 바꾸려면 위 멤버
+ 목록에서 역할을 변경하세요.
+
);
diff --git a/src/hooks/auth/useLogout.ts b/src/hooks/auth/useLogout.ts
index 1e12ce37..aa58c752 100644
--- a/src/hooks/auth/useLogout.ts
+++ b/src/hooks/auth/useLogout.ts
@@ -16,14 +16,15 @@ export function useLogout() {
return useCoreMutation(postLogout, {
userOnSuccess: () => {
- queryClient.removeQueries({ queryKey: ["my-workspaces"] });
+ toast.success("로그아웃이 완료되었습니다");
+ queryClient.clear();
logout();
nav("/", { replace: true });
},
userOnError: (error) => {
+ const apiError = error as IApiErrorResponse;
const message =
- (error as IApiErrorResponse).message ??
- "로그아웃에 실패했습니다. 다시 시도해주세요";
+ apiError.message ?? "로그아웃에 실패했습니다. 다시 시도해주세요";
toast.error(message);
},
});
diff --git a/src/hooks/setting/useSettingNotifications.ts b/src/hooks/setting/useSettingNotifications.ts
new file mode 100644
index 00000000..f532a6ec
--- /dev/null
+++ b/src/hooks/setting/useSettingNotifications.ts
@@ -0,0 +1,376 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+
+import type { IApiErrorResponse } from "@/types/common/common";
+import type { IUpdateOrgNotificationSettingsRequest } from "@/types/setting/notification";
+import {
+ DEFAULT_CHANNEL,
+ DEFAULT_ORG_NOTIF,
+ DEFAULT_WORKSPACE_NOTIF,
+ type IChannelNotificationSettings,
+ type IOrgNotificationSettings,
+ type IWorkspaceNotificationSettings,
+} from "@/types/setting/settingPage";
+
+import { useCoreQuery } from "@/hooks/customQuery";
+import { useMyNotificationSettings } from "@/hooks/setting/useMyNotificationSettings";
+import { useUpdateAlertsNotificationSettings } from "@/hooks/setting/useUpdateAlertsNotificationSettings";
+import { useUpdateChannelNotificationSettings } from "@/hooks/setting/useUpdateChannelNotificationSettings";
+import { useUpdateMasterNotificationSettings } from "@/hooks/setting/useUpdateMasterNotificationSetting";
+import { useUpdateOrgNotificationSettings } from "@/hooks/setting/useUpdateOrgNotificationSettings";
+
+import { getMyWorkspaces } from "@/api/workspace/org";
+import { QUERY_KEYS } from "@/lib/queryKeys";
+import useWorkspaceStore from "@/store/useWorkspaceStore";
+
+export default function useSettingNotifications() {
+ const [savedChannel, setSavedChannel] =
+ useState
(DEFAULT_CHANNEL);
+ const [draftChannel, setDraftChannel] =
+ useState(DEFAULT_CHANNEL);
+ const [savedWorkspaceNotif, setSavedWorkspaceNotif] =
+ useState(DEFAULT_WORKSPACE_NOTIF);
+ const [draftWorkspaceNotif, setDraftWorkspaceNotif] =
+ useState(DEFAULT_WORKSPACE_NOTIF);
+ const [savedOrgNotif, setSavedOrgNotif] =
+ useState(DEFAULT_ORG_NOTIF);
+ const [draftOrgNotif, setDraftOrgNotif] =
+ useState(DEFAULT_ORG_NOTIF);
+
+ const [slackWebhookUrl, setSlackWebhookUrl] = useState("");
+ const [slackWebhookError, setSlackWebhookError] = useState("");
+ const [discordWebhookUrl, setDiscordWebhookUrl] = useState("");
+ const [discordWebhookError, setDiscordWebhookError] = useState("");
+ const [pendingOrgAction, setPendingOrgAction] = useState<
+ "slack" | "discord" | null
+ >(null);
+
+ const selectedOrgId = useWorkspaceStore((s) => s.selectedOrgId);
+
+ const myRole = useWorkspaceStore((s) => s.myRole);
+ const isAdmin = myRole === "ADMIN";
+
+ const { data: workspaces, isLoading: isWorkspacesLoading } = useCoreQuery(
+ QUERY_KEYS.workspace.list(),
+ getMyWorkspaces,
+ );
+
+ const {
+ data: notificationSettings,
+ isLoading: isNotificationLoading,
+ isRefetching: isNotificationRefetching,
+ isError: isNotificationError,
+ error: notificationError,
+ errorUpdatedAt: notificationErrorUpdatedAt,
+ refetch: refetchNotificationSettings,
+ } = useMyNotificationSettings();
+
+ const lastNotifiedNotificationErrorAtRef = useRef(0);
+ const prevOrgIdRef = useRef(selectedOrgId);
+
+ const updateChannels = useUpdateChannelNotificationSettings();
+ const updateAlerts = useUpdateAlertsNotificationSettings();
+ const updateOrg = useUpdateOrgNotificationSettings();
+ const updateMaster = useUpdateMasterNotificationSettings();
+
+ const currentWorkspaceName = useMemo(() => {
+ if (selectedOrgId === null) return null;
+ return workspaces?.find((w) => w.orgId === selectedOrgId)?.name ?? null;
+ }, [selectedOrgId, workspaces]);
+
+ const workspaceNotifiDisabled =
+ selectedOrgId == null || (!isWorkspacesLoading && !currentWorkspaceName);
+
+ const isNotificationSectionLoading =
+ selectedOrgId !== null &&
+ (isNotificationLoading || isNotificationRefetching);
+
+ const buildOrgBody = (
+ overrides: Partial = {},
+ ): IUpdateOrgNotificationSettingsRequest => ({
+ isSlackEnabled: savedOrgNotif.slackEnabled,
+ slackWebhookUrl: "",
+ disconnectSlack: false,
+ isDiscordEnabled: savedOrgNotif.discordEnabled,
+ discordWebhookUrl: "",
+ disconnectDiscord: false,
+ alertClicks: savedWorkspaceNotif.clickAlarm ?? false,
+ alertReport: savedWorkspaceNotif.weeklyReport ?? false,
+ ...overrides,
+ });
+
+ const handleConnectSlack = async () => {
+ const url = slackWebhookUrl.trim();
+ if (!url) {
+ setSlackWebhookError("Webhook URL을 입력해주세요");
+ return;
+ }
+
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ setSlackWebhookError("올바른 URL 형식으로 입력해주세요");
+ return;
+ }
+ if (parsed.protocol !== "https:" || parsed.hostname !== "hooks.slack.com") {
+ setSlackWebhookError("슬랙 Webhook URL을 입력해주세요");
+ return;
+ }
+
+ setPendingOrgAction("slack");
+ try {
+ await updateOrg.mutateAsync(
+ buildOrgBody({
+ isSlackEnabled: true,
+ slackWebhookUrl: url,
+ disconnectSlack: false,
+ }),
+ );
+ toast.success("슬랙이 연동되었습니다");
+ setSlackWebhookUrl("");
+ setSlackWebhookError("");
+ } catch (e) {
+ const error = e as IApiErrorResponse;
+ toast.error(error.message ?? "슬랙 연동에 실패했습니다");
+ } finally {
+ setPendingOrgAction(null);
+ }
+ };
+
+ const handleDisconnectSlack = async () => {
+ setPendingOrgAction("slack");
+ try {
+ await updateOrg.mutateAsync(
+ buildOrgBody({
+ isSlackEnabled: false,
+ slackWebhookUrl: "",
+ disconnectSlack: true,
+ }),
+ );
+ toast.success("슬랙 연동이 해제되었습니다");
+ } catch (e) {
+ const error = e as IApiErrorResponse;
+ toast.error(error.message ?? "슬랙 연동 해제에 실패했습니다");
+ } finally {
+ setPendingOrgAction(null);
+ }
+ };
+
+ const handleConnectDiscord = async () => {
+ const url = discordWebhookUrl.trim();
+ if (!url) {
+ setDiscordWebhookError("Webhook URL을 입력해주세요");
+ return;
+ }
+ if (!url.startsWith("https://")) {
+ setDiscordWebhookError("올바른 URL 형식으로 입력해주세요");
+ return;
+ }
+
+ setPendingOrgAction("discord");
+ try {
+ await updateOrg.mutateAsync(
+ buildOrgBody({
+ isDiscordEnabled: true,
+ discordWebhookUrl: url,
+ disconnectDiscord: false,
+ }),
+ );
+ toast.success("디스코드가 연동되었습니다");
+ setDiscordWebhookUrl("");
+ setDiscordWebhookError("");
+ } catch (e) {
+ const error = e as IApiErrorResponse;
+ toast.error(error.message ?? "디스코드 연동에 실패했습니다");
+ } finally {
+ setPendingOrgAction(null);
+ }
+ };
+
+ const handleDisconnectDiscord = async () => {
+ setPendingOrgAction("discord");
+ try {
+ await updateOrg.mutateAsync(
+ buildOrgBody({
+ isDiscordEnabled: false,
+ discordWebhookUrl: "",
+ disconnectDiscord: true,
+ }),
+ );
+ toast.success("디스코드 연동이 해제되었습니다");
+ } catch (e) {
+ const error = e as IApiErrorResponse;
+ toast.error(error.message ?? "디스코드 연동 해제에 실패했습니다");
+ } finally {
+ setPendingOrgAction(null);
+ }
+ };
+
+ const handleMasterEnableChange = (value: boolean) => {
+ if (!value) {
+ setDraftOrgNotif((prev) => ({
+ ...prev,
+ masterEnabled: false,
+ slackEnabled: false,
+ discordEnabled: false,
+ }));
+ setDraftChannel({ browserPush: false, emailNotif: false });
+ setDraftWorkspaceNotif({
+ clickAlarm: false,
+ weeklyReport: false,
+ });
+ return;
+ }
+ setDraftOrgNotif((prev) => ({
+ ...prev,
+ masterEnabled: true,
+ slackEnabled: prev.slackConnected && savedOrgNotif.slackEnabled,
+ discordEnabled: prev.discordConnected && savedOrgNotif.discordEnabled,
+ }));
+ setDraftChannel(savedChannel);
+ setDraftWorkspaceNotif(savedWorkspaceNotif);
+ };
+
+ const hasChannelChanges = useMemo(() => {
+ return (
+ savedChannel.browserPush !== draftChannel.browserPush ||
+ savedChannel.emailNotif !== draftChannel.emailNotif
+ );
+ }, [savedChannel, draftChannel]);
+
+ const hasWorkspaceNotifChanges = useMemo(() => {
+ return (
+ savedWorkspaceNotif.clickAlarm !== draftWorkspaceNotif.clickAlarm ||
+ savedWorkspaceNotif.weeklyReport !== draftWorkspaceNotif.weeklyReport
+ );
+ }, [savedWorkspaceNotif, draftWorkspaceNotif]);
+
+ const hasMasterChanges =
+ savedOrgNotif.masterEnabled !== draftOrgNotif.masterEnabled;
+
+ const hasOrgToggleChanges =
+ savedOrgNotif.slackEnabled !== draftOrgNotif.slackEnabled ||
+ savedOrgNotif.discordEnabled !== draftOrgNotif.discordEnabled;
+
+ const hasNotificationChanges =
+ hasChannelChanges ||
+ hasWorkspaceNotifChanges ||
+ hasMasterChanges ||
+ hasOrgToggleChanges;
+
+ useEffect(() => {
+ //워크스페이스 미선택시에만 기본값
+ if (selectedOrgId === null) {
+ setSavedChannel(DEFAULT_CHANNEL);
+ setDraftChannel(DEFAULT_CHANNEL);
+ setSavedWorkspaceNotif(DEFAULT_WORKSPACE_NOTIF);
+ setDraftWorkspaceNotif(DEFAULT_WORKSPACE_NOTIF);
+ setSavedOrgNotif(DEFAULT_ORG_NOTIF);
+ setDraftOrgNotif(DEFAULT_ORG_NOTIF);
+ setSlackWebhookUrl("");
+ setSlackWebhookError("");
+ setDiscordWebhookUrl("");
+ setDiscordWebhookError("");
+ prevOrgIdRef.current = null;
+ return;
+ }
+
+ if (!notificationSettings) return; //로딩,에러면 손대지 않음
+
+ const masterOn = notificationSettings.isMasterEnabled;
+ const nextChannel = {
+ browserPush: masterOn && notificationSettings.isBrowserPushEnabled,
+ emailNotif: masterOn && notificationSettings.isEmailEnabled,
+ };
+ const nextWorkspace = {
+ clickAlarm: masterOn && notificationSettings.alertClicks,
+ weeklyReport: masterOn && notificationSettings.alertReport,
+ };
+ const nextOrg = {
+ masterEnabled: masterOn,
+ slackEnabled: masterOn && notificationSettings.isSlackEnabled,
+ slackConnected: notificationSettings.isSlackConnected,
+ discordEnabled: masterOn && notificationSettings.isDiscordEnabled,
+ discordConnected: notificationSettings.isDiscordConnected,
+ };
+
+ setSavedChannel(nextChannel);
+ setSavedWorkspaceNotif(nextWorkspace);
+ setSavedOrgNotif(nextOrg);
+
+ const orgChanged = prevOrgIdRef.current !== selectedOrgId;
+ if (orgChanged || !hasNotificationChanges) {
+ setDraftChannel(nextChannel);
+ setDraftWorkspaceNotif(nextWorkspace);
+ setDraftOrgNotif(nextOrg);
+ }
+
+ prevOrgIdRef.current = selectedOrgId;
+ }, [selectedOrgId, notificationSettings, hasNotificationChanges]);
+
+ useEffect(() => {
+ if (!isNotificationError || notificationErrorUpdatedAt === 0) return;
+ if (
+ lastNotifiedNotificationErrorAtRef.current === notificationErrorUpdatedAt
+ )
+ return;
+
+ lastNotifiedNotificationErrorAtRef.current = notificationErrorUpdatedAt;
+ toast.error(
+ notificationError?.message ?? "알림 설정을 불러오는데 실패했습니다",
+ );
+ }, [isNotificationError, notificationError, notificationErrorUpdatedAt]);
+
+ return {
+ isAdmin,
+ selectedOrgId,
+ currentWorkspaceName,
+ workspaceNotifiDisabled,
+ isNotificationSectionLoading,
+ isNotificationError,
+ notificationError,
+ refetchNotificationSettings,
+
+ draftChannel,
+ setDraftChannel,
+ draftWorkspaceNotif,
+ setDraftWorkspaceNotif,
+ draftOrgNotif,
+ setDraftOrgNotif,
+ savedChannel,
+ savedWorkspaceNotif,
+ savedOrgNotif,
+ setSavedChannel,
+ setSavedWorkspaceNotif,
+ setSavedOrgNotif,
+
+ slackWebhookUrl,
+ slackWebhookError,
+ discordWebhookUrl,
+ discordWebhookError,
+ pendingOrgAction,
+ setSlackWebhookUrl,
+ setSlackWebhookError,
+ setDiscordWebhookUrl,
+ setDiscordWebhookError,
+
+ handleMasterEnableChange,
+ handleConnectSlack,
+ handleDisconnectSlack,
+ handleConnectDiscord,
+ handleDisconnectDiscord,
+
+ hasChannelChanges,
+ hasWorkspaceNotifChanges,
+ hasMasterChanges,
+ hasOrgToggleChanges,
+ hasNotificationChanges,
+
+ updateChannels,
+ updateAlerts,
+ updateOrg,
+ updateMaster,
+ buildOrgBody,
+ };
+}
diff --git a/src/hooks/setting/useSettingPassword.ts b/src/hooks/setting/useSettingPassword.ts
new file mode 100644
index 00000000..ed54b47f
--- /dev/null
+++ b/src/hooks/setting/useSettingPassword.ts
@@ -0,0 +1,61 @@
+import { useState } from "react";
+
+const EMPTY_ERRORS = {
+ currentPassword: "",
+ newPassword: "",
+ confirmNewPassword: "",
+};
+export default function useSettingPassword() {
+ const [currentPassword, setCurrentPassword] = useState("");
+ const [newPassword, setNewPassword] = useState("");
+ const [confirmNewPassword, setConfirmNewPassword] = useState("");
+ const [passwordErrors, setPasswordErrors] = useState(EMPTY_ERRORS);
+
+ const hasPasswordChanges =
+ !!currentPassword || !!newPassword || !!confirmNewPassword;
+
+ const validatePassword = () => {
+ const errors = { ...EMPTY_ERRORS };
+
+ if (!currentPassword) {
+ errors.currentPassword = "현재 비밀번호를 입력해주세요";
+ }
+ if (
+ !newPassword.match(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d]).{8,16}$/)
+ ) {
+ errors.newPassword =
+ "영문, 숫자, 특수문자를 포함하여 8~16자로 입력해주세요";
+ }
+ if (currentPassword && newPassword && currentPassword === newPassword) {
+ errors.newPassword = "현재 비밀번호와 다른 비밀번호를 입력해주세요";
+ }
+ if (newPassword !== confirmNewPassword) {
+ errors.confirmNewPassword = "새 비밀번호가 일치하지 않습니다";
+ }
+ setPasswordErrors(errors);
+ return !Object.values(errors).some(Boolean);
+ };
+
+ const clearPasswordErrors = () => {
+ setPasswordErrors(EMPTY_ERRORS);
+ };
+ const clearPassword = () => {
+ setCurrentPassword("");
+ setNewPassword("");
+ setConfirmNewPassword("");
+ };
+
+ return {
+ currentPassword,
+ setCurrentPassword,
+ newPassword,
+ setNewPassword,
+ confirmNewPassword,
+ setConfirmNewPassword,
+ passwordErrors,
+ hasPasswordChanges,
+ validatePassword,
+ clearPasswordErrors,
+ clearPassword,
+ };
+}
diff --git a/src/hooks/setting/useSettingProfile.ts b/src/hooks/setting/useSettingProfile.ts
new file mode 100644
index 00000000..cd84a937
--- /dev/null
+++ b/src/hooks/setting/useSettingProfile.ts
@@ -0,0 +1,108 @@
+import { type ChangeEvent, useEffect, useMemo, useState } from "react";
+import { toast } from "sonner";
+
+import type { IDraftProfile, ISavedProfile } from "@/types/setting/settingPage";
+
+import { useImageUploader } from "@/hooks/common/useImageUploader";
+
+import { getMyInfo } from "@/api/auth/auth";
+
+export default function useSettingProfile() {
+ const [savedProfile, setSavedProfile] = useState({
+ name: "",
+ profileImageUrl: null,
+ });
+ const [draftProfile, setDraftProfile] = useState({
+ name: "",
+ email: "",
+ phoneNumber: "",
+ });
+
+ const [isImageDeleted, setIsImageDeleted] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+
+ const {
+ fileRef,
+ file,
+ preview,
+ setPreview,
+ openFilePicker,
+ onPickFile,
+ resetImage,
+ } = useImageUploader();
+
+ const hasProfileChanges = useMemo(() => {
+ return (
+ savedProfile.name !== draftProfile.name ||
+ savedProfile.profileImageUrl !== preview ||
+ !!file
+ );
+ }, [savedProfile, draftProfile, preview, file]);
+
+ const setName = (name: string) =>
+ setDraftProfile((prev) => ({ ...prev, name }));
+
+ const resetProfileImage = () => {
+ resetImage();
+ setIsImageDeleted(true);
+ };
+
+ const handlePickFile = (e: ChangeEvent) => {
+ setIsImageDeleted(false);
+ onPickFile(e);
+ };
+
+ const applyAccountSaveSuccess = (res: ISavedProfile) => {
+ setSavedProfile({
+ name: res.name,
+ profileImageUrl: res.profileImageUrl,
+ });
+ setDraftProfile((prev) => ({
+ ...prev,
+ name: res.name,
+ }));
+ setPreview(res.profileImageUrl);
+ setIsImageDeleted(false);
+ };
+
+ useEffect(() => {
+ const fetchMyInfo = async () => {
+ try {
+ setIsLoading(true);
+ const res = await getMyInfo();
+
+ setSavedProfile({
+ name: res.data.name,
+ profileImageUrl: res.data.profileImageUrl,
+ });
+ setDraftProfile({
+ name: res.data.name,
+ email: res.data.email,
+ phoneNumber: res.data.phoneNumber,
+ });
+ setPreview(res.data.profileImageUrl);
+ } catch (error) {
+ toast.error("회원 정보를 불러오는데 실패했습니다");
+ console.error(error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchMyInfo();
+ }, [setPreview]);
+
+ return {
+ isLoading,
+ draftProfile,
+ setName,
+ fileRef,
+ file,
+ preview,
+ openFilePicker,
+ handlePickFile,
+ resetProfileImage,
+ isImageDeleted,
+ hasProfileChanges,
+ applyAccountSaveSuccess,
+ };
+}
diff --git a/src/hooks/setting/useSettingSave.ts b/src/hooks/setting/useSettingSave.ts
new file mode 100644
index 00000000..a1fa0ca3
--- /dev/null
+++ b/src/hooks/setting/useSettingSave.ts
@@ -0,0 +1,186 @@
+import { useRef, useState } from "react";
+import { toast } from "sonner";
+
+import type { IApiErrorResponse } from "@/types/common/common";
+
+import type useSettingNotifications from "@/hooks/setting/useSettingNotifications";
+import type useSettingPassword from "@/hooks/setting/useSettingPassword";
+import type useSettingProfile from "@/hooks/setting/useSettingProfile";
+
+import { updateMyInfo } from "@/api/auth/auth";
+
+type TProfile = ReturnType;
+type TPassword = ReturnType;
+type TNotifications = ReturnType;
+
+interface IUseSettingSaveParams {
+ profile: TProfile;
+ password: TPassword;
+ notifications: TNotifications;
+}
+
+export default function useSettingSave({
+ profile,
+ password,
+ notifications,
+}: IUseSettingSaveParams) {
+ const [isSaving, setIsSaving] = useState(false);
+
+ const isSavingRef = useRef(false);
+
+ const hasAccountChanges =
+ profile.hasProfileChanges || password.hasPasswordChanges;
+
+ const hasChanges =
+ hasAccountChanges ||
+ (!notifications.isNotificationError &&
+ notifications.hasNotificationChanges);
+
+ const handleSave = async () => {
+ if (isSavingRef.current) return;
+
+ if (password.hasPasswordChanges) {
+ if (!password.validatePassword()) return;
+ } else {
+ password.clearPasswordErrors();
+ }
+
+ isSavingRef.current = true;
+ setIsSaving(true);
+
+ let savedAccount = false;
+ let savedAnyNotification = false;
+
+ try {
+ if (hasAccountChanges) {
+ try {
+ const res = await updateMyInfo({
+ name: profile.draftProfile.name,
+ oldPassword: password.currentPassword || undefined,
+ newPassword: password.newPassword || undefined,
+ isImageDeleted: profile.isImageDeleted,
+ imageFile: profile.file,
+ });
+ profile.applyAccountSaveSuccess(res.data);
+ password.clearPassword();
+ savedAccount = true;
+ } catch (e) {
+ const error = e as IApiErrorResponse;
+ toast.error(error.message ?? "회원정보수정에 실패했습니다");
+ return;
+ }
+ }
+
+ const canSaveNotification = !notifications.isNotificationError;
+
+ const { selectedOrgId, isAdmin } = notifications;
+ const shouldSaveChannel =
+ canSaveNotification &&
+ notifications.hasChannelChanges &&
+ selectedOrgId != null;
+ const shouldSaveAlerts =
+ canSaveNotification &&
+ notifications.hasWorkspaceNotifChanges &&
+ selectedOrgId != null;
+
+ const shouldSaveMaster =
+ canSaveNotification &&
+ notifications.hasMasterChanges &&
+ selectedOrgId != null;
+ const shouldSaveOrg =
+ canSaveNotification &&
+ notifications.hasOrgToggleChanges &&
+ selectedOrgId != null &&
+ isAdmin;
+
+ if (
+ shouldSaveChannel ||
+ shouldSaveAlerts ||
+ shouldSaveMaster ||
+ shouldSaveOrg
+ ) {
+ const savedSteps: string[] = [];
+ try {
+ if (shouldSaveChannel) {
+ await notifications.updateChannels.mutateAsync({
+ isBrowserPushEnabled: notifications.draftChannel.browserPush,
+ isEmailEnabled: notifications.draftChannel.emailNotif,
+ });
+ notifications.setSavedChannel(notifications.draftChannel);
+ savedSteps.push("알림 채널");
+ }
+ if (shouldSaveAlerts) {
+ await notifications.updateAlerts.mutateAsync({
+ alertClicks: notifications.draftWorkspaceNotif.clickAlarm,
+ alertReport: notifications.draftWorkspaceNotif.weeklyReport,
+ });
+ notifications.setSavedWorkspaceNotif(
+ notifications.draftWorkspaceNotif,
+ );
+ savedSteps.push("워크스페이스 알림");
+ }
+ if (shouldSaveMaster) {
+ await notifications.updateMaster.mutateAsync({
+ isMasterEnabled: notifications.draftOrgNotif.masterEnabled,
+ });
+ notifications.setSavedOrgNotif((prev) => ({
+ ...prev,
+ masterEnabled: notifications.draftOrgNotif.masterEnabled,
+ }));
+ savedSteps.push("마스터 알림");
+ }
+ if (shouldSaveOrg) {
+ await notifications.updateOrg.mutateAsync(
+ notifications.buildOrgBody({
+ isSlackEnabled: notifications.draftOrgNotif.slackEnabled,
+ slackWebhookUrl: "",
+ disconnectSlack: false,
+ isDiscordEnabled: notifications.draftOrgNotif.discordEnabled,
+ discordWebhookUrl: "",
+ disconnectDiscord: false,
+ }),
+ );
+ notifications.setSavedOrgNotif((prev) => ({
+ ...prev,
+ slackEnabled: notifications.draftOrgNotif.slackEnabled,
+ discordEnabled: notifications.draftOrgNotif.discordEnabled,
+ }));
+ savedSteps.push("슬랙/디스코드 설정");
+ }
+ savedAnyNotification = true;
+ } catch (e) {
+ const error = e as IApiErrorResponse;
+ if (savedAccount) {
+ toast.success("회원정보가 수정되었습니다");
+ }
+ const reason = error.message ?? "알림 저장에 실패했습니다.";
+ toast.error(
+ savedSteps.length > 0
+ ? `${savedSteps.join(", ")}은(는) 저장됐지만, 이후 단계에서 실패했습니다: ${reason}`
+ : reason,
+ );
+ return;
+ }
+ }
+
+ if (savedAccount || savedAnyNotification) {
+ toast.success(
+ savedAccount && savedAnyNotification
+ ? "설정이 저장되었습니다"
+ : savedAnyNotification
+ ? "알림 설정이 저장되었습니다"
+ : "회원정보가 수정되었습니다",
+ );
+ }
+ } finally {
+ isSavingRef.current = false;
+ setIsSaving(false);
+ }
+ };
+
+ return {
+ isSaving,
+ hasChanges,
+ handleSave,
+ };
+}
diff --git a/src/hooks/timeline/useTimelineEditModal.ts b/src/hooks/timeline/useTimelineEditModal.ts
new file mode 100644
index 00000000..0e7d7d60
--- /dev/null
+++ b/src/hooks/timeline/useTimelineEditModal.ts
@@ -0,0 +1,51 @@
+import { useEffect, useMemo, useState } from "react";
+import { toast } from "sonner";
+
+import { useTimelineDetail } from "./useTimelineDetail";
+
+export function useTimelineEditModal() {
+ const [editTimelineId, setEditTimelineId] = useState(null);
+
+ const {
+ data: editDetail,
+ isLoading: isEditDetailLoading,
+ isError: isEditDetailError,
+ error: editDetailError,
+ } = useTimelineDetail(editTimelineId);
+
+ const editInitialValues = useMemo(() => {
+ if (!editDetail) return undefined;
+ return {
+ name: editDetail.name,
+ startDate: editDetail.startDate,
+ endDate: editDetail.endDate,
+ metrics: editDetail.metrics,
+ comparisonPeriodType: editDetail.comparisonPeriodType,
+ };
+ }, [editDetail]);
+
+ useEffect(() => {
+ if (editTimelineId == null || !isEditDetailError) return;
+ toast.error(
+ editDetailError?.message ??
+ "타임라인 정보를 불러오지 못했습니다. 다시 시도해주세요",
+ );
+ setEditTimelineId(null);
+ }, [editTimelineId, isEditDetailError, editDetailError]);
+
+ useEffect(() => {
+ if (editTimelineId == null || !isEditDetailLoading) return;
+ toast.info("타임라인 정보를 불러오는 중...");
+ }, [editTimelineId, isEditDetailLoading]);
+
+ const openEditModal = (id: number) => setEditTimelineId(id);
+ const closeEditModal = () => setEditTimelineId(null);
+
+ return {
+ editTimelineId,
+ editInitialValues,
+ isEditOpen: editTimelineId != null && editInitialValues != null,
+ openEditModal,
+ closeEditModal,
+ };
+}
diff --git a/src/hooks/timeline/useTimelinePanel.ts b/src/hooks/timeline/useTimelinePanel.ts
new file mode 100644
index 00000000..1536d5b6
--- /dev/null
+++ b/src/hooks/timeline/useTimelinePanel.ts
@@ -0,0 +1,54 @@
+import { useEffect, useState } from "react";
+
+import type { ITimelineSummaryPanelData } from "@/types/timeline/summary";
+import type { ITimelineCampaignBar } from "@/types/timeline/ui";
+
+import { buildTimelineSummaryPanel } from "@/utils/timeline/buildTimelineSummaryPanel";
+
+import { useTimelineDetail } from "./useTimelineDetail";
+
+interface IUseTimelinePanelParams {
+ bars: ITimelineCampaignBar[];
+}
+
+export default function useTimelinePanel({ bars }: IUseTimelinePanelParams) {
+ const [isPanelOpen, setIsPanelOpen] = useState(false);
+ const [selectedBarId, setSelectedBarId] = useState(null);
+ const [panelData, setPanelData] = useState(
+ null,
+ );
+
+ const { data: detail } = useTimelineDetail(selectedBarId);
+
+ useEffect(() => {
+ if (!detail) return;
+ setPanelData(buildTimelineSummaryPanel(detail));
+ }, [detail]);
+
+ useEffect(() => {
+ if (selectedBarId === null) return;
+ if (!bars.some((bar) => bar.id === selectedBarId)) {
+ setIsPanelOpen(false);
+ setSelectedBarId(null);
+ }
+ }, [bars, selectedBarId]);
+
+ const handleBarClick = (bar: ITimelineCampaignBar) => {
+ setSelectedBarId(bar.id);
+ setPanelData(null);
+ setIsPanelOpen(true);
+ };
+
+ const handlePanelClose = () => {
+ setIsPanelOpen(false);
+ setSelectedBarId(null);
+ };
+
+ return {
+ isPanelOpen,
+ selectedBarId,
+ panelData,
+ handleBarClick,
+ handlePanelClose,
+ };
+}
diff --git a/src/hooks/timeline/useTimelinePeriod.ts b/src/hooks/timeline/useTimelinePeriod.ts
new file mode 100644
index 00000000..38f9bbc9
--- /dev/null
+++ b/src/hooks/timeline/useTimelinePeriod.ts
@@ -0,0 +1,49 @@
+import { type RefObject, useEffect, useState } from "react";
+
+import type { TTimelineViewUnit } from "@/types/timeline/ui";
+
+interface IUserTimelinePeriodParams {
+ scrollRef: RefObject;
+ hasNoTimelines: boolean;
+}
+
+export function useTimelinePeriod({
+ scrollRef,
+ hasNoTimelines,
+}: IUserTimelinePeriodParams) {
+ const [viewUnit, setViewUnit] = useState("WEEK");
+ const [periodIndex, setPeriodIndex] = useState(0);
+
+ useEffect(() => {
+ if (hasNoTimelines) return;
+ const el = scrollRef.current;
+ if (!el) return;
+ el.scrollLeft = viewUnit === "MONTH" ? 0 : el.scrollWidth - el.clientWidth;
+ }, [scrollRef, hasNoTimelines, viewUnit, periodIndex]);
+
+ const handleViewUnitChange = (unit: TTimelineViewUnit) => {
+ setViewUnit(unit);
+ setPeriodIndex(0);
+ };
+
+ const handlePrevPeriod = () => {
+ setPeriodIndex((prev) => prev + 1); //더 과거
+ };
+
+ const handleNextPeriod = () => {
+ setPeriodIndex((prev) => Math.max(0, prev - 1));
+ };
+
+ const handleGoToToday = () => {
+ setPeriodIndex(0);
+ };
+
+ return {
+ viewUnit,
+ periodIndex,
+ handleViewUnitChange,
+ handlePrevPeriod,
+ handleNextPeriod,
+ handleGoToToday,
+ };
+}
diff --git a/src/hooks/timeline/useTimelineSummaryPolling.ts b/src/hooks/timeline/useTimelineSummaryPolling.ts
new file mode 100644
index 00000000..28f8687e
--- /dev/null
+++ b/src/hooks/timeline/useTimelineSummaryPolling.ts
@@ -0,0 +1,69 @@
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+
+import { useRequestTimelineSummary } from "./useRequestTimelineSummary";
+import { useTimelineDetail } from "./useTimelineDetail";
+
+const SUMMARY_POLL_INTERVAL_MS = 1500;
+const SUMMARY_POLL_TIMEOUT_MS = 90000;
+
+export function useTimelineSummaryPolling(selectedBarId: number | null) {
+ const [isAwaitingSummary, setIsAwaitingSummary] = useState(false);
+ const [summaryPollStartedAt, setSummaryPollStartedAt] = useState<
+ number | null
+ >(null);
+
+ const { mutate: requestSummary, isPending: isSummaryPending } =
+ useRequestTimelineSummary();
+
+ const { data: detail } = useTimelineDetail(selectedBarId, {
+ refetchInterval: isAwaitingSummary ? SUMMARY_POLL_INTERVAL_MS : false,
+ });
+
+ useEffect(() => {
+ setIsAwaitingSummary(false);
+ setSummaryPollStartedAt(null);
+ }, [selectedBarId]);
+
+ useEffect(() => {
+ if (!isAwaitingSummary) return;
+ if (!detail?.summary?.trim()) return;
+ setIsAwaitingSummary(false);
+ setSummaryPollStartedAt(null);
+ }, [isAwaitingSummary, detail?.summary]);
+
+ useEffect(() => {
+ if (!isAwaitingSummary || summaryPollStartedAt == null) return;
+ const timer = window.setTimeout(() => {
+ setIsAwaitingSummary(false);
+ setSummaryPollStartedAt(null);
+ toast.error(
+ "더 상세한 요약을 위해 시간이 걸리고 있습니다. 잠시 후 다시 시도해주세요",
+ );
+ }, SUMMARY_POLL_TIMEOUT_MS);
+ return () => window.clearTimeout(timer);
+ }, [isAwaitingSummary, summaryPollStartedAt]);
+
+ const resetSummaryPolling = () => {
+ setIsAwaitingSummary(false);
+ setSummaryPollStartedAt(null);
+ };
+
+ const handleRequestSummary = () => {
+ if (selectedBarId == null) return;
+ setIsAwaitingSummary(true);
+ setSummaryPollStartedAt(Date.now());
+ requestSummary(selectedBarId, {
+ onError: () => {
+ resetSummaryPolling();
+ },
+ });
+ };
+
+ return {
+ isAwaitingSummary,
+ isSummaryPending,
+ resetSummaryPolling,
+ handleRequestSummary,
+ };
+}
diff --git a/src/pages/dashboard/timeline/Timeline.tsx b/src/pages/dashboard/timeline/Timeline.tsx
index eb54d28a..7105d3fe 100644
--- a/src/pages/dashboard/timeline/Timeline.tsx
+++ b/src/pages/dashboard/timeline/Timeline.tsx
@@ -1,72 +1,41 @@
-import { useEffect, useMemo, useRef, useState } from "react";
-import { toast } from "sonner";
-import { twMerge } from "tailwind-merge";
+import { useMemo, useRef, useState } from "react";
-import type { ITimelineSummaryPanelData } from "@/types/timeline/summary";
-import type {
- ITimelineCampaignBar,
- TTimelineViewUnit,
-} from "@/types/timeline/ui";
+import type { ITimelineCampaignBar } from "@/types/timeline/ui";
import {
TIMELINE_COL_WIDTH,
TIMELINE_PAGE_HEIGHT,
} from "@/constants/timeline/layout";
import { buildTimelineGrid } from "@/utils/timeline/buildTimelineGrid";
-import { buildTimelineSummaryPanel } from "@/utils/timeline/buildTimelineSummaryPanel";
import { useContainerWidth } from "@/hooks/timeline/useContainerWidth";
import { useDeleteTimeline } from "@/hooks/timeline/useDeleteTimeline";
-import { useRequestTimelineSummary } from "@/hooks/timeline/useRequestTimelineSummary";
-import { useTimelineDetail } from "@/hooks/timeline/useTimelineDetail";
+import { useTimelineEditModal } from "@/hooks/timeline/useTimelineEditModal";
import { useTimelineList } from "@/hooks/timeline/useTimelineList";
+import useTimelinePanel from "@/hooks/timeline/useTimelinePanel";
+import { useTimelinePeriod } from "@/hooks/timeline/useTimelinePeriod";
+import { useTimelineSummaryPolling } from "@/hooks/timeline/useTimelineSummaryPolling";
-import Button from "@/components/common/button/Button";
import AreaErrorFallback from "@/components/common/error/AreaErrorFallback";
import { ErrorBoundary } from "@/components/common/error/ErrorBoundary";
-import Modal from "@/components/common/modal/Modal";
-import ModalContent from "@/components/common/modal/ModalContent";
import TimelineSkeleton from "@/components/timeline/skeleton/TimelineSkeleton";
-import TimelineAxis from "@/components/timeline/TimelineAxis";
-import TimelineBar from "@/components/timeline/TimelineBar";
+import TimelineCanvas from "@/components/timeline/TimelineCanvas";
import TimelineCreateModal from "@/components/timeline/TimelineCreateModal";
+import TimelineDeleteModal from "@/components/timeline/TimelineDeleteModal";
import TimelineEmptyState from "@/components/timeline/TimelineEmptyState";
-import TimelineFilterSortMenus from "@/components/timeline/TimelineFilterSortMenus";
-import TimelineGrid from "@/components/timeline/TimelineGrid";
import TimelinePerformancePanel from "@/components/timeline/TimelinePerformancePanel";
-import {
- TimelinePeriodNav,
- TimelineViewUnitSegment,
-} from "@/components/timeline/TimelinePeriodSelector";
-import TimelineStatusLegend from "@/components/timeline/TimelineStatusLegend";
+import TimelineToolbar from "@/components/timeline/TimelineToolbar";
-import PlusIcon from "@/assets/icon/common/plus.svg?react";
-import TrashIcon from "@/assets/icon/common/trash.svg?react";
import useTimelineStore from "@/store/useTimelineStore";
-const SUMMARY_POLL_INTERVAL_MS = 1500;
-const SUMMARY_POLL_TIMEOUT_MS = 90000;
-
export default function Timeline() {
const scrollRef = useRef(null);
- const [viewUnit, setViewUnit] = useState("WEEK");
- const [periodIndex, setPeriodIndex] = useState(0);
const [isCreateOpen, setIsCreateOpen] = useState(false);
- const [isPanelOpen, setIsPanelOpen] = useState(false);
- const [selectedBarId, setSelectedBarId] = useState(null);
- const [panelData, setPanelData] = useState(
- null,
- );
- const [editTimelineId, setEditTimelineId] = useState(null);
const [deleteTarget, setDeleteTarget] = useState<{
id: number;
name: string;
} | null>(null);
- const [isAwaitingSummary, setIsAwaitingSummary] = useState(false);
- const [summaryPollStartedAt, setSummaryPollStartedAt] = useState<
- number | null
- >(null);
const statusFilter = useTimelineStore((s) => s.statusFilter);
const sort = useTimelineStore((s) => s.sort);
@@ -74,29 +43,6 @@ export default function Timeline() {
const setSort = useTimelineStore((s) => s.setSort);
const { mutate: deleteTimeline, isPending: isDeleting } = useDeleteTimeline();
- const { mutate: requestSummary, isPending: isSummaryPending } =
- useRequestTimelineSummary();
- const {
- data: editDetail,
- isLoading: isEditDetailLoading,
- isError: isEditDetailError,
- error: editDetailError,
- } = useTimelineDetail(editTimelineId);
-
- const { data: detail } = useTimelineDetail(selectedBarId, {
- refetchInterval: isAwaitingSummary ? SUMMARY_POLL_INTERVAL_MS : false,
- });
-
- const editInitialValues = useMemo(() => {
- if (!editDetail) return undefined;
- return {
- name: editDetail.name,
- startDate: editDetail.startDate,
- endDate: editDetail.endDate,
- metrics: editDetail.metrics,
- comparisonPeriodType: editDetail.comparisonPeriodType,
- };
- }, [editDetail]);
const listParams = useMemo(
() => ({
@@ -113,14 +59,29 @@ export default function Timeline() {
error,
} = useTimelineList(listParams);
+ const hasNoTimelines = timelineList.length === 0;
+
+ const {
+ viewUnit,
+ periodIndex,
+ handleViewUnitChange,
+ handlePrevPeriod,
+ handleNextPeriod,
+ handleGoToToday,
+ } = useTimelinePeriod({ scrollRef, hasNoTimelines });
+
const gridData = useMemo(
- () => buildTimelineGrid({ items: timelineList, viewUnit, periodIndex }),
+ () =>
+ buildTimelineGrid({
+ items: timelineList,
+ viewUnit: viewUnit,
+ periodIndex: periodIndex,
+ }),
[timelineList, viewUnit, periodIndex],
);
- const { columns, bars } = gridData;
- const hasNoTimelines = timelineList.length === 0;
+
+ const { columns, bars, periodLabel } = gridData;
const hasNoVisibleBars = !hasNoTimelines && bars.length === 0;
- const periodLabel = gridData.periodLabel;
const maxRow = useMemo(
() => (bars.length > 0 ? Math.max(...bars.map((bar) => bar.row)) : 0),
@@ -135,93 +96,33 @@ export default function Timeline() {
: TIMELINE_COL_WIDTH;
const totalWidth = columnCount * colWidth;
- useEffect(() => {
- if (!isAwaitingSummary) return;
- if (!detail?.summary?.trim()) return;
-
- setIsAwaitingSummary(false);
- setSummaryPollStartedAt(null);
- }, [isAwaitingSummary, detail?.summary]);
-
- useEffect(() => {
- if (!isAwaitingSummary || summaryPollStartedAt == null) return;
-
- const timer = window.setTimeout(() => {
- setIsAwaitingSummary(false);
- setSummaryPollStartedAt(null);
- toast.error(
- "더 상세한 요약을 위해 시간이 걸리고 있습니다. 잠시 후 다시 시도해주세요",
- );
- }, SUMMARY_POLL_TIMEOUT_MS);
- return () => window.clearTimeout(timer);
- }, [isAwaitingSummary, summaryPollStartedAt]);
-
- useEffect(() => {
- if (editTimelineId == null || !isEditDetailError) return;
- toast.error(
- editDetailError?.message ??
- "타임라인 정보를 불러오지 못했습니다. 다시 시도해주세요",
- );
- setEditTimelineId(null);
- }, [editTimelineId, isEditDetailError, editDetailError]);
-
- useEffect(() => {
- if (editTimelineId == null || !isEditDetailLoading) return;
- toast.info("타임라인 정보를 불러오는 중...");
- }, [editTimelineId, isEditDetailLoading]);
-
- useEffect(() => {
- if (!detail) return;
- setPanelData(buildTimelineSummaryPanel(detail));
- }, [detail]);
-
- useEffect(() => {
- if (hasNoTimelines) return;
- const el = scrollRef.current;
- if (!el) return;
- el.scrollLeft = viewUnit === "MONTH" ? 0 : el.scrollWidth - el.clientWidth;
- }, [columns, hasNoTimelines, viewUnit]);
-
- useEffect(() => {
- if (selectedBarId === null) return;
- if (!bars.some((bar) => bar.id === selectedBarId)) {
- setIsPanelOpen(false);
- setSelectedBarId(null);
- }
- }, [bars, selectedBarId]);
-
- const handleViewUnitChange = (unit: TTimelineViewUnit) => {
- setViewUnit(unit);
- setPeriodIndex(0);
- };
-
- const handlePrevPeriod = () => {
- setPeriodIndex((prev) => prev + 1); //더 과거
- };
-
- const handleNextPeriod = () => {
- setPeriodIndex((prev) => Math.max(0, prev - 1));
- };
+ const {
+ isPanelOpen,
+ selectedBarId,
+ panelData,
+ handleBarClick: selectBar,
+ handlePanelClose,
+ } = useTimelinePanel({ bars });
- const handleGoToToday = () => {
- setPeriodIndex(0);
- };
+ const {
+ isAwaitingSummary,
+ isSummaryPending,
+ handleRequestSummary,
+ resetSummaryPolling,
+ } = useTimelineSummaryPolling(selectedBarId);
const handleBarClick = (bar: ITimelineCampaignBar) => {
- setSelectedBarId(bar.id);
- setPanelData(null);
- setIsPanelOpen(true);
- setIsAwaitingSummary(false);
- setSummaryPollStartedAt(null);
- };
-
- const handlePanelClose = () => {
- setIsPanelOpen(false);
- setSelectedBarId(null);
+ resetSummaryPolling();
+ selectBar(bar);
};
- const openEditModal = (id: number) => setEditTimelineId(id);
- const closeEditModal = () => setEditTimelineId(null);
+ const {
+ editTimelineId,
+ editInitialValues,
+ isEditOpen,
+ openEditModal,
+ closeEditModal,
+ } = useTimelineEditModal();
const openDeleteModal = (target: { id: number; name: string }) => {
setDeleteTarget(target);
@@ -250,18 +151,6 @@ export default function Timeline() {
});
};
- const handleRequestSummary = () => {
- if (selectedBarId == null) return;
- setIsAwaitingSummary(true);
- setSummaryPollStartedAt(Date.now());
- requestSummary(selectedBarId, {
- onError: () => {
- setIsAwaitingSummary(false);
- setSummaryPollStartedAt(null);
- },
- });
- };
-
if (isLoading) {
return ;
}
@@ -296,107 +185,40 @@ export default function Timeline() {
resetKeys={[timelineList, viewUnit, periodIndex]}
>
-
-
-
-
-
-
-
-
-
-
-
-
+
setIsCreateOpen(true)}
+ />
{hasNoTimelines ? (
setIsCreateOpen(true)} />
) : (
-
-
-
- {hasNoVisibleBars ? (
-
-
- 이 기간에 표시할 타임라인이 없어요
-
-
- 다른 기간으로 이동하거나 보기 단위를 변경해 보세요
-
-
- ) : (
-
- {bars.map((bar) => (
- handleEditTimeline(bar.id)}
- onDelete={() =>
- handleDeleteTimeline({ id: bar.id, name: bar.title })
- }
- />
- ))}
-
- )}
-
-
+
)}
-
{/* 생성 */}
{/* 수정 */}
) : null}
-
- }
- title="해당 타임라인을 삭제할까요?"
- description={
- deleteTarget
- ? `"${deleteTarget.name}" 타임라인을 삭제하면 복구할 수 없습니다`
- : ""
- }
- buttonText="삭제하기"
- onConfirm={handleConfirmDelete}
- isLoading={isDeleting}
- variant="danger"
- />
-
+ onConfirm={handleConfirmDelete}
+ />
);
}
diff --git a/src/pages/setting/Setting.tsx b/src/pages/setting/Setting.tsx
index 1576154b..b45fd4bc 100644
--- a/src/pages/setting/Setting.tsx
+++ b/src/pages/setting/Setting.tsx
@@ -1,17 +1,10 @@
-import { type ChangeEvent, useEffect, useMemo, useRef, useState } from "react";
-import { toast } from "sonner";
-
-import type { IApiErrorResponse } from "@/types/common/common";
-import type { IUpdateOrgNotificationSettingsRequest } from "@/types/setting/notification";
+import { useState } from "react";
import { useDeleteMyAccount } from "@/hooks/auth/useDeleteMyAccount";
-import { useImageUploader } from "@/hooks/common/useImageUploader";
-import { useCoreQuery } from "@/hooks/customQuery";
-import { useMyNotificationSettings } from "@/hooks/setting/useMyNotificationSettings";
-import { useUpdateAlertsNotificationSettings } from "@/hooks/setting/useUpdateAlertsNotificationSettings";
-import { useUpdateChannelNotificationSettings } from "@/hooks/setting/useUpdateChannelNotificationSettings";
-import { useUpdateMasterNotificationSettings } from "@/hooks/setting/useUpdateMasterNotificationSetting";
-import { useUpdateOrgNotificationSettings } from "@/hooks/setting/useUpdateOrgNotificationSettings";
+import useSettingNotification from "@/hooks/setting/useSettingNotifications";
+import useSettingPassword from "@/hooks/setting/useSettingPassword";
+import useSettingProfile from "@/hooks/setting/useSettingProfile";
+import useSettingSave from "@/hooks/setting/useSettingSave";
import Button from "@/components/common/button/Button";
import AreaErrorFallback from "@/components/common/error/AreaErrorFallback";
@@ -23,574 +16,70 @@ import ProfileSection from "@/components/setting/ProfileSection";
import ProfileSectionSkeleton from "@/components/setting/ProfileSectionSkeleton";
import WithdrawConfirmModal from "@/components/setting/WithdrawConfirmModal";
-import { getMyInfo, updateMyInfo } from "@/api/auth/auth";
-import { getMyWorkspaces } from "@/api/workspace/org";
-import { QUERY_KEYS } from "@/lib/queryKeys";
-import useWorkspaceStore from "@/store/useWorkspaceStore";
-
-interface IChannelNotificationSettings {
- browserPush: boolean;
- emailNotif: boolean;
-}
-
-interface IWorkspaceNotificationSettings {
- clickAlarm: boolean;
- weeklyReport: boolean;
-}
-
-interface IOrgNotificationSettings {
- masterEnabled: boolean;
- slackEnabled: boolean;
- slackConnected: boolean;
- discordEnabled: boolean;
- discordConnected: boolean;
-}
-
-const DEFAULT_CHANNEL: IChannelNotificationSettings = {
- browserPush: false,
- emailNotif: false,
-};
-
-const DEFAULT_WORKSPACE_NOTIF: IWorkspaceNotificationSettings = {
- clickAlarm: false,
- weeklyReport: false,
-};
-
-const DEFAULT_ORG_NOTIF: IOrgNotificationSettings = {
- masterEnabled: true,
- slackEnabled: false,
- slackConnected: false,
- discordEnabled: false,
- discordConnected: false,
-};
-
-interface IDraftProfile {
- name: string;
- email: string;
- phoneNumber: string;
-}
-
-interface ISavedProfile {
- name: string;
- profileImageUrl: string | null;
-}
-
export default function Setting() {
- const [savedProfile, setSavedProfile] = useState({
- name: "",
- profileImageUrl: null,
- });
- const [draftProfile, setDraftProfile] = useState({
- name: "",
- email: "",
- phoneNumber: "",
- });
- const [currentPassword, setCurrentPassword] = useState("");
- const [newPassword, setNewPassword] = useState("");
- const [confirmNewPassword, setConfirmNewPassword] = useState("");
- const [savedChannel, setSavedChannel] =
- useState(DEFAULT_CHANNEL);
- const [draftChannel, setDraftChannel] =
- useState(DEFAULT_CHANNEL);
- const [savedWorkspaceNotif, setSavedWorkspaceNotif] =
- useState(DEFAULT_WORKSPACE_NOTIF);
- const [draftWorkspaceNotif, setDraftWorkspaceNotif] =
- useState(DEFAULT_WORKSPACE_NOTIF);
- const [savedOrgNotif, setSavedOrgNotif] =
- useState(DEFAULT_ORG_NOTIF);
- const [draftOrgNotif, setDraftOrgNotif] =
- useState(DEFAULT_ORG_NOTIF);
-
- const [slackWebhookUrl, setSlackWebhookUrl] = useState("");
- const [slackWebhookError, setSlackWebhookError] = useState("");
- const [discordWebhookUrl, setDiscordWebhookUrl] = useState("");
- const [discordWebhookError, setDiscordWebhookError] = useState("");
- const [pendingOrgAction, setPendingOrgAction] = useState<
- "slack" | "discord" | null
- >(null);
-
- const [isImageDeleted, setIsImageDeleted] = useState(false);
- const [isLoading, setIsLoading] = useState(false);
- const [isSaving, setIsSaving] = useState(false);
-
const [isWithdrawModalOpen, setIsWithdrawModalOpen] = useState(false);
+ const profile = useSettingProfile();
+ const password = useSettingPassword();
+ const notifications = useSettingNotification();
+ const { isSaving, hasChanges, handleSave } = useSettingSave({
+ profile,
+ password,
+ notifications,
+ });
+ const { mutate: deleteMyAccountMutate, isPending: isWithdrawPending } =
+ useDeleteMyAccount();
+
const {
+ isLoading,
+ draftProfile,
+ setName,
fileRef,
- file,
preview,
- setPreview,
openFilePicker,
- onPickFile,
- resetImage,
- } = useImageUploader();
-
- const selectedOrgId = useWorkspaceStore((s) => s.selectedOrgId);
- const { data: workspaces, isLoading: isWorkspacesLoading } = useCoreQuery(
- QUERY_KEYS.workspace.list(),
- getMyWorkspaces,
- );
-
- const myRole = useWorkspaceStore((s) => s.myRole);
- const isAdmin = myRole === "ADMIN";
+ handlePickFile,
+ resetProfileImage,
+ } = profile;
const {
- data: notificationSettings,
- isLoading: isNotificationLoading,
- isRefetching: isNotificationRefetching,
- isError: isNotificationError,
- error: notificationError,
- errorUpdatedAt: notificationErrorUpdatedAt,
- refetch: refetchNotificationSettings,
- } = useMyNotificationSettings();
-
- const lastNotifiedNotificationErrorAtRef = useRef(0);
- const isSavingRef = useRef(false);
-
- const currentWorkspaceName = useMemo(() => {
- if (selectedOrgId === null) return null;
- return workspaces?.find((w) => w.orgId === selectedOrgId)?.name ?? null;
- }, [selectedOrgId, workspaces]);
-
- const workspaceNotifiDisabled =
- selectedOrgId == null || (!isWorkspacesLoading && !currentWorkspaceName);
-
- const isNotificationSectionLoading =
- selectedOrgId !== null &&
- (isNotificationLoading || isNotificationRefetching);
-
- const updateChannels = useUpdateChannelNotificationSettings();
- const updateAlerts = useUpdateAlertsNotificationSettings();
- const updateOrg = useUpdateOrgNotificationSettings();
- const updateMaster = useUpdateMasterNotificationSettings();
-
- const { mutate: deleteMyAccountMutate, isPending: isWithdrawPending } =
- useDeleteMyAccount();
-
- const buildOrgBody = (
- overrides: Partial = {},
- ): IUpdateOrgNotificationSettingsRequest => ({
- isSlackEnabled: draftOrgNotif.slackEnabled,
- slackWebhookUrl: "",
- disconnectSlack: false,
- isDiscordEnabled: draftOrgNotif.discordEnabled,
- discordWebhookUrl: "",
- disconnectDiscord: false,
- alertClicks: draftWorkspaceNotif.clickAlarm ?? false,
- alertReport: draftWorkspaceNotif.weeklyReport ?? false,
- ...overrides,
- });
-
- const handlePickFile = (e: ChangeEvent) => {
- setIsImageDeleted(false);
- onPickFile(e);
- };
+ currentPassword,
+ setCurrentPassword,
+ newPassword,
+ setNewPassword,
+ confirmNewPassword,
+ setConfirmNewPassword,
+ passwordErrors,
+ } = password;
- const handleConnectSlack = async () => {
- const url = slackWebhookUrl.trim();
- if (!url) {
- setSlackWebhookError("Webhook URL을 입력해주세요");
- return;
- }
- if (!url.startsWith("https://")) {
- setSlackWebhookError("올바른 URL 형식으로 입력해주세요");
- return;
- }
-
- setPendingOrgAction("slack");
- try {
- await updateOrg.mutateAsync(
- buildOrgBody({
- isSlackEnabled: true,
- slackWebhookUrl: url,
- disconnectSlack: false,
- }),
- );
- toast.success("슬랙이 연동되었습니다");
- setSlackWebhookUrl("");
- setSlackWebhookError("");
- } catch (e) {
- const error = e as IApiErrorResponse;
- toast.error(error.message ?? "슬랙 연동에 실패했습니다");
- } finally {
- setPendingOrgAction(null);
- }
- };
-
- const handleDisconnectSlack = async () => {
- setPendingOrgAction("slack");
- try {
- await updateOrg.mutateAsync(
- buildOrgBody({
- isSlackEnabled: false,
- slackWebhookUrl: "",
- disconnectSlack: true,
- }),
- );
- toast.success("슬랙 연동이 해제되었습니다");
- } catch (e) {
- const error = e as IApiErrorResponse;
- toast.error(error.message ?? "슬랙 연동 해제에 실패했습니다");
- } finally {
- setPendingOrgAction(null);
- }
- };
-
- const handleConnectDiscord = async () => {
- const url = discordWebhookUrl.trim();
- if (!url) {
- setDiscordWebhookError("Webhook URL을 입력해주세요");
- return;
- }
- if (!url.startsWith("https://")) {
- setDiscordWebhookError("올바른 URL 형식으로 입력해주세요");
- return;
- }
-
- setPendingOrgAction("discord");
- try {
- await updateOrg.mutateAsync(
- buildOrgBody({
- isDiscordEnabled: true,
- discordWebhookUrl: url,
- disconnectDiscord: false,
- }),
- );
- toast.success("디스코드가 연동되었습니다");
- setDiscordWebhookUrl("");
- setDiscordWebhookError("");
- } catch (e) {
- const error = e as IApiErrorResponse;
- toast.error(error.message ?? "디스코드 연동에 실패했습니다");
- } finally {
- setPendingOrgAction(null);
- }
- };
-
- const handleDisconnectDiscord = async () => {
- setPendingOrgAction("discord");
- try {
- await updateOrg.mutateAsync(
- buildOrgBody({
- isDiscordEnabled: false,
- discordWebhookUrl: "",
- disconnectDiscord: true,
- }),
- );
- toast.success("디스코드 연동이 해제되었습니다");
- } catch (e) {
- const error = e as IApiErrorResponse;
- toast.error(error.message ?? "디스코드 연동 해제에 실패했습니다");
- } finally {
- setPendingOrgAction(null);
- }
- };
-
- const hasPasswordChanges =
- !!currentPassword || !!newPassword || !!confirmNewPassword;
-
- const hasProfileChanges = useMemo(() => {
- return (
- savedProfile.name !== draftProfile.name ||
- savedProfile.profileImageUrl !== preview ||
- !!file
- );
- }, [savedProfile, draftProfile, preview, file]);
-
- const hasChannelChanges = useMemo(() => {
- return (
- savedChannel.browserPush !== draftChannel.browserPush ||
- savedChannel.emailNotif !== draftChannel.emailNotif
- );
- }, [savedChannel, draftChannel]);
-
- const hasWorkspaceNotifChanges = useMemo(() => {
- return (
- savedWorkspaceNotif.clickAlarm !== draftWorkspaceNotif.clickAlarm ||
- savedWorkspaceNotif.weeklyReport !== draftWorkspaceNotif.weeklyReport
- );
- }, [savedWorkspaceNotif, draftWorkspaceNotif]);
-
- const hasMasterChanges =
- savedOrgNotif.masterEnabled !== draftOrgNotif.masterEnabled;
-
- const hasOrgToggleChanges =
- savedOrgNotif.slackEnabled !== draftOrgNotif.slackEnabled ||
- savedOrgNotif.discordEnabled !== draftOrgNotif.discordEnabled;
-
- const hasAccountChanges = hasProfileChanges || hasPasswordChanges;
-
- const hasNotificationChanges =
- hasChannelChanges ||
- hasWorkspaceNotifChanges ||
- hasMasterChanges ||
- hasOrgToggleChanges;
-
- const hasChanges =
- hasAccountChanges || (!isNotificationError && hasNotificationChanges);
-
- const [passwordErrors, setPasswordErrors] = useState({
- currentPassword: "",
- newPassword: "",
- confirmNewPassword: "",
- });
-
- const validatePassword = () => {
- const errors = {
- currentPassword: "",
- newPassword: "",
- confirmNewPassword: "",
- };
- if (!currentPassword) {
- errors.currentPassword = "현재 비밀번호를 입력해주세요";
- }
- if (
- !newPassword.match(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d]).{8,16}$/)
- ) {
- errors.newPassword =
- "영문, 숫자, 특수문자를 포함하여 8~16자로 입력해주세요";
- }
- if (currentPassword && newPassword && currentPassword === newPassword) {
- errors.newPassword = "현재 비밀번호와 다른 비밀번호를 입력해주세요";
- }
- if (newPassword !== confirmNewPassword) {
- errors.confirmNewPassword = "새 비밀번호가 일치하지 않습니다";
- }
- return errors;
- };
-
- const handleSave = async () => {
- if (isSavingRef.current) return;
-
- if (hasPasswordChanges) {
- const errors = validatePassword();
- setPasswordErrors(errors);
- if (Object.values(errors).some(Boolean)) return;
- } else {
- setPasswordErrors({
- currentPassword: "",
- newPassword: "",
- confirmNewPassword: "",
- });
- }
-
- isSavingRef.current = true;
- setIsSaving(true);
-
- let savedAccount = false;
- let savedAnyNotification = false;
-
- try {
- if (hasAccountChanges) {
- try {
- const res = await updateMyInfo({
- name: draftProfile.name,
- oldPassword: currentPassword || undefined,
- newPassword: newPassword || undefined,
- isImageDeleted,
- imageFile: file,
- });
- setSavedProfile({
- name: res.data.name,
- profileImageUrl: res.data.profileImageUrl,
- });
- setDraftProfile((prev) => ({
- ...prev,
- name: res.data.name,
- }));
- setPreview(res.data.profileImageUrl);
- setCurrentPassword("");
- setNewPassword("");
- setConfirmNewPassword("");
- setIsImageDeleted(false);
- savedAccount = true;
- } catch (e) {
- const error = e as IApiErrorResponse;
- toast.error(error.message ?? "회원정보수정에 실패했습니다");
- return;
- }
- }
-
- const canSaveNotification = !isNotificationError;
- const shouldSaveChannel =
- canSaveNotification && hasChannelChanges && selectedOrgId != null;
- const shouldSaveAlerts =
- canSaveNotification &&
- hasWorkspaceNotifChanges &&
- selectedOrgId != null;
-
- const shouldSaveMaster =
- canSaveNotification && hasMasterChanges && selectedOrgId != null;
- const shouldSaveOrg =
- canSaveNotification &&
- hasOrgToggleChanges &&
- selectedOrgId != null &&
- isAdmin;
-
- if (
- shouldSaveChannel ||
- shouldSaveAlerts ||
- shouldSaveMaster ||
- shouldSaveOrg
- ) {
- const savedSteps: string[] = [];
- try {
- if (shouldSaveChannel) {
- await updateChannels.mutateAsync({
- isBrowserPushEnabled: draftChannel.browserPush,
- isEmailEnabled: draftChannel.emailNotif,
- });
- setSavedChannel(draftChannel);
- savedSteps.push("알림 채널");
- }
- if (shouldSaveAlerts) {
- await updateAlerts.mutateAsync({
- alertClicks: draftWorkspaceNotif.clickAlarm,
- alertReport: draftWorkspaceNotif.weeklyReport,
- });
- setSavedWorkspaceNotif(draftWorkspaceNotif);
- savedSteps.push("워크스페이스 알림");
- }
- if (shouldSaveMaster) {
- await updateMaster.mutateAsync({
- isMasterEnabled: draftOrgNotif.masterEnabled,
- });
- setSavedOrgNotif((prev) => ({
- ...prev,
- masterEnabled: draftOrgNotif.masterEnabled,
- }));
- savedSteps.push("마스터 알림");
- }
- if (shouldSaveOrg) {
- await updateOrg.mutateAsync(
- buildOrgBody({
- isSlackEnabled: draftOrgNotif.slackEnabled,
- slackWebhookUrl: "",
- disconnectSlack: false,
- isDiscordEnabled: draftOrgNotif.discordEnabled,
- discordWebhookUrl: "",
- disconnectDiscord: false,
- }),
- );
- setSavedOrgNotif((prev) => ({
- ...prev,
- slackEnabled: draftOrgNotif.slackEnabled,
- discordEnabled: draftOrgNotif.discordEnabled,
- }));
- savedSteps.push("슬랙/디스코드 설정");
- }
- savedAnyNotification = true;
- } catch (e) {
- const error = e as IApiErrorResponse;
- if (savedAccount) {
- toast.success("회원정보가 수정되었습니다");
- }
- toast.error(
- savedSteps.length > 0
- ? `${savedSteps.join(", ")}은(는) 저장됐지만, 이후 단계에서 실패했습니다`
- : (error.message ?? "알림 설정 저장에 실패했습니다"),
- );
- return;
- }
- }
-
- if (savedAccount || savedAnyNotification) {
- toast.success(
- savedAccount && savedAnyNotification
- ? "설정이 저장되었습니다"
- : savedAnyNotification
- ? "알림 설정이 저장되었습니다"
- : "회원정보가 수정되었습니다",
- );
- }
- } finally {
- isSavingRef.current = false;
- setIsSaving(false);
- }
- };
-
- useEffect(() => {
- const fetchMyInfo = async () => {
- try {
- setIsLoading(true);
- const res = await getMyInfo();
-
- const profileData = {
- name: res.data.name,
- email: res.data.email,
- phoneNumber: res.data.phoneNumber,
- };
- setSavedProfile({
- name: res.data.name,
- profileImageUrl: res.data.profileImageUrl,
- });
- setDraftProfile(profileData);
- setPreview(res.data.profileImageUrl);
- } catch (error) {
- toast.error("회원 정보를 불러오는데 실패했습니다");
- console.error(error);
- } finally {
- setIsLoading(false);
- }
- };
- fetchMyInfo();
- }, [setPreview]);
-
- useEffect(() => {
- //워크스페이스 미선택시에만 기본값
- if (selectedOrgId === null) {
- setSavedChannel(DEFAULT_CHANNEL);
- setDraftChannel(DEFAULT_CHANNEL);
- setSavedWorkspaceNotif(DEFAULT_WORKSPACE_NOTIF);
- setDraftWorkspaceNotif(DEFAULT_WORKSPACE_NOTIF);
- setSavedOrgNotif(DEFAULT_ORG_NOTIF);
- setDraftOrgNotif(DEFAULT_ORG_NOTIF);
- setSlackWebhookUrl("");
- setSlackWebhookError("");
- setDiscordWebhookUrl("");
- setDiscordWebhookError("");
- return;
- }
-
- if (!notificationSettings) return; //로딩,에러면 손대지 않음
-
- const masterOn = notificationSettings.isMasterEnabled;
- const nextChannel = {
- browserPush: masterOn && notificationSettings.isBrowserPushEnabled,
- emailNotif: masterOn && notificationSettings.isEmailEnabled,
- };
- const nextWorkspace = {
- clickAlarm: masterOn && notificationSettings.alertClicks,
- weeklyReport: masterOn && notificationSettings.alertReport,
- };
- const nextOrg = {
- masterEnabled: masterOn,
- slackEnabled: masterOn && notificationSettings.isSlackEnabled,
- slackConnected: notificationSettings.isSlackConnected,
- discordEnabled: masterOn && notificationSettings.isDiscordEnabled,
- discordConnected: notificationSettings.isDiscordConnected,
- };
-
- setSavedChannel(nextChannel);
- setDraftChannel(nextChannel);
- setSavedWorkspaceNotif(nextWorkspace);
- setDraftWorkspaceNotif(nextWorkspace);
- setSavedOrgNotif(nextOrg);
- setDraftOrgNotif(nextOrg);
- }, [selectedOrgId, notificationSettings]);
-
- useEffect(() => {
- if (!isNotificationError || notificationErrorUpdatedAt === 0) return;
- if (
- lastNotifiedNotificationErrorAtRef.current === notificationErrorUpdatedAt
- )
- return;
-
- lastNotifiedNotificationErrorAtRef.current = notificationErrorUpdatedAt;
- toast.error(
- notificationError?.message ?? "알림 설정을 불러오는데 실패했습니다",
- );
- }, [isNotificationError, notificationError, notificationErrorUpdatedAt]);
+ const {
+ isAdmin,
+ currentWorkspaceName,
+ workspaceNotifiDisabled,
+ isNotificationSectionLoading,
+ isNotificationError,
+ notificationError,
+ refetchNotificationSettings,
+ draftChannel,
+ setDraftChannel,
+ draftWorkspaceNotif,
+ setDraftWorkspaceNotif,
+ draftOrgNotif,
+ setDraftOrgNotif,
+ slackWebhookUrl,
+ slackWebhookError,
+ discordWebhookUrl,
+ discordWebhookError,
+ pendingOrgAction,
+ setSlackWebhookUrl,
+ setSlackWebhookError,
+ setDiscordWebhookUrl,
+ setDiscordWebhookError,
+ handleMasterEnableChange,
+ handleConnectSlack,
+ handleDisconnectSlack,
+ handleConnectDiscord,
+ handleDisconnectDiscord,
+ } = notifications;
return (
@@ -600,17 +89,14 @@ export default function Setting() {
) : (
setDraftProfile((prev) => ({ ...prev, name: v }))}
+ setName={setName}
email={draftProfile.email}
phoneNumber={draftProfile.phoneNumber}
fileRef={fileRef}
preview={preview}
onPickFile={handlePickFile}
openFilePicker={openFilePicker}
- resetImage={() => {
- resetImage();
- setIsImageDeleted(true);
- }}
+ resetImage={resetProfileImage}
/>
)}
@@ -656,32 +142,7 @@ export default function Setting() {
email={draftProfile.email}
isAdmin={isAdmin}
masterEnabled={draftOrgNotif.masterEnabled}
- onMasterEnabledChange={(value) => {
- if (!value) {
- setDraftOrgNotif((prev) => ({
- ...prev,
- masterEnabled: false,
- slackEnabled: false,
- discordEnabled: false,
- }));
- setDraftChannel({ browserPush: false, emailNotif: false });
- setDraftWorkspaceNotif({
- clickAlarm: false,
- weeklyReport: false,
- });
- return;
- }
- setDraftOrgNotif((prev) => ({
- ...prev,
- masterEnabled: true,
- slackEnabled:
- prev.slackConnected && savedOrgNotif.slackEnabled,
- discordEnabled:
- prev.discordConnected && savedOrgNotif.discordEnabled,
- }));
- setDraftChannel(savedChannel);
- setDraftWorkspaceNotif(savedWorkspaceNotif);
- }}
+ onMasterEnabledChange={handleMasterEnableChange}
browserPush={draftChannel.browserPush}
emailNotif={draftChannel.emailNotif}
onBrowserPushChange={(value) =>
@@ -750,15 +211,13 @@ export default function Setting() {
{
+ if (!detail) return false;
+
+ const nameChanged = name.trim() !== detail.name.trim();
+ const descChanged = desc.trim() !== (detail.description ?? "").trim();
+ const logoChanged =
+ logoFile !== null || (isImageDeleted && Boolean(detail.logoUrl));
+
+ return nameChanged || descChanged || logoChanged;
+ }, [detail, name, desc, logoFile, isImageDeleted]);
+
const onSave = () => {
- if (orgId === null || !name.trim()) return;
+ if (orgId === null || !name.trim() || !hasChanges) return;
updateMutation.mutate(orgId);
};
@@ -278,7 +289,7 @@ export default function WorkspaceSetting() {
조직 기본 정보
-
+
로고 이미지
@@ -294,7 +305,7 @@ export default function WorkspaceSetting() {
onClick={openFilePicker}
disabled={!isAdmin || saving || deleting}
aria-label="로고 이미지 업로드 또는 변경"
- className="flex h-60 w-60 cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-surface-400 bg-surface-200 outline-none transition-colors hover:bg-surface-300/70 focus-visible:ring-2 focus-visible:ring-primary-500/40 disabled:cursor-not-allowed disabled:opacity-50 tablet:h-46 tablet:w-46"
+ className="flex h-52 w-52 cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-surface-400 bg-surface-200 outline-none transition-colors hover:bg-surface-300/70 focus-visible:ring-2 focus-visible:ring-primary-500/40 disabled:cursor-not-allowed disabled:opacity-50 tablet:h-40 tablet:w-40"
>
{logoPreview ? (
![]()
setDesc(e.target.value)}
- minRows={4}
- className="min-h-90"
+ minRows={3}
+ className="min-h-44"
disabled={!isAdmin || saving || deleting}
/>
@@ -366,7 +377,7 @@ export default function WorkspaceSetting() {
)}
@@ -398,7 +415,7 @@ export default function WorkspaceSetting() {
현재 소유자: {currentOwner?.name ?? myName ?? "-"}
-
+
소유권은 같은 조직의 관리자(ADMIN)에게만 양도할 수
있습니다.
diff --git a/src/types/setting/settingPage.ts b/src/types/setting/settingPage.ts
new file mode 100644
index 00000000..209beee1
--- /dev/null
+++ b/src/types/setting/settingPage.ts
@@ -0,0 +1,46 @@
+export interface IChannelNotificationSettings {
+ browserPush: boolean;
+ emailNotif: boolean;
+}
+
+export interface IWorkspaceNotificationSettings {
+ clickAlarm: boolean;
+ weeklyReport: boolean;
+}
+
+export interface IOrgNotificationSettings {
+ masterEnabled: boolean;
+ slackEnabled: boolean;
+ slackConnected: boolean;
+ discordEnabled: boolean;
+ discordConnected: boolean;
+}
+
+export const DEFAULT_CHANNEL: IChannelNotificationSettings = {
+ browserPush: false,
+ emailNotif: false,
+};
+
+export const DEFAULT_WORKSPACE_NOTIF: IWorkspaceNotificationSettings = {
+ clickAlarm: false,
+ weeklyReport: false,
+};
+
+export const DEFAULT_ORG_NOTIF: IOrgNotificationSettings = {
+ masterEnabled: true,
+ slackEnabled: false,
+ slackConnected: false,
+ discordEnabled: false,
+ discordConnected: false,
+};
+
+export interface IDraftProfile {
+ name: string;
+ email: string;
+ phoneNumber: string;
+}
+
+export interface ISavedProfile {
+ name: string;
+ profileImageUrl: string | null;
+}
diff --git a/src/types/workspace/workspace.ts b/src/types/workspace/workspace.ts
index 61b4446b..1f4d8efd 100644
--- a/src/types/workspace/workspace.ts
+++ b/src/types/workspace/workspace.ts
@@ -79,6 +79,7 @@ export type TDeleteWorkspaceMemberResponse = string;
export type TPermissionKey =
| "campaignView"
+ | "timelineManage"
| "billingManage"
| "workspaceView"
| "memberInvite"
@@ -90,7 +91,7 @@ export type TPermissionRow = {
key: TPermissionKey;
label: string;
description: string;
- defaultMemberEnabled: boolean;
+ memberAllowed: boolean;
};
export type TInviteMemberRequest = {