-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotificationController.java
More file actions
429 lines (356 loc) · 23.1 KB
/
Copy pathNotificationController.java
File metadata and controls
429 lines (356 loc) · 23.1 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package com.carecode.domain.notification.controller;
import com.carecode.core.annotation.LogExecutionTime;
import com.carecode.core.controller.BaseController;
import com.carecode.core.exception.CareServiceException;
import com.carecode.core.security.CurrentUserFacade;
import com.carecode.domain.notification.dto.request.NotificationCreateRequest;
import com.carecode.domain.notification.dto.request.NotificationMarkAsReadRequest;
import com.carecode.domain.notification.dto.request.NotificationRegisterPushTokenRequest;
import com.carecode.domain.notification.dto.request.NotificationUpdateSettingsRequest;
import com.carecode.domain.notification.dto.request.NotificationSendTestRequest;
import com.carecode.domain.notification.dto.response.NotificationChannelStatusResponse;
import com.carecode.domain.notification.dto.response.NotificationInfoResponse;
import com.carecode.domain.notification.dto.response.NotificationSettingsResponse;
import com.carecode.domain.notification.dto.response.NotificationStatsResponse;
import com.carecode.domain.notification.dto.response.NotificationTemplateResponse;
import com.carecode.domain.notification.dto.response.NotificationDeliveryStatusResponse;
import com.carecode.domain.notification.app.NotificationFacade;
import com.carecode.domain.notification.entity.Notification;
import com.carecode.domain.notification.realtime.NotificationStreamService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import com.carecode.core.handler.ApiSuccess;
import java.util.Date;
import java.util.Map;
/** 알림 API 컨트롤러 육아 관련 알림 관리 서비스 */
@RestController
@RequestMapping("/notifications")
@RequiredArgsConstructor
@Slf4j
@PreAuthorize("isAuthenticated()")
@Tag(name = "알림 관리", description = "육아 관련 알림 관리 API")
public class NotificationController extends BaseController {
private final NotificationFacade notificationFacade;
private final CurrentUserFacade currentUserFacade;
private final NotificationStreamService notificationStreamService;
// 실시간 수신 (SSE)
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@Operation(summary = "알림 실시간 수신 (SSE)",
description = "연결 직후 connected 이벤트, 새 알림마다 notification 이벤트(JSON, id=알림 id)가 온다. "
+ "25초마다 heartbeat 주석. 끊기면 다시 연결하고 목록을 새로 불러온다.")
public SseEmitter stream(HttpServletResponse response) {
// Nginx 가 이벤트를 모아 두지 않고 바로 흘려보내게 한다.
response.setHeader("X-Accel-Buffering", "no");
response.setHeader("Cache-Control", "no-cache");
return notificationStreamService.connect(currentUserFacade.requireCurrentUserDbId());
}
// 알림 목록 조회
@GetMapping
@LogExecutionTime
@Operation(summary = "알림 목록 조회")
public ResponseEntity<List<NotificationInfoResponse>> getAllNotifications() {
String userId = getAuthenticatedUserCode();
List<NotificationInfoResponse> notifications = notificationFacade.getNotificationsByUserId(userId);
return ResponseEntity.ok(notifications);
}
// 알림 상세 조회
@GetMapping("/{notificationId}")
@LogExecutionTime
@Operation(summary = "알림 상세 조회", description = "특정 알림의 상세 정보 조회")
public ResponseEntity<NotificationInfoResponse> getNotification(@Parameter(description = "알림 ID", required = true) @PathVariable Long notificationId) {
NotificationInfoResponse notification = notificationFacade.getNotificationById(notificationId, getAuthenticatedUserCode());
return ResponseEntity.ok(notification);
}
// 알림 생성
@PostMapping
@LogExecutionTime
@Operation(summary = "알림 생성", description = "새로운 알림 생성")
public ResponseEntity<NotificationInfoResponse> createNotification(@Parameter(description = "알림 정보", required = true) @RequestBody NotificationCreateRequest request) {
NotificationInfoResponse notification = notificationFacade.createNotification(request, getAuthenticatedUserCode());
return ResponseEntity.ok(notification);
}
// 알림 수정
@PutMapping("/{notificationId}")
@LogExecutionTime
@Operation(summary = "알림 수정")
public ResponseEntity<NotificationInfoResponse> updateNotification(@Parameter(description = "알림 ID", required = true) @PathVariable Long notificationId,
@Parameter(description = "수정할 알림 정보", required = true) @RequestBody NotificationCreateRequest request) {
NotificationInfoResponse notification = notificationFacade.updateNotification(notificationId, request, getAuthenticatedUserCode());
return ResponseEntity.ok(notification);
}
// 알림 삭제
@DeleteMapping("/{notificationId}")
@LogExecutionTime
@Operation(summary = "알림 삭제")
public ResponseEntity<ApiSuccess> deleteNotification(@Parameter(description = "알림 ID", required = true) @PathVariable Long notificationId) {
notificationFacade.deleteNotification(notificationId, getAuthenticatedUserCode());
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("알림이 삭제되었습니다.").build());
}
// 알림 읽음 처리
@PutMapping("/{notificationId}/read")
@LogExecutionTime
@Operation(summary = "알림 읽음 처리", description = "알림을 읽음 상태로 변경")
public ResponseEntity<ApiSuccess> markAsRead(@Parameter(description = "알림 ID", required = true) @PathVariable Long notificationId) {
notificationFacade.markAsRead(notificationId, getAuthenticatedUserCode());
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("알림이 읽음 처리되었습니다.").build());
}
// 모든 알림 읽음 처리
@PutMapping("/read-all")
@LogExecutionTime
@Operation(summary = "모든 알림 읽음 처리", description = "사용자의 모든 알림을 읽음 상태로 변경")
public ResponseEntity<ApiSuccess> markAllAsRead() {
String userId = getAuthenticatedUserCode();
notificationFacade.markAllAsRead(userId);
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("모든 알림이 읽음 처리되었습니다.").build());
}
// 읽지 않은 알림 조회
@GetMapping("/unread")
@LogExecutionTime
@Operation(summary = "읽지 않은 알림 조회", description = "사용자의 읽지 않은 알림 목록 조회")
public ResponseEntity<List<NotificationInfoResponse>> getUnreadNotifications() {
String userId = getAuthenticatedUserCode();
List<NotificationInfoResponse> notifications = notificationFacade.getUnreadNotifications(userId);
return ResponseEntity.ok(notifications);
}
// 알림 설정 조회
@GetMapping("/settings/{userId}")
@LogExecutionTime
@Operation(summary = "알림 설정 조회")
public ResponseEntity<Map<String, Object>> getNotificationSettings(@Parameter(description = "사용자 ID", required = true) @PathVariable String userId) {
requireNotificationUserIdMatchesCurrent(userId);
Map<String, Object> settings = notificationFacade.getNotificationSettings(getAuthenticatedUserCode());
return ResponseEntity.ok(settings);
}
// 알림 설정 업데이트
@PutMapping("/settings/{userId}")
@LogExecutionTime
@Operation(summary = "알림 설정 업데이트", description = "사용자의 알림 설정을 업데이트")
public ResponseEntity<Map<String, Object>> updateNotificationSettings(@Parameter(description = "사용자 ID", required = true) @PathVariable String userId,
@Parameter(description = "알림 설정", required = true) @RequestBody Map<String, Object> settings) {
requireNotificationUserIdMatchesCurrent(userId);
Map<String, Object> updatedSettings = notificationFacade.updateNotificationSettings(getAuthenticatedUserCode(), settings);
return ResponseEntity.ok(updatedSettings);
}
// 알림 통계 조회
@GetMapping("/statistics/{userId}")
@LogExecutionTime
@Operation(summary = "알림 통계 조회", description = "사용자의 알림 관련 통계 조회")
public ResponseEntity<Map<String, Object>> getNotificationStatistics(@Parameter(description = "사용자 ID", required = true) @PathVariable String userId) {
requireNotificationUserIdMatchesCurrent(userId);
Map<String, Object> statistics = notificationFacade.getNotificationStatistics(getAuthenticatedUserCode());
return ResponseEntity.ok(statistics);
}
// 알림 설정 목록 조회
@GetMapping("/preferences")
@LogExecutionTime
@Operation(summary = "알림 설정 목록 조회")
public ResponseEntity<List<NotificationSettingsResponse>> getNotificationPreferences() {
String userId = getAuthenticatedUserCode();
List<NotificationSettingsResponse> preferences = notificationFacade.getUserPreferences(userId);
return ResponseEntity.ok(preferences);
}
// 특정 알림 타입 설정 조회
@GetMapping("/preferences/{notificationType}")
@LogExecutionTime
@Operation(summary = "특정 알림 타입 설정 조회")
public ResponseEntity<NotificationSettingsResponse> getNotificationPreferenceByType(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "알림 타입", required = true) @PathVariable String notificationType) {
requireNotificationUserIdMatchesCurrent(userId);
NotificationSettingsResponse preference = notificationFacade.getPreferenceByType(getAuthenticatedUserCode(), notificationType);
return ResponseEntity.ok(preference);
}
// 전체 알림 설정 업데이트
@PutMapping("/preferences")
@LogExecutionTime
@Operation(summary = "전체 알림 설정 업데이트", description = "사용자의 모든 알림 설정을 한 번에 업데이트")
public ResponseEntity<NotificationSettingsResponse> updateNotificationPreferences(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "알림 설정", required = true) @RequestBody NotificationSettingsResponse preferenceDto) {
requireNotificationUserIdMatchesCurrent(userId);
NotificationSettingsResponse updatedPreference = notificationFacade.savePreference(getAuthenticatedUserCode(), preferenceDto);
return ResponseEntity.ok(updatedPreference);
}
// 채널별 사용 가능 여부
@GetMapping("/channels")
@LogExecutionTime
@Operation(summary = "알림 채널 상태 조회",
description = "각 채널을 이 사용자에게 지금 실제로 발송할 수 있는지와, 불가능하면 그 이유")
public ResponseEntity<List<NotificationChannelStatusResponse>> getNotificationChannels() {
return ResponseEntity.ok(notificationFacade.getChannelStatuses(getAuthenticatedUserCode()));
}
// 알림 설정 저장
@PostMapping("/preferences")
@LogExecutionTime
@Operation(summary = "알림 설정 저장", description = "사용자의 알림 설정을 저장")
public ResponseEntity<NotificationSettingsResponse> saveNotificationPreference(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "알림 설정", required = true) @RequestBody NotificationSettingsResponse preferenceDto) {
requireNotificationUserIdMatchesCurrent(userId);
NotificationSettingsResponse savedPreference = notificationFacade.savePreference(getAuthenticatedUserCode(), preferenceDto);
return ResponseEntity.ok(savedPreference);
}
// 채널별 설정 업데이트
@PutMapping("/preferences/{notificationType}/channels/{channel}")
@LogExecutionTime
@Operation(summary = "채널별 설정 업데이트", description = "사용자의 특정 알림 타입의 채널별 설정을 업데이트")
public ResponseEntity<NotificationSettingsResponse> updateChannelPreference(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "알림 타입", required = true) @PathVariable String notificationType,
@Parameter(description = "채널", required = true) @PathVariable String channel,
@Parameter(description = "활성화 여부", required = true) @RequestParam boolean enabled) {
requireNotificationUserIdMatchesCurrent(userId);
NotificationSettingsResponse updatedPreference = notificationFacade.updateChannelPreference(getAuthenticatedUserCode(), notificationType, channel, enabled);
return ResponseEntity.ok(updatedPreference);
}
// 모든 알림 설정 비활성화
@PutMapping("/preferences/disable-all")
@LogExecutionTime
@Operation(summary = "모든 알림 설정 비활성화")
public ResponseEntity<ApiSuccess> disableAllNotifications(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId) {
requireNotificationUserIdMatchesCurrent(userId);
notificationFacade.disableAllNotifications(getAuthenticatedUserCode());
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("모든 알림 설정이 비활성화되었습니다.").build());
}
// 알림 설정 기본값으로 초기화
@PutMapping("/preferences/reset")
@LogExecutionTime
@Operation(summary = "알림 설정 초기화", description = "사용자의 알림 설정을 기본값으로 초기화")
public ResponseEntity<ApiSuccess> resetNotificationPreferences(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId) {
requireNotificationUserIdMatchesCurrent(userId);
notificationFacade.resetToDefault(getAuthenticatedUserCode());
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("알림 설정이 기본값으로 초기화되었습니다.").build());
}
// 알림 읽음 처리
@PutMapping("/mark-read")
@LogExecutionTime
@Operation(summary = "알림 읽음 처리", description = "알림을 읽음으로 표시")
public ResponseEntity<ApiSuccess> markAsRead(@Parameter(description = "읽음 처리 요청", required = true) @RequestBody NotificationMarkAsReadRequest request) {
notificationFacade.markAsRead(request, getAuthenticatedUserCode());
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("알림이 읽음으로 처리되었습니다.").build());
}
// 푸시 알림 토큰 등록
@PostMapping("/push-token")
@LogExecutionTime
@Operation(summary = "푸시 알림 토큰 등록")
public ResponseEntity<ApiSuccess> registerPushToken(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "푸시 토큰 등록 요청", required = true) @RequestBody NotificationRegisterPushTokenRequest request) {
requireNotificationUserIdMatchesCurrent(userId);
notificationFacade.registerPushToken(getAuthenticatedUserCode(), request);
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("푸시 알림 토큰이 등록되었습니다.").build());
}
// 알림 설정 수정
@PutMapping("/settings")
@LogExecutionTime
@Operation(summary = "알림 설정 수정")
public ResponseEntity<ApiSuccess> updateSettings(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "설정 수정 요청", required = true) @RequestBody NotificationUpdateSettingsRequest request) {
requireNotificationUserIdMatchesCurrent(userId);
notificationFacade.updateSettings(getAuthenticatedUserCode(), request);
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("알림 설정이 수정되었습니다.").build());
}
// 테스트 알림 발송
@PostMapping("/test")
@LogExecutionTime
@Operation(summary = "테스트 알림 발송")
public ResponseEntity<ApiSuccess> sendTestNotification(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "테스트 알림 요청", required = true) @RequestBody NotificationSendTestRequest request) {
requireNotificationUserIdMatchesCurrent(userId);
notificationFacade.sendTestNotification(getAuthenticatedUserCode(), request);
return ResponseEntity.ok(ApiSuccess.builder().timestamp(new Date()).message("테스트 알림이 발송되었습니다.").build());
}
// 알림 통계 조회
@GetMapping("/stats")
@LogExecutionTime
@Operation(summary = "알림 통계 조회")
public ResponseEntity<NotificationStatsResponse> getNotificationStats(@Parameter(description = "사용자 ID", required = true) @RequestParam String userId) {
requireNotificationUserIdMatchesCurrent(userId);
NotificationStatsResponse stats = notificationFacade.getNotificationStats(getAuthenticatedUserCode());
return ResponseEntity.ok(stats);
}
// 알림 템플릿 조회
@GetMapping("/templates")
@LogExecutionTime
@Operation(summary = "알림 템플릿 조회")
public ResponseEntity<List<NotificationTemplateResponse>> getNotificationTemplates(@Parameter(description = "알림 타입", required = false) @RequestParam(required = false) String type) {
List<NotificationTemplateResponse> templates = notificationFacade.getNotificationTemplates(type);
return ResponseEntity.ok(templates);
}
// 알림 전송 상태 조회
@GetMapping("/delivery-status/{notificationId}")
@LogExecutionTime
@Operation(summary = "알림 전송 상태 조회")
public ResponseEntity<NotificationDeliveryStatusResponse> getDeliveryStatus(@Parameter(description = "알림 ID", required = true) @PathVariable Long notificationId) {
NotificationDeliveryStatusResponse status = notificationFacade.getDeliveryStatus(notificationId, getAuthenticatedUserCode());
return ResponseEntity.ok(status);
}
// ====================
// 알림 필터링 기능 ====================
// 알림 타입별 조회
@GetMapping("/type")
@LogExecutionTime
@Operation(summary = "알림 타입별 조회", description = "특정 타입의 알림 조회")
public ResponseEntity<List<NotificationInfoResponse>> getNotificationsByType(
@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "알림 타입 (SYSTEM, POLICY, FACILITY, COMMUNITY, CHATBOT, HEALTH)", required = true) @RequestParam String notificationType) {
requireNotificationUserIdMatchesCurrent(userId);
List<NotificationInfoResponse> notifications = notificationFacade.getNotificationsByType(
getAuthenticatedUserCode(), Notification.NotificationType.valueOf(notificationType));
return ResponseEntity.ok(notifications);
}
// 기간별 알림 조회
@GetMapping("/date-range")
@LogExecutionTime
@Operation(summary = "기간별 알림 조회", description = "특정 기간의 알림 조회")
public ResponseEntity<List<NotificationInfoResponse>> getNotificationsByDateRange(
@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "시작일시 (yyyy-MM-ddTHH:mm:ss)", required = true) @RequestParam String startDate,
@Parameter(description = "종료일시 (yyyy-MM-ddTHH:mm:ss)", required = true) @RequestParam String endDate) {
requireNotificationUserIdMatchesCurrent(userId);
List<NotificationInfoResponse> notifications = notificationFacade.getNotificationsByDateRange(
getAuthenticatedUserCode(), LocalDateTime.parse(startDate), LocalDateTime.parse(endDate));
return ResponseEntity.ok(notifications);
}
// 사용자별 전체 알림 개수 조회
@GetMapping("/count")
@LogExecutionTime
@Operation(summary = "전체 알림 개수 조회")
public ResponseEntity<Map<String, Long>> getTotalNotificationCount(
@Parameter(description = "사용자 ID", required = true) @RequestParam String userId) {
requireNotificationUserIdMatchesCurrent(userId);
long count = notificationFacade.getTotalNotificationCount(getAuthenticatedUserCode());
Map<String, Long> response = new java.util.HashMap<>();
response.put("totalCount", count);
return ResponseEntity.ok(response);
}
// 읽음 상태별 알림 개수 조회
@GetMapping("/count-by-status")
@LogExecutionTime
@Operation(summary = "읽음 상태별 알림 개수 조회")
public ResponseEntity<Map<String, Long>> getNotificationCountByReadStatus(
@Parameter(description = "사용자 ID", required = true) @RequestParam String userId,
@Parameter(description = "읽음 여부 (true: 읽음, false: 읽지 않음)", required = true) @RequestParam boolean isRead) {
requireNotificationUserIdMatchesCurrent(userId);
long count = notificationFacade.getNotificationCountByReadStatus(getAuthenticatedUserCode(), isRead);
Map<String, Long> response = new java.util.HashMap<>();
response.put("count", count);
response.put("isRead", isRead ? 1L : 0L);
return ResponseEntity.ok(response);
}
private String getAuthenticatedUserCode() {
return currentUserFacade.requireCurrentUserId();
}
private void requireNotificationUserIdMatchesCurrent(String declaredUserId) {
String current = currentUserFacade.requireCurrentUserId();
if (declaredUserId == null || declaredUserId.isBlank() || !declaredUserId.equals(current)) {
throw new CareServiceException("FORBIDDEN", "요청의 사용자 ID가 로그인한 사용자와 일치하지 않습니다.");
}
}
}