Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main'
Browse files Browse the repository at this point in the history
  • Loading branch information
Hot-dong committed Jul 3, 2023
2 parents 43b3d39 + 2a8baed commit 5b2982c
Show file tree
Hide file tree
Showing 12 changed files with 174 additions and 87 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.khpt.projectkim.controller.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import com.khpt.projectkim.csv.CsvReader;
Expand Down Expand Up @@ -70,11 +69,12 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
return null;
}
String userId = session.getAttribute("user").toString();
List<ChatMessage> chatMessages = chatService.getUserChats(userId);

String chat = session.getAttribute("chat").toString();
session.removeAttribute("chat");
ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), chat);
chatMessages.add(chatMessage);

List<ChatMessage> chatMessages = chatService.getUserChats(userId);
chatMessages.add(new ChatMessage(ChatMessageRole.USER.value(), chat));

User user = userService.getUserByStringId(userId);

Expand All @@ -84,7 +84,7 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
try {
emitter.send(SseEmitter.event().name("info").data("Processing ChatGPT request..."));

List<String> apiResponseRecord = new ArrayList<>();
// List<String> apiResponseRecord = new ArrayList<>();

final List<ChatFunction> functions = Collections.singletonList(ChatFunction.builder()
.name("get_job_info")
Expand All @@ -93,7 +93,8 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
Map<String, String> params = new HashMap<>();
if (w.getKeyword() != null) params.put("keywords", w.getKeyword());
if (w.getSort() != null) params.put("sort", String.valueOf(w.getSort()));
if (w.getCodes()!= null) params.put("job_cd", w.getCodes()); // TODO
if (w.getCodes() != null) params.put("job-cd", w.getCodes()); // TODO
if (user.getCategory() != null) params.put("job-mid-cd", user.getCategory());
if (user.getType() != null) params.put("job_type", user.getType());
if (user.getEducation() != null) params.put("edu_lv", user.getEducation());
if (user.getRegion() != null) params.put("loc_mcd", user.getRegion());
Expand All @@ -106,15 +107,19 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
ObjectMapper mapper = new ObjectMapper();
SimplifyJsonService.Root root = mapper.readValue(apiResponse, SimplifyJsonService.Root.class);

Map<String, List<Map<String, Object>>> simplifiedJobs = simplifyJobs(root);
Map<String, List<Map<String, Object>>> simplifiedJobs = simplifyJobs(root, user.getCareer(), 15);
System.out.println("api res:");
System.out.println(apiResponse);
System.out.println(simplifiedJobs);

apiResponseRecord.add(apiResponse);
// apiResponseRecord.add(apiResponse);
Map<String, List<Map<String, Object>>> simplifiedJobs2 = simplifyJobs2(root, user.getCareer(), 15);
// String jobDataResponse = mapper.writeValueAsString(simplifiedJobs2);
emitter.send(SseEmitter.event().name("result").data("result ready"));
userService.setUserResults(userId, simplifiedJobs2);

System.out.println(simplifiedJobs);
return mapper.writeValueAsString(simplifiedJobs);
} catch (JsonProcessingException e) {
} catch (IOException e) {
throw new RuntimeException(e);
}
// TODO 요청 100개중 커리어가 맞는거 20개 고르기
Expand Down Expand Up @@ -168,6 +173,8 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
emitter.send(SseEmitter.event().name("function").data("prepare"));
}
} catch (IOException e) {
emitter.send(SseEmitter.event().name("error").data("ChatGPT 응답중 에러"));
emitter.completeWithError(e);
throw new RuntimeException(e);
}
},
Expand Down Expand Up @@ -200,15 +207,19 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
}

// send result
ObjectMapper mapper = new ObjectMapper();
SimplifyJsonService.Root root = mapper.readValue(apiResponseRecord.get(0), SimplifyJsonService.Root.class);
Map<String, List<Map<String, Object>>> simplifiedJobs = simplifyJobs2(root);
String jobDataResponse = mapper.writeValueAsString(simplifiedJobs);
emitter.send(SseEmitter.event().name("result").data(jobDataResponse));
userService.setUserResults(userId, simplifiedJobs);
// ObjectMapper mapper = new ObjectMapper();
// SimplifyJsonService.Root root = mapper.readValue(apiResponseRecord.get(0), SimplifyJsonService.Root.class);
// Map<String, List<Map<String, Object>>> simplifiedJobs = simplifyJobs2(root, user.getCareer());
// String jobDataResponse = mapper.writeValueAsString(simplifiedJobs);
// emitter.send(SseEmitter.event().name("result").data(jobDataResponse));
// userService.setUserResults(userId, simplifiedJobs);


// TODO add job codes table
chatMessages.add(new ChatMessage(
ChatMessageRole.SYSTEM.value(),
"Below is job_code_table."
));
chatMessages.add(new ChatMessage(
ChatMessageRole.SYSTEM.value(),
CsvReader.getDetailedJobCode(user.getCategory())
Expand Down Expand Up @@ -260,6 +271,8 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
emitter.send(SseEmitter.event().name("message").data(message.getContent().replaceAll(" ", "%20").replaceAll("\n", "%0A")));
}
} catch (IOException e) {
emitter.send(SseEmitter.event().name("error").data("ChatGPT functions 응답중 에러"));
emitter.completeWithError(e);
throw new RuntimeException(e);
}
},
Expand All @@ -274,7 +287,10 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
emitter.send(SseEmitter.event().name("info").data("ChatGPT processing complete."));
emitter.send(SseEmitter.event().name("complete").data("Processing complete"));
emitter.complete();
System.out.println("Save chat with functions");
} catch (IOException e) {
System.out.println("complete error3");
emitter.send(SseEmitter.event().name("error").data("채팅 저장중 에러"));
emitter.completeWithError(e);
}
}
Expand All @@ -287,17 +303,22 @@ public SseEmitter getChatEvents(HttpSession session, HttpServletResponse respons
emitter.send(SseEmitter.event().name("info").data("ChatGPT processing complete."));
emitter.send(SseEmitter.event().name("complete").data("Processing complete"));
emitter.complete();
System.out.println("Save chat without functions");
}
} catch (IOException e) {
System.out.println("complete error2");
emitter.send(SseEmitter.event().name("error").data("ChatGPT 응답 처리 중 에러"));
emitter.completeWithError(e);
}
}
);
} catch (IOException e) {
System.out.println("complete error1");
emitter.completeWithError(e);
}
}).start();

System.out.println("return emitter");
return emitter;
}

Expand All @@ -321,24 +342,16 @@ public ResponseEntity<Void> sendChat(HttpSession session, HttpServletResponse re
}

@GetMapping("/all")
public List<ChatMessage> getChats(HttpSession session, HttpServletResponse response) {
public List<ChatMessage> getChats(HttpSession session, HttpServletResponse response) throws IOException {
if (session.getAttribute("user") == null) {
System.out.println("Get chat failed. No session");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.sendRedirect("/");
return null;
}
String userId = session.getAttribute("user").toString();
return chatService.getUserChats(userId);
}

@GetMapping("/new")
public String newChat(HttpSession session) {
// TODO remove chats in user
// TODO move results to recentResults and empty results

return "chat";
}

@GetMapping("/test")
public String test(@RequestParam("cd") String cd) {
String result = CsvReader.getDetailedJobCode(cd);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,27 @@
package com.khpt.projectkim.controller.api;

import com.khpt.projectkim.dto.ResultDto;
import com.khpt.projectkim.service.ApiRequestService;
import com.khpt.projectkim.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequiredArgsConstructor
public class ResultRestController {

private final ApiRequestService apiRequestService;

private final UserService userService;

@GetMapping("/result")
public List<ResultDto> getResult(HttpSession session, HttpServletResponse response) {
public List<ResultDto> getResult(HttpSession session, HttpServletResponse response) throws IOException {
if (session.getAttribute("user") == null) {
System.out.println("Get chat failed. No session");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
System.out.println("Get result failed. No session");
response.sendRedirect("/");
return null;
}
String userId = session.getAttribute("user").toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/user")
Expand All @@ -30,10 +31,10 @@ public ResponseEntity<Void> setPrevData(HttpSession session, @RequestBody UserPr
}

@GetMapping("prev")
public UserPrevData sgtPrevData(HttpSession session, HttpServletResponse response) {
public UserPrevData getPrevData(HttpSession session, HttpServletResponse response) throws IOException {
if (session.getAttribute("user") == null) {
System.out.println("Set prev data failed. No session");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
System.out.println("Get prev data failed. No session");
response.sendRedirect("/");
return null;
}
String userId = session.getAttribute("user").toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,54 @@
import com.khpt.projectkim.dto.ExtractListFromUserDto;
import com.khpt.projectkim.entity.User;
import com.khpt.projectkim.service.ChatService;
import com.khpt.projectkim.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/chat")
@RequiredArgsConstructor
public class ChatController {

private final ChatService chatService;

private final UserService userService;

// TODO add examples. Add html code, with js

@ModelAttribute
public void addAttributes(HttpServletRequest request, Model model) {
model.addAttribute("current_url", request.getRequestURL().toString());
model.addAttribute("image", "/icons/black.png");
}

@GetMapping("/chat")
@GetMapping("/new")
public String newChat(HttpSession session, HttpServletResponse response) throws IOException {
if (session.getAttribute("user") == null) {
System.out.println("Create new chat failed. No session");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return null;
}
// TODO remove chats in user
String userId = session.getAttribute("user").toString();
userService.clearChats(userId);

// TODO move results to recentResults and empty results
userService.copyResultsToRecentResultsAndClearResults(userId);

response.sendRedirect("/chat");
return null;
}

@GetMapping
public String chat(HttpSession session, Model model) {
if (session.getAttribute("user") == null) {
System.out.println("userid is null");
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/khpt/projectkim/dto/ResultDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ public class ResultDto {

private String title; // 제목

private String region; // 지역
private String location; // 지역

private String salary; // 급여

private String type; // 근무 형태

private String education; // 학력

private String career; // 경력
private String experience_level; // 경력
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static class JobData {
@JsonProperty(defaultValue = "pd")
public Sort sort;

@JsonPropertyDescription("A list of job_code in job_code_table separated by comma. example 1) 1,2,3,4 example 2) 43,7,12,56,12,78,45,23,2")
@JsonPropertyDescription("A list of code in job_code_table separated by comma. Select all the code that is related to user. example 1) 1,2,3,4 example 2) 43,7,12,56,12,78,45,23,2")
public String codes;

// @JsonProperty(value = "job_cd", required = true)
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/com/khpt/projectkim/repository/ChatRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.khpt.projectkim.repository;

import com.khpt.projectkim.entity.Chat;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;

public interface ChatRepository extends JpaRepository<Chat, Long> {
@Modifying
@Transactional
@Query("DELETE FROM Chat c WHERE c.user = :userId")
void deleteAllByUserId(@Param("userId") String userId);
}
27 changes: 0 additions & 27 deletions src/main/java/com/khpt/projectkim/service/ChatService.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,6 @@ public class ChatService {

private final UserRepository userRepository;

// public ChatData getChatGptResponse(List<ChatData> chatDataList) {
// ObjectMapper objectMapper = new ObjectMapper();
// RestTemplate restTemplate = new RestTemplate();
// HttpHeaders headers = new HttpHeaders();
// try {
// String url = "http://localhost:8000/chat";
// headers.setContentType(MediaType.APPLICATION_JSON);
// String json = objectMapper.writeValueAsString(chatDataList);
// HttpEntity<String> requestEntity = new HttpEntity<>(json, headers);
// ResponseEntity<ChatData> res = restTemplate.exchange(url, HttpMethod.POST, requestEntity, ChatData.class);
// return res.getBody();
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }

@Transactional
public ExtractListFromUserDto getListFromUser(String userId) {
User user = userRepository.findById(Long.parseLong(userId))
Expand Down Expand Up @@ -90,13 +73,3 @@ public void addUserChats(String userId, ChatMessage chatMessage) {
}

}
//extractListFromUserDto.setUser(user);
// System.out.println("recent");
//// System.out.println(user.getRecentResults());
// extractListFromUserDto.setRecentResults(user.getRecentResults());
// System.out.println("result");
//// System.out.println(user.getResults());
// extractListFromUserDto.setResults(user.getResults());
// System.out.println("chat");
//// System.out.println(user.getChats());
// extractListFromUserDto.setChats(user.getChats());
Loading

0 comments on commit 5b2982c

Please sign in to comment.