summaryrefslogtreecommitdiff
path: root/lib/notification/NotificationContext.tsx
blob: b1779264ccdc146832aeabe9541d4d34d04a68ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// lib/notification/NotificationContext.tsx
"use client";

import React, { createContext, useContext, useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { toast } from 'sonner'; // 또는 react-hot-toast

interface Notification {
  id: string;
  title: string;
  message: string;
  type: string;
  relatedRecordId?: string;
  relatedRecordType?: string;
  isRead: boolean;
  createdAt: string;
}

interface NotificationContextType {
  notifications: Notification[];
  unreadCount: number;
  markAsRead: (id: string) => Promise<void>;
  markAllAsRead: () => Promise<void>;
  refreshNotifications: () => Promise<void>;
}

const NotificationContext = createContext<NotificationContextType | null>(null);

export function NotificationProvider({ children }: { children: React.ReactNode }) {
  const { data: session } = useSession();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);

  // 알림 목록 가져오기
  const refreshNotifications = async () => {
    if (!session?.user) return;

    try {
      const response = await fetch('/api/notifications');
      const data = await response.json();
      setNotifications(data.notifications);
      setUnreadCount(data.unreadCount);
    } catch (error) {
      console.error('Failed to fetch notifications:', error);
    }
  };

  // 읽음 처리
  const markAsRead = async (id: string) => {
    try {
      await fetch(`/api/notifications/${id}/read`, { method: 'PATCH' });
      setNotifications(prev => 
        prev.map(n => n.id === id ? { ...n, isRead: true } : n)
      );
      setUnreadCount(prev => prev - 1);
    } catch (error) {
      console.error('Failed to mark notification as read:', error);
    }
  };

  // 모든 알림 읽음 처리
  const markAllAsRead = async () => {
    try {
      await fetch('/api/notifications/read-all', { method: 'PATCH' });
      setNotifications(prev => prev.map(n => ({ ...n, isRead: true })));
      setUnreadCount(0);
    } catch (error) {
      console.error('Failed to mark all notifications as read:', error);
    }
  };

  // SSE 연결로 실시간 알림 수신
  useEffect(() => {
    if (!session?.user) return;

    // 초기 알림 로드
    refreshNotifications();

    // SSE 연결
    const eventSource = new EventSource('/api/notifications/stream');

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        
        if (data.type === 'heartbeat' || data.type === 'connected') {
          return; // 하트비트 및 연결 확인 메시지는 무시
        }
        
        if (data.type === 'new_notification') {
          const newNotification = data.data;
          
          // 새 알림을 기존 목록에 추가
          setNotifications(prev => [newNotification, ...prev]);
          setUnreadCount(prev => prev + 1);
          
          // Toast 알림 표시
          toast(newNotification.title, {
            description: newNotification.message,
            action: {
              label: "보기",
              onClick: () => {
                handleNotificationClick(newNotification);
              },
            },
          });
        } else if (data.type === 'notification_read') {
          const readData = data.data;
          
          // 읽음 상태 업데이트
          setNotifications(prev => 
            prev.map(n => n.id === readData.id ? { ...n, isRead: true, readAt: readData.read_at } : n)
          );
          
          if (!readData.is_read) {
            setUnreadCount(prev => Math.max(0, prev - 1));
          }
        }
      } catch (error) {
        console.error('Failed to parse SSE data:', error);
      }
    };

    eventSource.onopen = () => {
      console.log('SSE connection established');
    };

    eventSource.onerror = (error) => {
      console.error('SSE error:', error);
      // 자동 재연결은 EventSource가 처리
    };

    return () => {
      eventSource.close();
    };
  }, [session?.user]);

  const handleNotificationClick = (notification: Notification) => {
    // 알림 클릭 시 관련 페이지로 이동
    if (notification.relatedRecordId && notification.relatedRecordType) {
      const url = getNotificationUrl(notification.relatedRecordType, notification.relatedRecordId);
      window.location.href = url;
    }
    markAsRead(notification.id);
  };

  const getNotificationUrl = (type: string, id: string | null) => {
    const pathParts = window.location.pathname.split('/');
    const lng = pathParts[1];
    const domain = pathParts[2];
    
    // 도메인별 기본 URL 설정
    const baseUrls = {
      'partners': `/${lng}/partners`,
      'procurement': `/${lng}/procurement`, 
      'sales': `/${lng}/sales`,
      'engineering': `/${lng}/engineering`,
      'evcp': `/${lng}/evcp`
    };
    
    const baseUrl = baseUrls[domain as keyof typeof baseUrls] || `/${lng}/evcp`;
    
    if (!id) {
      // ID가 없는 경우 (시스템 공지, 일반 알림 등)
      switch (type) {
        case 'evaluation':
        case 'evaluation_request':
          return domain === 'partners' ? `${baseUrl}/evaluation` : `${baseUrl}/evaluations`;
        case 'announcement':
        case 'system':
          return `${baseUrl}/announcements`;
        default:
          return baseUrl;
      }
    }
    
    // ID가 있는 경우
    switch (type) {
      case 'project':
        return `${baseUrl}/projects/${id}`;
      case 'task':
        return `${baseUrl}/tasks/${id}`;
      case 'order':
        return `${baseUrl}/orders/${id}`;
      case 'evaluation_submission':
        return domain === 'partners' 
          ? `${baseUrl}/evaluation/${id}` 
          : `${baseUrl}/evaluations/submissions/${id}`;
      case 'document':
        return `${baseUrl}/documents/${id}`;
      case 'approval':
        return `${baseUrl}/approvals/${id}`;
      default:
        return baseUrl;
    }
  };

  return (
    <NotificationContext.Provider 
      value={{ 
        notifications, 
        unreadCount, 
        markAsRead, 
        markAllAsRead, 
        refreshNotifications 
      }}
    >
      {children}
    </NotificationContext.Provider>
  );
}

export function useNotifications() {
  const context = useContext(NotificationContext);
  if (!context) {
    throw new Error('useNotifications must be used within NotificationProvider');
  }
  return context;
}