Skip to content

Commit

Permalink
편지저장까지
Browse files Browse the repository at this point in the history
  • Loading branch information
sumin1012 committed Nov 2, 2024
1 parent 02948a8 commit e5a42ec
Show file tree
Hide file tree
Showing 16 changed files with 386 additions and 110 deletions.
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
//thymeleaf
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

//swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
}

dependencyManagement {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login", "/signup", "/letter/add", "/get/letter").permitAll()
.requestMatchers("/login", "/signup", "/letter/**", "/get/**").permitAll()
.requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-resources/**").permitAll()
.anyRequest().authenticated()
)
.sessionManagement(session -> session
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

package com.example.tomorrow_letter.config;


import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;

public class SwaggerConfig {

@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.components(new Components())
.info(apiInfo());
}

private Info apiInfo() {
return new Info()
.title("Spring Boot REST API Specifications")
.description("Specification")
.version("1.0.0");
}
}

Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package com.example.tomorrow_letter.controller;


import com.example.tomorrow_letter.dto.Letter;
import com.example.tomorrow_letter.dto.LetterRequest;
import com.example.tomorrow_letter.dto.User;
import com.example.tomorrow_letter.dto.*;
import com.example.tomorrow_letter.repository.LetterRepository;
import com.example.tomorrow_letter.service.LetterService;
import com.example.tomorrow_letter.service.SmsSchedulerService;
import jakarta.servlet.http.HttpServletRequest;
Expand All @@ -20,16 +19,6 @@
public class LetterController {

private final LetterService letterService;
private final SmsSchedulerService smsSchedulerService;

//
// @Value("${openai.model}")
// private String model;
//
// @Value("${openai.api.url}")
// private String apiURL;



@PostMapping("/add")
public ResponseEntity<?> addLetter(@RequestBody LetterRequest letterRequest, HttpServletRequest request) {
Expand All @@ -40,30 +29,40 @@ public ResponseEntity<?> addLetter(@RequestBody LetterRequest letterRequest, Htt
}

System.out.println("letter = " + letterRequest);
User user = (User) session.getAttribute("user");

Letter returnLetter =letterService.save(letterRequest, user);
//return ResponseEntity.ok(returnLetter);
System.out.println("returnLetter = " + returnLetter);
try {
smsSchedulerService.scheduleSms(returnLetter); // 문자 발송 예약
return ResponseEntity.ok("문자 발송이 예약되었습니다.");
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().body(e.getMessage());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("예약 중 오류가 발생했습니다.");
//User user = (User) session.getAttribute("user");
int userid = (int) session.getAttribute("user");

return letterService.save(letterRequest, userid);
}

@PutMapping("/update")
public ResponseEntity<?> updateLetter(@RequestBody LetterUpdate letterUpdate, HttpServletRequest request) {
HttpSession session = request.getSession(false);

if (session == null || session.getAttribute("user") == null) { //로그인하지 않았거나 로그인 상태가 아닌 경우
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("로그인 필요");
}
System.out.println("letter = " + letterUpdate);
int userid = (int) session.getAttribute("user");

return letterService.updateLetter(letterUpdate, userid);

}

/* @Value("${openai.model}")
private String model;
@Value("${openai.api.url}")
private String apiURL;
무료버전이어서 용량 초과했다는 249 오류 발생
@GetMapping("/chat")
public String chat(@RequestParam(name = "ask")String prompt){
//무료버전이어서 용량 초과했다는 249 오류 발생
// @GetMapping("/chat")
// public String chat(@RequestParam(name = "ask")String prompt){
//
// ChatGPTRequest request = new ChatGPTRequest(model, prompt);
// ChatGPTResponse chatGPTResponse = template.postForObject(apiURL, request, ChatGPTResponse.class);
// return chatGPTResponse.getChoices().get(0).getMessage().getContent();
// }
ChatGPTRequest request = new ChatGPTRequest(model, prompt);
ChatGPTResponse chatGPTResponse = template.postForObject(apiURL, request, ChatGPTResponse.class);
return chatGPTResponse.getChoices().get(0).getMessage().getContent();
}*/

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
package com.example.tomorrow_letter.controller;


import com.example.tomorrow_letter.dto.Letter;
import com.example.tomorrow_letter.dto.User;
import com.example.tomorrow_letter.dto.UserLogin;
import com.example.tomorrow_letter.dto.UserSignup;
import com.example.tomorrow_letter.dto.*;
import com.example.tomorrow_letter.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
Expand All @@ -18,6 +15,7 @@
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
@RequiredArgsConstructor
Expand All @@ -44,15 +42,15 @@ public ResponseEntity<?> login(@RequestBody UserLogin userLogin,
{

System.out.println("userLogin = " + userLogin.toString());
User responseMember = userService.login(userLogin);
Optional<User> responseMember = userService.login(userLogin);

System.out.println("responseMember = " + responseMember);
if (responseMember==null) {
if (responseMember.isEmpty()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("로그인 정보 없거나 아이디 또는 비밀번호가 맞지 않습니다.");
}

HttpSession session = request.getSession();
session.setAttribute("user", responseMember);
session.setAttribute("user", responseMember.get().getId());
session.setMaxInactiveInterval(60 * 30);
System.out.println("Session ID: " + session.getId());
System.out.println("Session User: " + session.getAttribute("user"));
Expand All @@ -71,22 +69,71 @@ public ResponseEntity<?> logout(HttpServletRequest request) {
return ResponseEntity.ok("로그아웃");
}

@GetMapping("/get/letter")
public Object getLetter(HttpServletRequest request) {
@GetMapping("/get/all/letter")
public Object getAllLetter(HttpServletRequest request) {
HttpSession session=request.getSession(false);

if (session == null || session.getAttribute("user") == null) { //로그인하지 않았거나 로그인 상태가 아닌 경우
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("로그인 필요");
}

int userid = (int) session.getAttribute("user");

try {
List<Letter> list = userService.getAllLetter(userid);
if (list.isEmpty()) {
return ResponseEntity.ok("들어 있는 편지가 없음");
}
return list;
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("로그인 필요함");
}

}

@GetMapping("/get/sent/letter")
public Object getSentLetter(HttpServletRequest request) {
HttpSession session=request.getSession(false);

if (session == null || session.getAttribute("user") == null) { //로그인하지 않았거나 로그인 상태가 아닌 경우
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("로그인 필요");
}

User user = (User) session.getAttribute("user");
int userid = (int) session.getAttribute("user");

//Letter returnLetter =letterService.save(letterRequest, user);
List<Letter> list = userService.getAllLetter(user);
try {
List<Letter> list = userService.getSentLetter(userid);
if (list.isEmpty()) {
return ResponseEntity.ok("들어 있는 보낸 편지가 없음");
}
return list;
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("로그인 필요함");
}

}

@GetMapping("/get/received/letter")
public Object getReceivedLetter(HttpServletRequest request) {
HttpSession session=request.getSession(false);

if (session == null || session.getAttribute("user") == null) { //로그인하지 않았거나 로그인 상태가 아닌 경우
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("로그인 필요");
}

if(list.isEmpty()){
return ResponseEntity.ok("들어 있는 편지가 없음");
int userid = (int) session.getAttribute("user");

try {
List<Letter> list = userService.getReceivedLetter(userid);
if (list.isEmpty()) {
return ResponseEntity.ok("들어 있는 받은 편지가 없음");
}
return list;
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("로그인 필요함");
}
return list;

}


}
11 changes: 7 additions & 4 deletions src/main/java/com/example/tomorrow_letter/dto/Letter.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.example.tomorrow_letter.dto;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import lombok.*;

Expand All @@ -22,18 +22,21 @@ public class Letter {

private String letter;

private String ReceivePhone;
private String receivePhone;

private LocalDateTime createdAt;

private LocalDateTime sendAt;

@Enumerated(EnumType.STRING)
private LetterStatus status; //발송예쩡, 발송완료
private LetterStatus status; //발송예정, 발송완료

@Enumerated(EnumType.STRING)
private LetterisSent letterisSent; //받은 편지인지 보낸 편지인지

@ManyToOne
@JoinColumn(name = "user_id") // 외래 키
@JsonIgnore
@JsonIgnoreProperties("letterStore")
private User user;

}
22 changes: 22 additions & 0 deletions src/main/java/com/example/tomorrow_letter/dto/LetterUpdate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.example.tomorrow_letter.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;

@AllArgsConstructor
@Setter
@Getter
public class LetterUpdate {

private int letterId;

private String letter;

private String receivePhone;

private LocalDateTime sendAt;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.example.tomorrow_letter.dto;

public enum LetterisSent {
SENT, //보낸편지
RECEIVED //받은 편지
}
25 changes: 24 additions & 1 deletion src/main/java/com/example/tomorrow_letter/dto/User.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@

package com.example.tomorrow_letter.dto;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Entity
@Table(name="user")
Expand All @@ -28,7 +31,27 @@ public class User {
private LocalDateTime createdAt;


@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@Builder.Default
@JsonBackReference
@ToString.Exclude
private List<Letter> letterStore = new ArrayList<>();


@JsonBackReference
public List<Letter> getSentLetter() { //보낸 문자만 가져오기
return letterStore.stream()
.filter(letter ->
letter.getLetterisSent().equals(LetterisSent.SENT))
.toList();
}

@JsonBackReference// 받은 문자 목록 가져오기
public List<Letter> getReceivedLetter() {
return letterStore.stream()
.filter(letter ->
letter.getLetterisSent().equals(LetterisSent.RECEIVED))
.toList();
}
}

13 changes: 13 additions & 0 deletions src/main/java/com/example/tomorrow_letter/dto/UserDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.tomorrow_letter.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserDTO {
private int id;
private String nickname;
private String phone;
private String password; // 편지 목록
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import com.example.tomorrow_letter.dto.Letter;
import org.springframework.data.jpa.repository.JpaRepository;

public interface LetterRepository extends JpaRepository<Letter, Long> {
import java.time.LocalDateTime;
import java.util.Optional;

public interface LetterRepository extends JpaRepository<Letter, Long> {
public Letter findById(int id);
}
Loading

0 comments on commit e5a42ec

Please sign in to comment.