-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatbotController.java
More file actions
227 lines (207 loc) · 12.4 KB
/
Copy pathChatbotController.java
File metadata and controls
227 lines (207 loc) · 12.4 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
package com.carecode.domain.chatbot.controller;
import com.carecode.core.annotation.LogExecutionTime;
import com.carecode.core.annotation.RateLimit;
import com.carecode.core.controller.BaseController;
import com.carecode.core.security.CurrentUserFacade;
import com.carecode.core.exception.CareServiceException;
import com.carecode.domain.chatbot.dto.request.ChatbotMessageRequest;
import com.carecode.domain.chatbot.dto.response.ChatbotMessageResponse;
import com.carecode.domain.chatbot.dto.response.ChatbotChatHistoryDtoResponse;
import com.carecode.domain.chatbot.dto.response.ChatbotSessionDtoResponse;
import com.carecode.domain.chatbot.dto.response.ChatbotFeedbackDtoResponse;
import com.carecode.domain.chatbot.app.ChatbotFacade;
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.util.List;
import java.util.Map;
/** 챗봇 API 컨트롤러 육아 관련 챗봇 서비스 */
@RestController
@RequestMapping("/chatbot")
@RequiredArgsConstructor
@Slf4j
@PreAuthorize("isAuthenticated()")
@Tag(name = "챗봇", description = "육아 관련 챗봇 서비스 API")
public class ChatbotController extends BaseController {
private final ChatbotFacade chatbotFacade;
private final CurrentUserFacade currentUserFacade;
// 챗봇 메시지 전송
//
// 이 엔드포인트는 요청 한 건이 곧 Claude API 유료 호출이다. 인증만 통과하면 무제한으로
// 부를 수 있으면 계정 하나로 비용을 얼마든지 발생시킬 수 있어, 호출 단위 상한을 둔다.
// 사람이 실제로 대화하는 속도(분당 수 건)보다는 넉넉하게 잡았다.
@PostMapping("/chat")
@LogExecutionTime
@RateLimit(requests = 20, windowSeconds = 60, message = "대화 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.")
@Operation(summary = "챗봇 메시지 전송", description = "챗봇과 대화를 시작")
public ResponseEntity<ChatbotMessageResponse> sendMessage(
@Parameter(description = "챗봇 요청 정보", required = true) @RequestBody ChatbotMessageRequest request) {
String userId = currentUserFacade.requireCurrentUserId();
request.setUserId(userId);
log.info("챗봇 메시지 전송: 사용자ID={}, 메시지={}", userId, request.getMessage());
try {
ChatbotMessageResponse response = chatbotFacade.processMessage(request);
return ResponseEntity.ok(response);
} catch (CareServiceException e) {
log.error("챗봇 처리 오류: {}", e.getMessage());
throw e;
} catch (Exception e) {
log.error("챗봇 처리 중 예상치 못한 오류: {}", e.getMessage(), e);
throw new CareServiceException("챗봇 처리 중 오류가 발생했습니다: " + e.getMessage(), e);
}
}
// 대화 기록 조회
@GetMapping("/history")
@LogExecutionTime
@Operation(summary = "대화 기록 조회", description = "사용자의 챗봇 대화 기록 조회")
public ResponseEntity<List<ChatbotChatHistoryDtoResponse>> getChatHistory(
@Parameter(description = "세션 ID") @RequestParam(required = false) String sessionId,
@Parameter(description = "페이지 번호") @RequestParam(defaultValue = "0") int page,
@Parameter(description = "페이지 크기") @RequestParam(defaultValue = "20") int size) {
String userId = currentUserFacade.requireCurrentUserId();
log.info("대화 기록 조회: 사용자ID={}, 세션ID={}, 페이지={}, 크기={}", userId, sessionId, page, size);
try {
List<ChatbotChatHistoryDtoResponse> history = chatbotFacade.getChatHistory(userId, sessionId, page, size);
return ResponseEntity.ok(history);
} catch (CareServiceException e) {
log.error("대화 기록 조회 오류: {}", e.getMessage());
throw e;
}
}
// 세션 목록 조회
@GetMapping("/sessions")
@LogExecutionTime
@Operation(summary = "세션 목록 조회", description = "사용자의 챗봇 세션 목록 조회")
public ResponseEntity<List<ChatbotSessionDtoResponse>> getSessions(
@Parameter(description = "페이지 번호") @RequestParam(defaultValue = "0") int page,
@Parameter(description = "페이지 크기") @RequestParam(defaultValue = "10") int size) {
String userId = currentUserFacade.requireCurrentUserId();
log.info("세션 목록 조회: 사용자ID={}, 페이지={}, 크기={}", userId, page, size);
try {
List<ChatbotSessionDtoResponse> sessions = chatbotFacade.getSessions(userId, page, size);
return ResponseEntity.ok(sessions);
} catch (CareServiceException e) {
log.error("세션 목록 조회 오류: {}", e.getMessage());
throw e;
}
}
// 메시지 피드백 처리
@PostMapping("/feedback")
@LogExecutionTime
@Operation(summary = "메시지 피드백 처리", description = "챗봇 메시지에 대한 피드백 처리")
public ResponseEntity<ChatbotFeedbackDtoResponse> processFeedback(
@Parameter(description = "메시지 ID", required = true) @RequestParam Long messageId,
@Parameter(description = "도움됨 여부", required = true) @RequestParam boolean isHelpful) {
log.info("메시지 피드백 처리: 메시지ID={}, 도움됨={}", messageId, isHelpful);
try {
chatbotFacade.processFeedback(messageId, isHelpful);
ChatbotFeedbackDtoResponse response = ChatbotFeedbackDtoResponse.builder()
.messageId(messageId)
.isHelpful(isHelpful)
.message("피드백이 성공적으로 처리되었습니다.")
.updatedAt(java.time.LocalDateTime.now())
.build();
return ResponseEntity.ok(response);
} catch (CareServiceException e) {
log.error("메시지 피드백 처리 오류: {}", e.getMessage());
throw e;
}
}
// ====================
// 챗봇 필터링 기능 ====================
// 의도 타입별 메시지 조회
@GetMapping("/messages/intent")
@LogExecutionTime
@Operation(summary = "의도 타입별 메시지 조회")
public ResponseEntity<List<ChatbotChatHistoryDtoResponse>> getMessagesByIntentType(
@Parameter(description = "(사용하지 않음) 대상은 인증 주체로 결정됩니다") @RequestParam(required = false) String userId,
@Parameter(description = "의도 타입 (GREETING, QUESTION, COMPLAINT, THANKS, GOODBYE, HEALTH_INFO, UNKNOWN)", required = true) @RequestParam String intentType) {
List<ChatbotChatHistoryDtoResponse> messages = chatbotFacade.getMessagesByIntentType(
currentUserId(), com.carecode.domain.chatbot.entity.ChatMessage.IntentType.valueOf(intentType));
return ResponseEntity.ok(messages);
}
// 기간별 메시지 조회
@GetMapping("/messages/date-range")
@LogExecutionTime
@Operation(summary = "기간별 메시지 조회")
public ResponseEntity<List<ChatbotChatHistoryDtoResponse>> getMessagesByDateRange(
@Parameter(description = "(사용하지 않음) 대상은 인증 주체로 결정됩니다") @RequestParam(required = false) 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) {
List<ChatbotChatHistoryDtoResponse> messages = chatbotFacade.getMessagesByDateRange(
currentUserId(), java.time.LocalDateTime.parse(startDate), java.time.LocalDateTime.parse(endDate));
return ResponseEntity.ok(messages);
}
// 도움됨 여부별 메시지 조회
@GetMapping("/messages/helpful")
@LogExecutionTime
@Operation(summary = "도움됨 여부별 메시지 조회")
public ResponseEntity<List<ChatbotChatHistoryDtoResponse>> getMessagesByHelpfulStatus(
@Parameter(description = "(사용하지 않음) 대상은 인증 주체로 결정됩니다") @RequestParam(required = false) String userId,
@Parameter(description = "도움됨 여부", required = true) @RequestParam Boolean isHelpful) {
List<ChatbotChatHistoryDtoResponse> messages = chatbotFacade.getMessagesByHelpfulStatus(currentUserId(), isHelpful);
return ResponseEntity.ok(messages);
}
// 키워드로 메시지 검색
@GetMapping("/messages/search")
@LogExecutionTime
@Operation(summary = "키워드로 메시지 검색")
public ResponseEntity<List<ChatbotChatHistoryDtoResponse>> searchMessagesByKeyword(
@Parameter(description = "(사용하지 않음) 대상은 인증 주체로 결정됩니다") @RequestParam(required = false) String userId,
@Parameter(description = "검색 키워드", required = true) @RequestParam String keyword) {
List<ChatbotChatHistoryDtoResponse> messages = chatbotFacade.searchMessagesByKeyword(currentUserId(), keyword);
return ResponseEntity.ok(messages);
}
// 상태별 세션 조회
@GetMapping("/sessions/status")
@LogExecutionTime
@Operation(summary = "상태별 세션 조회", description = "특정 상태의 세션 조회")
public ResponseEntity<List<ChatbotSessionDtoResponse>> getSessionsByStatus(
@Parameter(description = "(사용하지 않음) 대상은 인증 주체로 결정됩니다") @RequestParam(required = false) String userId,
@Parameter(description = "세션 상태 (ACTIVE, INACTIVE, CLOSED)", required = true) @RequestParam String status) {
List<ChatbotSessionDtoResponse> sessions = chatbotFacade.getSessionsByStatus(
currentUserId(), com.carecode.domain.chatbot.entity.ChatSession.SessionStatus.valueOf(status));
return ResponseEntity.ok(sessions);
}
// 기간별 세션 조회
@GetMapping("/sessions/date-range")
@LogExecutionTime
@Operation(summary = "기간별 세션 조회", description = "특정 기간의 세션 조회")
public ResponseEntity<List<ChatbotSessionDtoResponse>> getSessionsByDateRange(
@Parameter(description = "(사용하지 않음) 대상은 인증 주체로 결정됩니다") @RequestParam(required = false) 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) {
List<ChatbotSessionDtoResponse> sessions = chatbotFacade.getSessionsByDateRange(
currentUserId(), java.time.LocalDateTime.parse(startDate), java.time.LocalDateTime.parse(endDate));
return ResponseEntity.ok(sessions);
}
// 사용자별 세션 수 조회
@GetMapping("/sessions/count")
@LogExecutionTime
@Operation(summary = "사용자별 세션 수 조회")
public ResponseEntity<Map<String, Long>> getSessionCountByUser(
@Parameter(description = "(사용하지 않음) 대상은 인증 주체로 결정됩니다") @RequestParam(required = false) String userId) {
long count = chatbotFacade.getSessionCountByUser(currentUserId());
Map<String, Long> response = new java.util.HashMap<>();
response.put("sessionCount", count);
return ResponseEntity.ok(response);
}
/**
* 조회 대상은 언제나 로그인한 본인이다.
*
* <p>아래 조회들은 요청 파라미터의 {@code userId} 를 그대로 파사드에 넘기고 있었다.
* 즉 로그인만 하면 남의 {@code userId} 를 적어 <b>다른 사람의 상담 내역과 세션</b>을
* 그대로 읽을 수 있었다. 챗봇 대화에는 아이 건강·가정 사정이 담긴다.
*
* <p>파라미터는 기존 클라이언트 호환을 위해 남겨 두되 사용하지 않는다.
* HealthController·NotificationController 가 같은 방식으로 처리한다.
*/
private String currentUserId() {
return currentUserFacade.requireCurrentUserId();
}
}