Skip to content

Commit

Permalink
Merge pull request #29 from olmangjolmang/OMJM-98-post_sort
Browse files Browse the repository at this point in the history
post 최신순으로 정렬 & post 스크랩 수 추가
  • Loading branch information
chaeyeonKong authored Jul 17, 2024
2 parents e0036f8 + 69f6464 commit 659bcbf
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 54 deletions.
4 changes: 0 additions & 4 deletions src/main/java/com/ticle/server/memo/domain/Memo.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
import com.ticle.server.user.domain.User;
import jakarta.persistence.*;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Table(name = "Memo")
@Entity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.ticle.server.post.service.PostService;
import com.ticle.server.scrapped.domain.Scrapped;
import com.ticle.server.scrapped.dto.ScrappedDto;
import com.ticle.server.user.service.CustomUserDetails;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -57,9 +58,9 @@ public ResponseEntity<ResponseTemplate<Object>> findArticle(@PathVariable long i

@Operation(summary = "아티클 스크랩", description = "새로운 아티클 스크랩, 스크랩 취소")
@PostMapping("/{id}/scrap")
public ResponseEntity<ResponseTemplate<Object>> scrappedArticle(@PathVariable long id, @AuthenticationPrincipal UserDetails userDetails) {
public ResponseEntity<ResponseTemplate<Object>> scrappedArticle(@PathVariable long id, @AuthenticationPrincipal CustomUserDetails customUserDetails) {

Object scrapped = postService.scrappedById(id, userDetails);
Object scrapped = postService.scrappedById(id, customUserDetails);

if (scrapped instanceof ScrappedDto) { // 이미 스크랩 했던 경우(취소기능)
return ResponseEntity
Expand All @@ -78,9 +79,9 @@ public ResponseEntity<ResponseTemplate<Object>> scrappedArticle(@PathVariable lo
// post memo
@Operation(summary = "메모", description = "메모 작성하기")
@PostMapping("/memo/{id}")
public ResponseEntity<ResponseTemplate<Object>> memoArticle(@PathVariable long id, @RequestBody MemoRequest memoRequest, @AuthenticationPrincipal UserDetails userDetails) {
public ResponseEntity<ResponseTemplate<Object>> memoArticle(@PathVariable long id, @RequestBody MemoRequest memoRequest, @AuthenticationPrincipal CustomUserDetails customUserDetails) {
{
Object memo = postService.writeMemo(id, userDetails, memoRequest.getTargetText(), memoRequest.getContent());
Object memo = postService.writeMemo(id, customUserDetails, memoRequest.getTargetText(), memoRequest.getContent());

return ResponseEntity
.status(HttpStatus.OK)
Expand Down
14 changes: 10 additions & 4 deletions src/main/java/com/ticle/server/post/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.ticle.server.global.domain.BaseTimeEntity;
import com.ticle.server.global.domain.S3Info;
import com.ticle.server.scrapped.domain.Scrapped;
import com.ticle.server.user.domain.User;
import com.ticle.server.user.domain.type.Category;
import jakarta.persistence.*;
import lombok.*;
Expand Down Expand Up @@ -42,9 +41,9 @@ public class Post extends BaseTimeEntity {
@Column
private S3Info image;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
@Column(name = "scrap_count")
private Integer scrapCount;


@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Scrapped> scrappeds;
Expand All @@ -54,4 +53,11 @@ public class Post extends BaseTimeEntity {
private List recommendPost;


public void increaseScrapCount() {
this.scrapCount++; //스크랩 수 증가
}

public void decreaseScrapCount() {
this.scrapCount--; // 스크랩 수 감소
}
}
76 changes: 47 additions & 29 deletions src/main/java/com/ticle/server/post/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import com.ticle.server.scrapped.domain.Scrapped;
import com.ticle.server.scrapped.repository.ScrappedRepository;
import com.ticle.server.user.domain.User;
import com.ticle.server.user.repository.UserRepository;
import com.ticle.server.user.service.CustomUserDetails;
import com.ticle.server.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
Expand All @@ -19,14 +21,13 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ResponseStatusException;

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

@RequiredArgsConstructor
Expand All @@ -36,15 +37,16 @@ public class PostService {

private final PostRepository postRepository;
private final ScrappedRepository scrappedRepository;
private final UserService userService;
private final UserRepository userRepository;
private final NoteRepository noteRepository;

// 카테고리에 맞는 글 찾기
public Page<PostResponse> findAllByCategory(String category, int page) {

final int SIZE = 9; // 한 페이지에 보여질 객체 수

Pageable pageable = PageRequest.of(page - 1, SIZE);
//최신순으로 post 정렬
Pageable pageable = PageRequest.of(page - 1, SIZE, Sort.by(Sort.Direction.DESC, "createdDate"));
Page<Post> postPage;

if (category == null || category.isEmpty()) {
Expand Down Expand Up @@ -105,43 +107,54 @@ public Post findById(long id) {
recommendPost = response.formatRecommendPost(); // 새로운 추천 포스트 리스트 업데이트
}
post.setRecommendPost(recommendPost);

return post;
}


public Object scrappedById(long id, UserDetails userDetails) {
public Object scrappedById(long id, CustomUserDetails customUserDetails) {

// 게시물 조회
Post post = postRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("해당 id의 post 찾을 수 없음 id: " + id));

// getUsername에는 email이 들어있음. / email로 유저 찾고 id 찾도록 함.
User user = userService.getLoginUserByEmail(userDetails.getUsername());
Long userId = user.getId();
// System.out.println("User ID: " + userId);
Long userId = customUserDetails.getUserId();
User user = userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("해당 id의 user 찾을 수 없음 id: " + userId));

// 이미 스크랩했는지 확인
Optional<Scrapped> existingScrap = scrappedRepository.findByUserIdAndPost_PostId(userId, post.getPostId());

Scrapped scrap;

if (existingScrap.isPresent()) {
// 이미 스크랩한 상태라면 스크랩 취소
existingScrap.get().changeToUnscrapped(); //status를 unscrapped로 변경
scrappedRepository.delete(existingScrap.get());
return ScrappedDto.from(existingScrap.get());
scrap = existingScrap.get();

if ("SCRAPPED".equals(scrap.getStatus())) { // 이미 스크랩한 상태 -> 스크랩 취소
scrap.changeToUnscrapped();
post.decreaseScrapCount();
} else { // 스크랩
scrap.changeToScrapped();
post.increaseScrapCount();
}
} else {
// 새로운 스크랩 생성
scrap = Scrapped.builder()
.post(post)
.user(user)
.status("SCRAPPED")
.build();
post.increaseScrapCount(); // 새로운 스크랩 시에도 카운트 증가
}

Scrapped scrapped = new Scrapped();
scrapped.setPost(post);
scrapped.setUser(user);
scrapped.changeToScrapped(); //status를 scrapped로 변경

return scrappedRepository.save(scrapped);
// post와 scrap 저장
postRepository.save(post);
return scrappedRepository.save(scrap);
}

public Object writeMemo(long id, UserDetails userDetails, String targetText, String content) {
public Object writeMemo(long id, CustomUserDetails customUserDetails, String targetText, String content) {

Long userId = customUserDetails.getUserId();
User user = userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("해당 id의 user 찾을 수 없음 id: " + userId));

// getUsername에는 email이 들어있음. / email로 유저 찾고 id 찾도록 함.
User user = userService.getLoginUserByEmail(userDetails.getUsername());

// 같은 내용의 targetText-content 세트가 있는지 확인
Memo existingMemo = noteRepository.findByUserAndTargetTextAndContent(user, targetText, content);
Expand All @@ -150,11 +163,16 @@ public Object writeMemo(long id, UserDetails userDetails, String targetText, Str
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "이미 동일한 메모가 존재합니다.");
}

Memo memo = new Memo();
memo.setPost(postRepository.findByPostId(id));
memo.setUser(user);
memo.setTargetText(targetText);
memo.setContent(content);
// Post 객체를 찾을 때 예외 처리
Post post = postRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("해당 id의 post 찾을 수 없음 id: " + id));

Memo memo = Memo.builder()
.post(post)
.user(user)
.targetText(targetText)
.content(content)
.build();

return noteRepository.save(memo);
}
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/com/ticle/server/scrapped/domain/Scrapped.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.ticle.server.scrapped.domain;

import com.ticle.server.global.domain.BaseTimeEntity;
import com.ticle.server.post.domain.Post;
import com.ticle.server.user.domain.User;
import jakarta.persistence.*;
Expand All @@ -12,7 +13,7 @@
@NoArgsConstructor()
@AllArgsConstructor
@Builder
public class Scrapped {
public class Scrapped extends BaseTimeEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Expand All @@ -25,7 +26,7 @@ public class Scrapped {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id", nullable = false)
private Post post;

@Column(name = "status")
private String status;

Expand Down
22 changes: 11 additions & 11 deletions src/main/java/com/ticle/server/user/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
@RequiredArgsConstructor
@Transactional
@Slf4j
public class UserService{
public class UserService {

private final UserRepository userRepository;

Expand All @@ -35,39 +35,39 @@ public class UserService{
private final PasswordEncoder passwordEncoder;

@Transactional
public JwtToken signIn(String email,String password){
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email,password);
public JwtToken signIn(String email, String password) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email, password);

Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);

JwtToken jwtToken = jwtTokenProvider.generateToken(authentication);

log.info("hello"+authentication.getDetails());
log.info("hello22"+authentication.getName());
log.info("hello" + authentication.getDetails());
log.info("hello22" + authentication.getName());


return jwtToken;
}

@Transactional
public UserDto signUp(JoinRequest joinRequest){
if(userRepository.existsByEmail(joinRequest.getEmail())){
public UserDto signUp(JoinRequest joinRequest) {
if (userRepository.existsByEmail(joinRequest.getEmail())) {
throw new IllegalArgumentException("이미 사용 중인 이메일입니다");
}
String encodedPassword = passwordEncoder.encode(joinRequest.getPassword());
List<String> roles = new ArrayList<>();
roles.add("USER");
return UserDto.toDto(userRepository.save(joinRequest.toEntity(encodedPassword,roles)));
return UserDto.toDto(userRepository.save(joinRequest.toEntity(encodedPassword, roles)));
}


public User getLoginUserByEmail(String email){
if(email == null)
public User getLoginUserByEmail(String email) {
if (email == null)
return null;

Optional<User> optionalUser = userRepository.findByEmail(email);

if(optionalUser.isEmpty())
if (optionalUser.isEmpty())
return null;

return optionalUser.get();
Expand Down

0 comments on commit 659bcbf

Please sign in to comment.