From 29321c1bd11bba6140efb5084e612f1b59aa9045 Mon Sep 17 00:00:00 2001 From: chae33 Date: Wed, 17 Jan 2024 23:04:03 +0900 Subject: [PATCH 01/72] [feat] WritePost --- .../community/controller/PostController.java | 42 +++++++++++-- .../community/dto/WritePostRequestDto.java | 24 +++++++ .../backend/domain/community/entity/Post.java | 2 +- .../community/repository/PostRepository.java | 2 + .../domain/community/service/PostService.java | 63 +++++++++++++++++++ .../domain/community/service/S3Service.java | 10 +-- .../backend/domain/profile/entity/Badge.java | 50 +++++++-------- .../kimgreen/backend/response/Message.java | 3 + 8 files changed, 155 insertions(+), 41 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index a21d730..7056452 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -1,14 +1,48 @@ package com.kimgreen.backend.domain.community.controller; +import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; +import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.community.service.PostService; +import com.kimgreen.backend.response.Response; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; + +import static com.kimgreen.backend.response.Message.*; +import static com.kimgreen.backend.response.Response.*; +import static org.springframework.http.HttpStatus.OK; +import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; + @Tag(name = "Post") @RestController +@RequiredArgsConstructor @RequestMapping(value="/post") + public class PostController { -} + private final PostService postService; + private final MemberService memberService; + + @Operation(summary = "게시글 작성(인증)") + @ResponseStatus(OK) + @PostMapping(path="/check", consumes = MULTIPART_FORM_DATA_VALUE) + public Response writeCheckPost(@RequestBody WritePostRequestDto writePostRequestDto, + @RequestPart(name = "files") MultipartFile multipartFiles) throws IOException { //파일 필수 O + postService.writeCheckPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); + return success(SUCCESS_TO_WRITE_POST); + } + + @Operation(summary = "게시글 작성(일상)") + @ResponseStatus(OK) + @PostMapping(path="/daily", consumes = MULTIPART_FORM_DATA_VALUE) + public Response writeDailyPost(@RequestPart(name = "body(json)") WritePostRequestDto writePostRequestDto, + @RequestPart(name = "files", required = false) MultipartFile multipartFiles) throws IOException { //파일 필수 X + postService.writeDailyPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); + return success(SUCCESS_TO_WRITE_POST); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java new file mode 100644 index 0000000..d76c91b --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java @@ -0,0 +1,24 @@ +package com.kimgreen.backend.domain.community.dto; + +import com.kimgreen.backend.domain.community.entity.Category; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.Tag; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class WritePostRequestDto { + private String category; + private String content; + + public Post toPostEntity(String category, String content) { + return Post.builder() + .category(Category.valueOf(category)) + .content(content) + .tag(Tag.DAILY) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java index 3af4d6a..371973e 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java @@ -9,6 +9,7 @@ import lombok.NoArgsConstructor; import java.util.ArrayList; +import java.util.Calendar; import java.util.List; @Getter @@ -45,5 +46,4 @@ public class Post extends AuditEntity { private Category category; @Enumerated(EnumType.STRING) private Tag tag; - } diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java index 036309c..16a4f23 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java @@ -1,9 +1,11 @@ package com.kimgreen.backend.domain.community.repository; +import com.kimgreen.backend.domain.community.entity.Category; import com.kimgreen.backend.domain.community.entity.Post; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface PostRepository extends JpaRepository { + int countByCategory(Category category); //해당 카테고리에 속한 게시글 수 조회 } diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index 4ad8a65..342e49a 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -1,7 +1,70 @@ package com.kimgreen.backend.domain.community.service; +import com.kimgreen.backend.domain.community.entity.Category; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.PostImg; +import com.kimgreen.backend.domain.community.repository.PostImgRepository; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.member.entity.Member; +import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.util.List; @Service +@RequiredArgsConstructor public class PostService { + + private final S3Service s3Service; + private final PostRepository postRepository; + private final PostImgRepository postImgRepository; + + @Transactional + public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member writer) throws IOException { + // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, + // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. + + // post를 먼저 저장 + Post post = postRepository.save(writePostRequestDto.toPostEntity( + writePostRequestDto.getCategory(), + writePostRequestDto.getContent())); + + //파일을 첨부한 경우 + if(multipartFile != null){ + // s3에 첨부파일을 저장하고, db에도 post_file을 저장 + uploadPostFileList(multipartFile, post); + } + } + + @Transactional + public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member writer) throws IOException { + // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, + // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. + + // post를 먼저 저장 + Post post = postRepository.save(writePostRequestDto.toPostEntity( + writePostRequestDto.getCategory(), + writePostRequestDto.getContent())); + + //파일을 첨부한 경우 + if(multipartFile != null){ + // s3에 첨부파일을 저장하고, db에도 post_file을 저장 + uploadPostFileList(multipartFile, post); + } + } + + @Transactional + public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { + // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, + // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. + + PostImg postFile = postImgRepository.save(PostImg.builder() + .imgUrl(s3Service.saveFile(multipartFile)) + .title(multipartFile.getOriginalFilename()) + .post(post).build()); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java index 9a2de1a..17b1061 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java @@ -22,8 +22,8 @@ public class S3Service { private String bucket; public String saveFile(MultipartFile multipartFile) throws IOException { - String originalFilename = multipartFile.getOriginalFilename(); - String createdFilename = createFileName(originalFilename); + String originalFilename = multipartFile.getOriginalFilename(); //사용자가 업로드한 파일명 + String createdFilename = createFileName(originalFilename); //겹치지 않게 랜덤 파일명 생성 ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(multipartFile.getSize()); @@ -31,10 +31,6 @@ public String saveFile(MultipartFile multipartFile) throws IOException { amazonS3.putObject(bucket, createdFilename, multipartFile.getInputStream(), metadata); - uploadDB(PostImg.builder() - .imgUrl(createdFilename) - .title(originalFilename) - .build()); //return amazonS3.getUrl(bucket, createdFilename).toString(); //key? return createdFilename; //createdFilename = key : S3URL+key 형식으로 불러오면 됨 } @@ -47,4 +43,4 @@ public String createFileName(String fileName) { String fileExtension = fileName.substring(fileName.lastIndexOf(".")); return UUID.randomUUID().toString()+fileExtension; } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index 7f99435..98be329 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -23,6 +23,11 @@ public class Badge extends AuditEntity { @JoinColumn(name="member_id") private Member member; + @Column(name="earlybird_count",columnDefinition = "int default 0" ) + private int earlybirdCount; + @Column(name="ealrybird_is_achieved",columnDefinition = "boolean default false") + private boolean earlybirdIsAchieved; + @Column(name="mentor_count",columnDefinition = "int default 0") private int mentorCount; @Column(name="mentor_is_achieved",columnDefinition = "boolean default false") @@ -43,66 +48,52 @@ public class Badge extends AuditEntity { @Column(name="receipt_count",columnDefinition = "int default 0") private int receiptCount; + @Column(name="receipt_3_is_achieved",columnDefinition = "boolean default false") + private boolean receipt3IsAchieved; @Column(name="receipt_10_is_achieved",columnDefinition = "boolean default false") private boolean receipt10IsAchieved; - @Column(name="receipt_20_is_achieved",columnDefinition = "boolean default false") - private boolean receipt20IsAchieved; - @Column(name="receipt_50_is_achieved",columnDefinition = "boolean default false") - private boolean receipt50IsAchieved; @Column(name="reusable_count",columnDefinition = "int default 0") private int reusableCount; + @Column(name="reusable_3_is_achieved",columnDefinition = "boolean default false") + private boolean reusable3IsAchieved; @Column(name="reusable_10_is_achieved",columnDefinition = "boolean default false") private boolean reusable10IsAchieved; - @Column(name="reusable_20_is_achieved",columnDefinition = "boolean default false") - private boolean reusable20IsAchieved; - @Column(name="reusable_50_is_achieved",columnDefinition = "boolean default false") - private boolean reusable50IsAchieved; @Column(name="plastic_count",columnDefinition = "int default 0") private int plasticCount; + @Column(name="plastic_3_is_achieved",columnDefinition = "boolean default false") + private boolean plastic3IsAchieved; @Column(name="plastic_10_is_achieved",columnDefinition = "boolean default false") private boolean plastic10IsAchieved; - @Column(name="plastic_20_is_achieved",columnDefinition = "boolean default false") - private boolean plastic20IsAchieved; - @Column(name="plastic_50_is_achieved",columnDefinition = "boolean default false") - private boolean plastic50IsAchieved; @Column(name="plogging_count",columnDefinition = "int default 0") private int ploggingCount; + @Column(name="plogging_3_is_achieved",columnDefinition = "boolean default false") + private boolean plogging3IsAchieved; @Column(name="plogging_10_is_achieved",columnDefinition = "boolean default false") private boolean plogging10IsAchieved; - @Column(name="plogging_20_is_achieved",columnDefinition = "boolean default false") - private boolean plogging20IsAchieved; - @Column(name="plogging_50_is_achieved",columnDefinition = "boolean default false") - private boolean plogging50IsAchieved; @Column(name="reform_count",columnDefinition = "int default 0") private int reformCount; + @Column(name="reform_3_is_achieved",columnDefinition = "boolean default false") + private boolean reform3IsAchieved; @Column(name="reform_10_is_achieved",columnDefinition = "boolean default false") private boolean reform10IsAchieved; - @Column(name="reform_20_is_achieved",columnDefinition = "boolean default false") - private boolean reform20IsAchieved; - @Column(name="reform_50_is_achieved",columnDefinition = "boolean default false") - private boolean reform50IsAchieved; @Column(name="transport_count",columnDefinition = "int default 0") private int transportCount; + @Column(name="transport_3_is_achieved",columnDefinition = "boolean default false") + private boolean transport3IsAchieved; @Column(name="transport_10_is_achieved",columnDefinition = "boolean default false") private boolean transport10IsAchieved; - @Column(name="transport_20_is_achieved",columnDefinition = "boolean default false") - private boolean transport20IsAchieved; - @Column(name="transport_50_is_achieved",columnDefinition = "boolean default false") - private boolean transport50IsAchieved; @Column(name="etc_count",columnDefinition = "int default 0") private int etcCount; + @Column(name="etc_3_is_achieved",columnDefinition = "boolean default false") + private boolean etc3IsAchieved; @Column(name="etc_10_is_achieved",columnDefinition = "boolean default false") private boolean etc10IsAchieved; - @Column(name="etc_20_is_achieved",columnDefinition = "boolean default false") - private boolean etc20IsAchieved; - @Column(name="etc_50_is_achieved",columnDefinition = "boolean default false") - private boolean etc50IsAchieved; @Column(name="adventurer_is_achieved",columnDefinition = "boolean default false") @@ -110,4 +101,5 @@ public class Badge extends AuditEntity { @Column(name="golden_is_achieved",columnDefinition = "boolean default false") private boolean goldenIsAchieved; -} + +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 40d08a0..e73587c 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -8,4 +8,7 @@ public class Message { public static String CHANGE_ALARM_SUCCESS="알림 설정 변경 성공했습니다."; public static String DELETE_MEMBER_SUCCESS="탈퇴하기 성공했습니다."; + + public static String SUCCESS_TO_WRITE_POST="인증 게시글 작성 성공했습니다."; + } From 8b42e0d71a9d3439506901080826e9655bd3f151 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 14:39:28 +0900 Subject: [PATCH 02/72] [feat] changeNickname & changeProfileImg --- .../Authentication/JwtAuthenticationEntryPoint.java | 7 +++++++ .../domain/community/dto/WritePostRequestDto.java | 10 +++++++++- .../backend/domain/community/service/PostService.java | 4 ++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java index 676c0c9..5fb1a19 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java @@ -26,6 +26,13 @@ public void commence(HttpServletRequest request, response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json; charset=UTF-8"); +/* if (EXPIRED.equals(exception)) { //exception이 null인지 확인 + setResponse(response, EXPIRED); + } + if (DENIED.equals(exception)) { + setResponse(response, DENIED); + }*/ + if(exception.equals(EXPIRED)) { setResponse(response,EXPIRED); } diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java index d76c91b..5742d9a 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java @@ -14,7 +14,15 @@ public class WritePostRequestDto { private String category; private String content; - public Post toPostEntity(String category, String content) { + public Post toCertifyPostEntity(String category, String content) { + return Post.builder() + .category(Category.valueOf(category)) + .content(content) + .tag(Tag.CERTIFY) + .build(); + } + + public Post toDailyPostEntity(String category, String content) { return Post.builder() .category(Category.valueOf(category)) .content(content) diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index 342e49a..d7f1d60 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -29,7 +29,7 @@ public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFil // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. // post를 먼저 저장 - Post post = postRepository.save(writePostRequestDto.toPostEntity( + Post post = postRepository.save(writePostRequestDto.toCertifyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent())); @@ -46,7 +46,7 @@ public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFil // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. // post를 먼저 저장 - Post post = postRepository.save(writePostRequestDto.toPostEntity( + Post post = postRepository.save(writePostRequestDto.toDailyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent())); From 71d7a27cc3209b283bde29066a4118e1a2331bc6 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 17:35:28 +0900 Subject: [PATCH 03/72] [feat] getSettingInfo --- .../kimgreen/backend/domain/BadgeList.java | 55 +++++++------- .../domain/community/service/S3Service.java | 17 ++++- .../member/controller/MemberController.java | 22 ++++++ .../dto/Member/SettingInfoResponseDto.java | 20 ++++++ .../backend/domain/member/entity/Member.java | 4 ++ .../domain/member/service/AuthService.java | 25 +++++++ .../domain/member/service/MemberService.java | 62 +++++++++++++++- .../backend/domain/profile/entity/Badge.java | 71 +++++++++---------- .../domain/profile/entity/ProfileBadge.java | 3 + .../profile/entity/RepresentativeBadge.java | 2 + .../profile/repository/BadgeRepository.java | 2 + .../repository/ProfileBadgeRepository.java | 2 + .../RepresentativeBadgeRepository.java | 11 +++ 13 files changed, 231 insertions(+), 65 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/repository/RepresentativeBadgeRepository.java diff --git a/src/main/java/com/kimgreen/backend/domain/BadgeList.java b/src/main/java/com/kimgreen/backend/domain/BadgeList.java index 5a5c5d9..5e00036 100644 --- a/src/main/java/com/kimgreen/backend/domain/BadgeList.java +++ b/src/main/java/com/kimgreen/backend/domain/BadgeList.java @@ -1,33 +1,34 @@ package com.kimgreen.backend.domain; public enum BadgeList { - MENTOR("그린 멘토",5), - MENTEE("그린 멘티",5), - EARLYBIRD("얼리버드",3), - NORANG("김노랑",10), - YEONDU("김연두",20), - GREEN("김그린",50), - RECEIPT_3("영수증도 전자로",3), - RECEIPT_10("디지털 환경 지킴이",10), - REUSABLE_3("re: user",3), - REUSABLE_10("re: 마스터",10), - PLASTIC_3("자연과 친구하기",3), - PLASTIC_10("자연과 물아일체",10), - PLOGGING_3("자연 속에 만 보 추구",3), - PLOGGING_10("클린로드의 개척자",10), - REFORM_3("손재주 아티스트",3), - REFORM_10("친환경 대가",10), - TRANSPORT_3("탄소 헤이터",3), + BLANK(""), + MENTOR("그린 멘토",5,"mentor.png"), + MENTEE("그린 멘티",5,"mentee.png"), + EARLYBIRD("얼리버드",3,"earlybird.png"), + NORANG("김노랑",10,"norang.png"), + YEONDU("김연두",20,"yeondu.png"), + GREEN("김그린",50,"green.png"), + RECEIPT_3("영수증도 전자로","electronic_receipt.png"), + RECEIPT_10("디지털 환경 지킴이",10,"digital_protector.png"), + REUSABLE_3("re: user",3,"re_user.png"), + REUSABLE_10("re: 마스터",10,"re_master.png"), + PLASTIC_3("자연과 친구하기",3,"eco_friend.png"), + PLASTIC_10("자연과 물아일체",10,"eco_one.png"), + PLOGGING_3("자연 속에 만 보 추구",3,"jamanchu.png"), + PLOGGING_10("클린로드의 개척자",10,"clean_road.png"), + REFORM_3("손재주 아티스트",3,"artist.png"), + REFORM_10("친환경 대가",10,"eco_master.png"), + TRANSPORT_3("탄소 헤이터",3,"C_hater.png"), TRANSPORT_10("지구 세이버",10), - ETC_3("아마추어 기타리스트",3), - ETC_10("프로 기타리스트",10), - ADVENTURER("환경 모험가"), - DOCTOR("김그린 박사"), - GOLDEN_KIMGREEN("황금 김그린"); + ETC_3("아마추어 기타리스트",3,"amateur_guitarist.png"), + ETC_10("프로 기타리스트",10,"pro_guitarist.png"), + ADVENTURER("환경 모험가","adventurer.png"), + DOCTOR("김그린 박사","doctor.png"), + GOLDEN_KIMGREEN("황금 김그린","golden_kimgreen.png"); - private String name; - private int goal; - private String url; + public String name; + public int goal; + public String url; private BadgeList(String name, int goal) { this.name = name; @@ -36,6 +37,10 @@ private BadgeList(String name, int goal) { private BadgeList(String name) { this.name = name; } + private BadgeList(String name, String url) { + this.name = name; + this.url = url; + } private BadgeList(String name, int goal, String url) { this.name = name; this.goal = goal; diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java index 17b1061..c8bca48 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java @@ -11,6 +11,7 @@ import org.springframework.web.multipart.MultipartFile; import java.io.IOException; +import java.net.URL; import java.util.UUID; @Service @@ -35,12 +36,22 @@ public String saveFile(MultipartFile multipartFile) throws IOException { return createdFilename; //createdFilename = key : S3URL+key 형식으로 불러오면 됨 } - public void uploadDB(PostImg postImg) { - postImgRepository.save(postImg); + //삭제 + public void delete(String url) { + amazonS3.deleteObject(bucket, url); } + //db에 저장 - 필요없으면 삭제 O + public void uploadDB(PostImg postImg) {postImgRepository.save(postImg);} + //랜덤이름 생성 public String createFileName(String fileName) { String fileExtension = fileName.substring(fileName.lastIndexOf(".")); return UUID.randomUUID().toString()+fileExtension; } -} \ No newline at end of file + + //실제 주소 얻기 + public String getFullUrl(String key) { + return amazonS3.getUrl(bucket,key).toString(); + } + +} diff --git a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java index d31400f..175fac6 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java +++ b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java @@ -37,4 +37,26 @@ public Response deleteMember() { return success(DELETE_MEMBER_SUCCESS); } + + @Operation(summary = "닉네임 변경하기") + @ResponseStatus(OK) + @PatchMapping("/nickname") + public Response changeNickname(@RequestBody NicknameRequestDto nicknameRequestDto) { + memberService.changeNickname(nicknameRequestDto.getNickname()); + return success(CHANGE_NICKNAME_SUCCESS); + } + @Operation(summary = "프로필 사진진 변경기") + @ResponseStatus(OK) + @PatchMapping(value="/profile-img",consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public Response changeProfileImg(@RequestPart(value="file") MultipartFile multipartFile) throws IOException { + memberService.changeProfileImg(multipartFile); + return success(CHANGE_PROFILE_IMG_SUCCESS); + } + + @Operation(summary = "설정창 정보 불러오기") + @ResponseStatus(OK) + @GetMapping() + public Response getSettingsInfo() { + return success(GET_MEMBER_INFO_SETTING_SUCCESS, memberService.getSettingInfo()); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java new file mode 100644 index 0000000..49ae2f6 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java @@ -0,0 +1,20 @@ +package com.kimgreen.backend.domain.member.dto.Member; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class SettingInfoResponseDto { + private String nickname; + private String profileImg; + private String badge; + private String badgeImg; + private boolean commentAlarm; + private boolean likeAlarm; + +} diff --git a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java index 732dcdb..82fb212 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java +++ b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java @@ -27,12 +27,16 @@ public class Member extends AuditEntity { //OneToMany @OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default private List posts = new ArrayList<>(); @OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default private List likes = new ArrayList<>(); @OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default private List comments = new ArrayList<>(); @OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default private List reports = new ArrayList<>(); diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java index 2ae34b0..5da1fcd 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java @@ -1,6 +1,7 @@ package com.kimgreen.backend.domain.member.service; import com.kimgreen.backend.config.Authentication.JwtProvider; +import com.kimgreen.backend.domain.BadgeList; import com.kimgreen.backend.domain.member.dto.Auth.ChangePasswordDto; import com.kimgreen.backend.domain.member.dto.Auth.LogInRequestDto; import com.kimgreen.backend.domain.member.dto.Auth.SignUpRequestDto; @@ -9,6 +10,12 @@ import com.kimgreen.backend.domain.member.entity.RefreshToken; import com.kimgreen.backend.domain.member.repository.MemberRepository; import com.kimgreen.backend.domain.member.repository.RefreshTokenRepository; +import com.kimgreen.backend.domain.profile.entity.Badge; +import com.kimgreen.backend.domain.profile.entity.ProfileBadge; +import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import com.kimgreen.backend.domain.profile.repository.BadgeRepository; +import com.kimgreen.backend.domain.profile.repository.ProfileBadgeRepository; +import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; import com.kimgreen.backend.exception.DuplicateEmail; import com.kimgreen.backend.exception.LogInFailureEmail; import com.kimgreen.backend.exception.LogInFailurePassword; @@ -30,6 +37,9 @@ public class AuthService { private final MemberRepository memberRepository; private final RefreshTokenRepository refreshTokenRepository; + private final BadgeRepository badgeRepository; + private final ProfileBadgeRepository profileBadgeRepository; + private final RepresentativeBadgeRepository representativeBadgeRepository; private final PasswordEncoder passwordEncoder; private final JwtProvider jwtProvider; private final AuthenticationManagerBuilder authenticationManagerBuilder; @@ -43,7 +53,9 @@ public void signUp(SignUpRequestDto signUpRequestDto) { String nickname = signUpRequestDto.getNickname(); validateEmail(email); + memberRepository.save(signUpRequestDto.toMemberEntity(email, passwordEncoder.encode(password),nickname)); + saveMember(signUpRequestDto,email, password, nickname); } @Transactional @@ -136,4 +148,17 @@ public void validateEmail(String email) { } } + public void saveMember(SignUpRequestDto signUpRequestDto,String email, String password, String nickname) { + memberRepository.save(signUpRequestDto.toMemberEntity(email, passwordEncoder.encode(password),nickname)); + Member member = memberRepository.findByEmail(email); + profileImgRepository.save(signUpRequestDto.toMemberProfileImgEntity(member)); + badgeRepository.save(Badge.builder().member(member).build()); + profileBadgeRepository.save(ProfileBadge.builder().member(member).build()); + representativeBadgeRepository.save( + RepresentativeBadge.builder() + .representativeBadge(BadgeList.BLANK) + .member(member) + .build()); + } + } diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java index 213f1fb..9855766 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java @@ -1,11 +1,17 @@ package com.kimgreen.backend.domain.member.service; +import com.kimgreen.backend.domain.community.service.S3Service; +import com.kimgreen.backend.domain.member.dto.Member.SettingInfoResponseDto; import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.entity.MemberProfileImg; import com.kimgreen.backend.domain.member.entity.RefreshToken; import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; import com.kimgreen.backend.domain.member.repository.MemberRepository; import com.kimgreen.backend.domain.member.repository.RefreshTokenRepository; +import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import com.kimgreen.backend.domain.profile.repository.BadgeRepository; +import com.kimgreen.backend.domain.profile.repository.ProfileBadgeRepository; +import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; import lombok.RequiredArgsConstructor; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @@ -19,7 +25,10 @@ public class MemberService { private final MemberRepository memberRepository; private final RefreshTokenRepository refreshTokenRepository; private final MemberProfileImgRepository memberProfileImgRepository; - + private final RepresentativeBadgeRepository representativeBadgeRepository; + private final BadgeRepository badgeRepository; + private final ProfileBadgeRepository profileBadgeRepository; + private final S3Service s3Service; public Member getCurrentMember() { @@ -43,6 +52,9 @@ public void deleteMember() { if(refreshTokenRepository.existsByEmail(email)) { refreshTokenRepository.deleteByEmail(email); } + profileBadgeRepository.deleteByMember(member); + badgeRepository.deleteByMember(member); + representativeBadgeRepository.deleteByMember(member); memberProfileImgRepository.deleteByMember(member); memberRepository.deleteByEmail(email); } @@ -65,4 +77,52 @@ public void changeLikeAlarm() { member.changeLikeAlarm(true); } } + + @Transactional + public void changeNickname(String nickname) { + Member member = getCurrentMember(); + member.changeNickname(nickname); + } + @Transactional + public void changeProfileImg(MultipartFile multipartFile) throws IOException { + Member member= getCurrentMember(); + MemberProfileImg memberProfileImg = memberProfileImgRepository.findByMember(member); + //S3에 업로드 + String newImgUrl = s3Service.saveProfileFile(multipartFile); + String title = multipartFile.getOriginalFilename(); + + // 기존이미지 S3에서 삭제 + deleteFromS3(memberProfileImg.getImgUrl()); + + //엔티티 변경 + memberProfileImg.changeProfileImg(newImgUrl,title); + } + + public SettingInfoResponseDto getSettingInfo() { + String badgeUrl=""; + Member member = getCurrentMember(); + + MemberProfileImg memberProfileImg = memberProfileImgRepository.findByMember(member); + String profileUrl = s3Service.getFullUrl(memberProfileImg.getImgUrl()); + + RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(member); + if(!(representativeBadge.getRepresentativeBadge().name.equals(""))) { + badgeUrl = s3Service.getFullUrl(representativeBadge.getRepresentativeBadge().url); + } + + return SettingInfoResponseDto.builder() + .nickname(member.getNickname()) + .profileImg(profileUrl) + .badge(representativeBadge.getRepresentativeBadge().name) + .badgeImg(badgeUrl) + .commentAlarm(member.isCommentAlarm()) + .likeAlarm(member.isLikeAlarm()) + .build(); + } + + public void deleteFromS3(String urlToDelete) { + if(!(urlToDelete.equals("profile.jpg"))) { + s3Service.delete(urlToDelete); + } + } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index 98be329..1614a45 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -16,90 +16,89 @@ public class Badge extends AuditEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name="badge_id") + @Column(name = "badge_id") private Long memberId; @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(name="member_id") + @JoinColumn(name = "member_id") private Member member; - @Column(name="earlybird_count",columnDefinition = "int default 0" ) + @Column(name = "earlybird_count", columnDefinition = "int default 0") private int earlybirdCount; - @Column(name="ealrybird_is_achieved",columnDefinition = "boolean default false") + @Column(name = "ealrybird_is_achieved", columnDefinition = "boolean default false") private boolean earlybirdIsAchieved; - @Column(name="mentor_count",columnDefinition = "int default 0") + @Column(name = "mentor_count", columnDefinition = "int default 0") private int mentorCount; - @Column(name="mentor_is_achieved",columnDefinition = "boolean default false") + @Column(name = "mentor_is_achieved", columnDefinition = "boolean default false") private boolean mentorIsAchieved; - @Column(name="mentee_count",columnDefinition = "int default 0") + @Column(name = "mentee_count", columnDefinition = "int default 0") private int menteeCount; - @Column(name="mentee_is_achieved",columnDefinition = "boolean default false") + @Column(name = "mentee_is_achieved", columnDefinition = "boolean default false") private boolean menteeIsAchieved; - @Column(name="certification_count",columnDefinition = "int default 0") + @Column(name = "certification_count", columnDefinition = "int default 0") private int certificationCount; - @Column(name="certification_10_is_achieved",columnDefinition = "boolean default false") + @Column(name = "certification_10_is_achieved", columnDefinition = "boolean default false") private boolean certification10IsAchieved; - @Column(name="certification_20_is_achieved",columnDefinition = "boolean default false") + @Column(name = "certification_20_is_achieved", columnDefinition = "boolean default false") private boolean certification20IsAchieved; - @Column(name="certification_50_is_achieved",columnDefinition = "boolean default false") + @Column(name = "certification_50_is_achieved", columnDefinition = "boolean default false") private boolean certification50IsAchieved; - @Column(name="receipt_count",columnDefinition = "int default 0") + @Column(name = "receipt_count", columnDefinition = "int default 0") private int receiptCount; - @Column(name="receipt_3_is_achieved",columnDefinition = "boolean default false") + @Column(name = "receipt_3_is_achieved", columnDefinition = "boolean default false") private boolean receipt3IsAchieved; - @Column(name="receipt_10_is_achieved",columnDefinition = "boolean default false") + @Column(name = "receipt_10_is_achieved", columnDefinition = "boolean default false") private boolean receipt10IsAchieved; - @Column(name="reusable_count",columnDefinition = "int default 0") + @Column(name = "reusable_count", columnDefinition = "int default 0") private int reusableCount; - @Column(name="reusable_3_is_achieved",columnDefinition = "boolean default false") + @Column(name = "reusable_3_is_achieved", columnDefinition = "boolean default false") private boolean reusable3IsAchieved; - @Column(name="reusable_10_is_achieved",columnDefinition = "boolean default false") + @Column(name = "reusable_10_is_achieved", columnDefinition = "boolean default false") private boolean reusable10IsAchieved; - @Column(name="plastic_count",columnDefinition = "int default 0") + @Column(name = "plastic_count", columnDefinition = "int default 0") private int plasticCount; - @Column(name="plastic_3_is_achieved",columnDefinition = "boolean default false") + @Column(name = "plastic_3_is_achieved", columnDefinition = "boolean default false") private boolean plastic3IsAchieved; - @Column(name="plastic_10_is_achieved",columnDefinition = "boolean default false") + @Column(name = "plastic_10_is_achieved", columnDefinition = "boolean default false") private boolean plastic10IsAchieved; - @Column(name="plogging_count",columnDefinition = "int default 0") + @Column(name = "plogging_count", columnDefinition = "int default 0") private int ploggingCount; - @Column(name="plogging_3_is_achieved",columnDefinition = "boolean default false") + @Column(name = "plogging_3_is_achieved", columnDefinition = "boolean default false") private boolean plogging3IsAchieved; - @Column(name="plogging_10_is_achieved",columnDefinition = "boolean default false") + @Column(name = "plogging_10_is_achieved", columnDefinition = "boolean default false") private boolean plogging10IsAchieved; - @Column(name="reform_count",columnDefinition = "int default 0") + @Column(name = "reform_count", columnDefinition = "int default 0") private int reformCount; - @Column(name="reform_3_is_achieved",columnDefinition = "boolean default false") + @Column(name = "reform_3_is_achieved", columnDefinition = "boolean default false") private boolean reform3IsAchieved; - @Column(name="reform_10_is_achieved",columnDefinition = "boolean default false") + @Column(name = "reform_10_is_achieved", columnDefinition = "boolean default false") private boolean reform10IsAchieved; - @Column(name="transport_count",columnDefinition = "int default 0") + @Column(name = "transport_count", columnDefinition = "int default 0") private int transportCount; - @Column(name="transport_3_is_achieved",columnDefinition = "boolean default false") + @Column(name = "transport_3_is_achieved", columnDefinition = "boolean default false") private boolean transport3IsAchieved; - @Column(name="transport_10_is_achieved",columnDefinition = "boolean default false") + @Column(name = "transport_10_is_achieved", columnDefinition = "boolean default false") private boolean transport10IsAchieved; - @Column(name="etc_count",columnDefinition = "int default 0") + @Column(name = "etc_count", columnDefinition = "int default 0") private int etcCount; - @Column(name="etc_3_is_achieved",columnDefinition = "boolean default false") + @Column(name = "etc_3_is_achieved", columnDefinition = "boolean default false") private boolean etc3IsAchieved; - @Column(name="etc_10_is_achieved",columnDefinition = "boolean default false") + @Column(name = "etc_10_is_achieved", columnDefinition = "boolean default false") private boolean etc10IsAchieved; - @Column(name="adventurer_is_achieved",columnDefinition = "boolean default false") + @Column(name = "adventurer_is_achieved", columnDefinition = "boolean default false") private boolean adventurerIsAchieved; - @Column(name="golden_is_achieved",columnDefinition = "boolean default false") + @Column(name = "golden_is_achieved", columnDefinition = "boolean default false") private boolean goldenIsAchieved; - } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java index 6e92549..eaf3ca8 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java @@ -8,6 +8,7 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import org.springframework.context.annotation.Profile; import java.util.ArrayList; import java.util.List; @@ -28,5 +29,7 @@ public class ProfileBadge extends AuditEntity { private Member member; @Enumerated(EnumType.STRING) + @Builder.Default private List profileBadges = new ArrayList<>(); + } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java index ad72c0b..29784eb 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java @@ -26,4 +26,6 @@ public class RepresentativeBadge extends AuditEntity { @Enumerated(EnumType.STRING) private BadgeList representativeBadge; + + } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java b/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java index a286f52..ba60c8f 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java @@ -1,10 +1,12 @@ package com.kimgreen.backend.domain.profile.repository; import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.profile.entity.Badge; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface BadgeRepository extends JpaRepository { + public void deleteByMember(Member member); } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java b/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java index 575c738..49379d8 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java @@ -1,10 +1,12 @@ package com.kimgreen.backend.domain.profile.repository; import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.profile.entity.ProfileBadge; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ProfileBadgeRepository extends JpaRepository { + public void deleteByMember(Member member); } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/repository/RepresentativeBadgeRepository.java b/src/main/java/com/kimgreen/backend/domain/profile/repository/RepresentativeBadgeRepository.java new file mode 100644 index 0000000..ff61e4b --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/repository/RepresentativeBadgeRepository.java @@ -0,0 +1,11 @@ +package com.kimgreen.backend.domain.profile.repository; + +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.profile.entity.ProfileBadge; +import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RepresentativeBadgeRepository extends JpaRepository { + public RepresentativeBadge findByMember(Member member); + public void deleteByMember(Member member); +} From 5feadaee31c3f53a59df1f2eafa037dce5fdcba6 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 19:17:09 +0900 Subject: [PATCH 04/72] [feat] getMemberInfo --- .../member/controller/MemberController.java | 7 +++++++ .../member/dto/Member/MemberInfoResponse.java | 16 ++++++++++++++++ .../domain/member/service/MemberService.java | 12 ++++++++++++ .../com/kimgreen/backend/response/Message.java | 5 ++++- 4 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/member/dto/Member/MemberInfoResponse.java diff --git a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java index 175fac6..e65b37d 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java +++ b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java @@ -59,4 +59,11 @@ public Response changeProfileImg(@RequestPart(value="file") MultipartFile multip public Response getSettingsInfo() { return success(GET_MEMBER_INFO_SETTING_SUCCESS, memberService.getSettingInfo()); } + + @Operation(summary = "사용자 별명 불러오기 불러오기") + @ResponseStatus(OK) + @GetMapping("/profile-name") + public Response getMemberInfo() { + return success(GET_MEMBER_INFO, memberService.getMemberInfo()); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/MemberInfoResponse.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/MemberInfoResponse.java new file mode 100644 index 0000000..5f2c699 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/MemberInfoResponse.java @@ -0,0 +1,16 @@ +package com.kimgreen.backend.domain.member.dto.Member; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class MemberInfoResponse { + private String writerEmail; + private String badge; + private String badgeImg; +} diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java index 9855766..a4a7312 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java @@ -1,6 +1,7 @@ package com.kimgreen.backend.domain.member.service; import com.kimgreen.backend.domain.community.service.S3Service; +import com.kimgreen.backend.domain.member.dto.Member.MemberInfoResponse; import com.kimgreen.backend.domain.member.dto.Member.SettingInfoResponseDto; import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.entity.MemberProfileImg; @@ -120,6 +121,17 @@ public SettingInfoResponseDto getSettingInfo() { .build(); } + public MemberInfoResponse getMemberInfo() { + Member member = getCurrentMember(); + RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(member); + + return MemberInfoResponse.builder() + .writerEmail(member.getEmail()) + .badge(representativeBadge.getRepresentativeBadge().name) + .badgeImg(s3Service.getFullUrl(representativeBadge.getRepresentativeBadge().url)) + .build(); + } + public void deleteFromS3(String urlToDelete) { if(!(urlToDelete.equals("profile.jpg"))) { s3Service.delete(urlToDelete); diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index e73587c..a7eab8e 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -10,5 +10,8 @@ public class Message { public static String SUCCESS_TO_WRITE_POST="인증 게시글 작성 성공했습니다."; - + public static String CHANGE_NICKNAME_SUCCESS="닉네임 변경하기 성공했습니다."; + public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; + public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; + public static String GET_MEMBER_INFO="사용자 별명 불러오기 성공했습니다."; } From 70a13fec79db76c2cbbae8ac831972024a166fc2 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 19:19:17 +0900 Subject: [PATCH 05/72] [fix] rename settingInfoDto variables --- .../domain/member/dto/Member/SettingInfoResponseDto.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java index 49ae2f6..9f1baf6 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java @@ -12,9 +12,9 @@ public class SettingInfoResponseDto { private String nickname; private String profileImg; - private String badge; - private String badgeImg; - private boolean commentAlarm; - private boolean likeAlarm; + private String profileBadge; + private String profileBadgeImg; + private boolean commentAgreement; + private boolean likeAgreement; } From 3624a3d0c120cc91c226ed496a4a2e9ad874fb7c Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 19:23:56 +0900 Subject: [PATCH 06/72] [fix] rename dto variables --- .../backend/domain/member/dto/Auth/SignUpRequestDto.java | 2 +- .../backend/domain/member/service/AuthService.java | 2 +- .../backend/domain/member/service/MemberService.java | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java index ab2fd27..701d123 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java @@ -12,7 +12,7 @@ public class SignUpRequestDto { private String email; private String password; - private String nickname; + private String name; public Member toMemberEntity(String email, String password, String nickname) { return Member.builder() diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java index 5da1fcd..3611d27 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java @@ -50,7 +50,7 @@ public class AuthService { public void signUp(SignUpRequestDto signUpRequestDto) { String email = signUpRequestDto.getEmail(); String password = signUpRequestDto.getPassword(); - String nickname = signUpRequestDto.getNickname(); + String nickname = signUpRequestDto.getName(); validateEmail(email); diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java index a4a7312..6170cf0 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java @@ -114,10 +114,10 @@ public SettingInfoResponseDto getSettingInfo() { return SettingInfoResponseDto.builder() .nickname(member.getNickname()) .profileImg(profileUrl) - .badge(representativeBadge.getRepresentativeBadge().name) - .badgeImg(badgeUrl) - .commentAlarm(member.isCommentAlarm()) - .likeAlarm(member.isLikeAlarm()) + .profileBadge(representativeBadge.getRepresentativeBadge().name) + .profileBadgeImg(badgeUrl) + .commentAgreement(member.isCommentAlarm()) + .likeAgreement(member.isLikeAlarm()) .build(); } From 707142b50b2c822ab7f88fc3f19e6143dd5c8b8e Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 20:37:58 +0900 Subject: [PATCH 07/72] [feat] changeRepresentativeBadge --- .../kimgreen/backend/domain/BadgeList.java | 1 + .../profile/controller/badgeController.java | 26 +++++++++++++++-- .../profile/dto/RepBadgeRequestDto.java | 13 +++++++++ .../profile/entity/RepresentativeBadge.java | 4 +++ .../domain/profile/service/BadgeService.java | 29 +++++++++++++++++++ ...endarService.java => CalendarService.java} | 2 +- ...{badgeService.java => ProfileService.java} | 2 +- .../profile/service/profileService.java | 7 ----- 8 files changed, 73 insertions(+), 11 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/RepBadgeRequestDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java rename src/main/java/com/kimgreen/backend/domain/profile/service/{calendarService.java => CalendarService.java} (78%) rename src/main/java/com/kimgreen/backend/domain/profile/service/{badgeService.java => ProfileService.java} (79%) delete mode 100644 src/main/java/com/kimgreen/backend/domain/profile/service/profileService.java diff --git a/src/main/java/com/kimgreen/backend/domain/BadgeList.java b/src/main/java/com/kimgreen/backend/domain/BadgeList.java index 5e00036..b0ea118 100644 --- a/src/main/java/com/kimgreen/backend/domain/BadgeList.java +++ b/src/main/java/com/kimgreen/backend/domain/BadgeList.java @@ -30,6 +30,7 @@ public enum BadgeList { public int goal; public String url; + private BadgeList(String name, int goal) { this.name = name; this.goal = goal; diff --git a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java index d705bb5..2ed0f47 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java @@ -1,12 +1,34 @@ package com.kimgreen.backend.domain.profile.controller; +import com.kimgreen.backend.domain.member.dto.Auth.SignUpRequestDto; +import com.kimgreen.backend.domain.member.repository.MemberRepository; +import com.kimgreen.backend.domain.profile.dto.RepBadgeRequestDto; +import com.kimgreen.backend.domain.profile.repository.BadgeRepository; +import com.kimgreen.backend.domain.profile.service.BadgeService; +import com.kimgreen.backend.response.Response; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; + +import static com.kimgreen.backend.response.Message.SIGN_UP_SUCCESS; +import static com.kimgreen.backend.response.Response.success; +import static org.springframework.http.HttpStatus.OK; @Tag(name = "badge") @RestController +@AllArgsConstructor @RequestMapping(value="/badge") public class badgeController { + + private final BadgeService badgeService; + + @Operation(summary = "대표뱃지 설정하기") + @ResponseStatus(OK) + @PatchMapping() + public Response changeRepBadge(@RequestBody RepBadgeRequestDto repBadgeRequestDto) { + badgeService.changeRepBadge(repBadgeRequestDto); + return success(SIGN_UP_SUCCESS); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/RepBadgeRequestDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/RepBadgeRequestDto.java new file mode 100644 index 0000000..a499ef6 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/RepBadgeRequestDto.java @@ -0,0 +1,13 @@ +package com.kimgreen.backend.domain.profile.dto; + +import com.kimgreen.backend.domain.BadgeList; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class RepBadgeRequestDto { + private String badgeName; +} diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java index 29784eb..cafcfb5 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java @@ -27,5 +27,9 @@ public class RepresentativeBadge extends AuditEntity { @Enumerated(EnumType.STRING) private BadgeList representativeBadge; + public void changeRepBadge(String badge) { + this.representativeBadge = BadgeList.valueOf(badge); + } + } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java new file mode 100644 index 0000000..7d22a20 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -0,0 +1,29 @@ +package com.kimgreen.backend.domain.profile.service; + +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.profile.dto.RepBadgeRequestDto; +import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import com.kimgreen.backend.domain.profile.repository.BadgeRepository; +import com.kimgreen.backend.domain.profile.repository.ProfileBadgeRepository; +import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@AllArgsConstructor +public class BadgeService { + + private final BadgeRepository badgeRepository; + private final ProfileBadgeRepository profileBadgeRepository; + private final RepresentativeBadgeRepository representativeBadgeRepository; + private final MemberService memberService; + + @Transactional + public void changeRepBadge(RepBadgeRequestDto repBadgeRequestDto) { + Member member = memberService.getCurrentMember(); + RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(member); + representativeBadge.changeRepBadge(repBadgeRequestDto.getBadgeName()); + } +} diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/calendarService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java similarity index 78% rename from src/main/java/com/kimgreen/backend/domain/profile/service/calendarService.java rename to src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java index 2a96f0d..9d1dc34 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/calendarService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java @@ -3,5 +3,5 @@ import org.springframework.stereotype.Service; @Service -public class calendarService { +public class CalendarService { } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/badgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java similarity index 79% rename from src/main/java/com/kimgreen/backend/domain/profile/service/badgeService.java rename to src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java index 5d90a6b..5a8f07c 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/badgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java @@ -3,5 +3,5 @@ import org.springframework.stereotype.Service; @Service -public class badgeService { +public class ProfileService { } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/profileService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/profileService.java deleted file mode 100644 index 5fd98cc..0000000 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/profileService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.kimgreen.backend.domain.profile.service; - -import org.springframework.stereotype.Service; - -@Service -public class profileService { -} From 430419e7c0dccde427c76dbc53b740e47c4bdd06 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 21:11:52 +0900 Subject: [PATCH 08/72] [fix] changeRepresentativeBadge - Exception --- .../JwtAuthenticationEntryPoint.java | 23 ++++++++----------- .../kimgreen/backend/domain/BadgeList.java | 2 +- .../profile/controller/badgeController.java | 4 ++-- .../profile/entity/RepresentativeBadge.java | 9 +++++++- .../backend/exception/BadgeNotFound.java | 4 ++++ .../com/kimgreen/backend/response/Advice.java | 15 ++++++++---- .../kimgreen/backend/response/Message.java | 3 +++ 7 files changed, 38 insertions(+), 22 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/exception/BadgeNotFound.java diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java index 5fb1a19..1503a75 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java @@ -21,27 +21,22 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, - AuthenticationException authException) throws IOException, ServletException { + AuthenticationException authException) throws IOException { String exception = (String)request.getAttribute("exception"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json; charset=UTF-8"); -/* if (EXPIRED.equals(exception)) { //exception이 null인지 확인 - setResponse(response, EXPIRED); - } - if (DENIED.equals(exception)) { - setResponse(response, DENIED); - }*/ - if(exception.equals(EXPIRED)) { setResponse(response,EXPIRED); - } - if(exception.equals(DENIED)) { - setResponse(response,DENIED); - } - - + if(exception!=null) { + if (exception.equals(EXPIRED)) { + setResponse(response, EXPIRED); + } + if (exception.equals(DENIED)) { + setResponse(response, DENIED); + } + } } public void setResponse(HttpServletResponse response,String msg) throws IOException{ diff --git a/src/main/java/com/kimgreen/backend/domain/BadgeList.java b/src/main/java/com/kimgreen/backend/domain/BadgeList.java index b0ea118..250b971 100644 --- a/src/main/java/com/kimgreen/backend/domain/BadgeList.java +++ b/src/main/java/com/kimgreen/backend/domain/BadgeList.java @@ -1,7 +1,7 @@ package com.kimgreen.backend.domain; public enum BadgeList { - BLANK(""), + BLANK("",""), MENTOR("그린 멘토",5,"mentor.png"), MENTEE("그린 멘티",5,"mentee.png"), EARLYBIRD("얼리버드",3,"earlybird.png"), diff --git a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java index 2ed0f47..380d4d1 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java @@ -12,7 +12,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; -import static com.kimgreen.backend.response.Message.SIGN_UP_SUCCESS; +import static com.kimgreen.backend.response.Message.*; import static com.kimgreen.backend.response.Response.success; import static org.springframework.http.HttpStatus.OK; @@ -29,6 +29,6 @@ public class badgeController { @PatchMapping() public Response changeRepBadge(@RequestBody RepBadgeRequestDto repBadgeRequestDto) { badgeService.changeRepBadge(repBadgeRequestDto); - return success(SIGN_UP_SUCCESS); + return success(CHANGE_REPRESENTATIVE_BADGE_SUCCESS); } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java index cafcfb5..a58a430 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java @@ -1,14 +1,19 @@ package com.kimgreen.backend.domain.profile.entity; +import com.fasterxml.jackson.databind.ser.std.EnumSerializer; import com.kimgreen.backend.domain.AuditEntity; import com.kimgreen.backend.domain.BadgeList; import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.exception.BadgeNotFound; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import java.util.Arrays; + + @Getter @NoArgsConstructor @AllArgsConstructor @@ -28,7 +33,9 @@ public class RepresentativeBadge extends AuditEntity { private BadgeList representativeBadge; public void changeRepBadge(String badge) { - this.representativeBadge = BadgeList.valueOf(badge); + if(Arrays.stream(BadgeList.values()).anyMatch(v->v.name().equals(badge))) { + this.representativeBadge = BadgeList.valueOf(badge); + } else throw new BadgeNotFound(); } diff --git a/src/main/java/com/kimgreen/backend/exception/BadgeNotFound.java b/src/main/java/com/kimgreen/backend/exception/BadgeNotFound.java new file mode 100644 index 0000000..6f7d7b6 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/exception/BadgeNotFound.java @@ -0,0 +1,4 @@ +package com.kimgreen.backend.exception; + +public class BadgeNotFound extends RuntimeException{ +} diff --git a/src/main/java/com/kimgreen/backend/response/Advice.java b/src/main/java/com/kimgreen/backend/response/Advice.java index 895fba9..4333c53 100644 --- a/src/main/java/com/kimgreen/backend/response/Advice.java +++ b/src/main/java/com/kimgreen/backend/response/Advice.java @@ -1,10 +1,7 @@ package com.kimgreen.backend.response; -import com.kimgreen.backend.exception.DuplicateEmail; -import com.kimgreen.backend.exception.LogInFailureEmail; -import com.kimgreen.backend.exception.LogInFailurePassword; -import com.kimgreen.backend.exception.RefreshTokenExpired; +import com.kimgreen.backend.exception.*; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @@ -36,6 +33,16 @@ public Response RefreshTokenExpiredResponse() { return Response.failure(HttpStatus.UNAUTHORIZED, "리프레시 토큰이 유효하지 않습니다."); } + @ExceptionHandler(MaxUploadSizeExceeded.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public Response MaxUploadSizeExceededResponse() { + return Response.failure(HttpStatus.INTERNAL_SERVER_ERROR, "파일 업로드 최대 용량을 초과했습니다.: 50MB"); + } + @ExceptionHandler(BadgeNotFound.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Response BadgeNotFoundResponse() { + return Response.failure(HttpStatus.NOT_FOUND,"요청한 뱃지를 찾을 수 없습니다."); + } } diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index a7eab8e..d2f4693 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -14,4 +14,7 @@ public class Message { public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; public static String GET_MEMBER_INFO="사용자 별명 불러오기 성공했습니다."; + public static String CHANGE_REPRESENTATIVE_BADGE_SUCCESS="대표뱃지 설정 성공했습니다."; + + } From 4a849424476391570ebeb2fa7304272b0ab05657 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Fri, 12 Jan 2024 12:23:42 +0900 Subject: [PATCH 09/72] [feat] changeProfileBadge --- .../profile/controller/badgeController.java | 15 ++++--- .../dto/Badge/ProfileBadgeRequestDto.java | 14 ++++++ .../dto/{ => Badge}/RepBadgeRequestDto.java | 2 +- .../domain/profile/entity/ProfileBadge.java | 21 ++++++++- .../repository/ProfileBadgeRepository.java | 1 + .../domain/profile/service/BadgeService.java | 44 ++++++++++++++++++- .../kimgreen/backend/response/Message.java | 1 + 7 files changed, 89 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/ProfileBadgeRequestDto.java rename src/main/java/com/kimgreen/backend/domain/profile/dto/{ => Badge}/RepBadgeRequestDto.java (81%) diff --git a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java index 380d4d1..29b5904 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java @@ -1,15 +1,12 @@ package com.kimgreen.backend.domain.profile.controller; -import com.kimgreen.backend.domain.member.dto.Auth.SignUpRequestDto; -import com.kimgreen.backend.domain.member.repository.MemberRepository; -import com.kimgreen.backend.domain.profile.dto.RepBadgeRequestDto; -import com.kimgreen.backend.domain.profile.repository.BadgeRepository; +import com.kimgreen.backend.domain.profile.dto.Badge.ProfileBadgeRequestDto; +import com.kimgreen.backend.domain.profile.dto.Badge.RepBadgeRequestDto; import com.kimgreen.backend.domain.profile.service.BadgeService; import com.kimgreen.backend.response.Response; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import static com.kimgreen.backend.response.Message.*; @@ -31,4 +28,12 @@ public Response changeRepBadge(@RequestBody RepBadgeRequestDto repBadgeRequestDt badgeService.changeRepBadge(repBadgeRequestDto); return success(CHANGE_REPRESENTATIVE_BADGE_SUCCESS); } + + @Operation(summary = "대표뱃지 설정하기") + @ResponseStatus(OK) + @PatchMapping("/profile") + public Response changeProfileBadges(@RequestBody ProfileBadgeRequestDto profileBadgeRequestDto) { + badgeService.changeProfileBadge(profileBadgeRequestDto); + return success(CHANGE_PROFILE_BADGE_SUCCESS); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/ProfileBadgeRequestDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/ProfileBadgeRequestDto.java new file mode 100644 index 0000000..5134940 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/ProfileBadgeRequestDto.java @@ -0,0 +1,14 @@ +package com.kimgreen.backend.domain.profile.dto.Badge; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class ProfileBadgeRequestDto { + private List badge; +} diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/RepBadgeRequestDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/RepBadgeRequestDto.java similarity index 81% rename from src/main/java/com/kimgreen/backend/domain/profile/dto/RepBadgeRequestDto.java rename to src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/RepBadgeRequestDto.java index a499ef6..350e869 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/dto/RepBadgeRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/RepBadgeRequestDto.java @@ -1,4 +1,4 @@ -package com.kimgreen.backend.domain.profile.dto; +package com.kimgreen.backend.domain.profile.dto.Badge; import com.kimgreen.backend.domain.BadgeList; import lombok.AllArgsConstructor; diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java index eaf3ca8..0261502 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java @@ -3,6 +3,7 @@ import com.kimgreen.backend.domain.AuditEntity; import com.kimgreen.backend.domain.BadgeList; import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.exception.BadgeNotFound; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; @@ -11,6 +12,7 @@ import org.springframework.context.annotation.Profile; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; @Getter @@ -29,7 +31,22 @@ public class ProfileBadge extends AuditEntity { private Member member; @Enumerated(EnumType.STRING) - @Builder.Default - private List profileBadges = new ArrayList<>(); + private BadgeList profileBadge_1; + @Enumerated(EnumType.STRING) + private BadgeList profileBadge_2; + @Enumerated(EnumType.STRING) + private BadgeList profileBadge_3; + @Enumerated(EnumType.STRING) + private BadgeList profileBadge_4; + @Enumerated(EnumType.STRING) + private BadgeList profileBadge_5; + + public void changeProfileBadge(List badgeList) { + this.profileBadge_1 = badgeList.get(0); + this.profileBadge_2 = badgeList.get(1); + this.profileBadge_3 = badgeList.get(2); + this.profileBadge_4 = badgeList.get(3); + this.profileBadge_5 = badgeList.get(4); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java b/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java index 49379d8..8accfa1 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java @@ -9,4 +9,5 @@ @Repository public interface ProfileBadgeRepository extends JpaRepository { public void deleteByMember(Member member); + public ProfileBadge findByMember(Member member); } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java index 7d22a20..e2f36a0 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -1,16 +1,24 @@ package com.kimgreen.backend.domain.profile.service; +import com.kimgreen.backend.domain.BadgeList; import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.service.MemberService; -import com.kimgreen.backend.domain.profile.dto.RepBadgeRequestDto; +import com.kimgreen.backend.domain.profile.dto.Badge.ProfileBadgeRequestDto; +import com.kimgreen.backend.domain.profile.dto.Badge.RepBadgeRequestDto; +import com.kimgreen.backend.domain.profile.entity.ProfileBadge; import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; import com.kimgreen.backend.domain.profile.repository.BadgeRepository; import com.kimgreen.backend.domain.profile.repository.ProfileBadgeRepository; import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; +import com.kimgreen.backend.exception.BadgeNotFound; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + @Service @AllArgsConstructor public class BadgeService { @@ -26,4 +34,38 @@ public void changeRepBadge(RepBadgeRequestDto repBadgeRequestDto) { RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(member); representativeBadge.changeRepBadge(repBadgeRequestDto.getBadgeName()); } + + @Transactional + public void changeProfileBadge(ProfileBadgeRequestDto profileBadgeRequestDto){ + Member member=memberService.getCurrentMember(); + ProfileBadge profileBadge = profileBadgeRepository.findByMember(member); + //뱃지 이름 검증 + List badges = profileBadgeRequestDto.getBadge(); + validateList(badges); + //List -> List + List badgeList = toEnumList(badges); + + profileBadge.changeProfileBadge(badgeList); + } + + + public List toEnumList(List badgeList) { + List returnList = new ArrayList<>(); + for(String badge: badgeList) { + returnList.add(Arrays.stream(BadgeList.values()) + .filter(v->v.name().equals(badge)) + .findAny() + .orElseThrow()); + } + return returnList; + + } + + public void validateList(List badges) { + for(String badge: badges) { + if (!(Arrays.stream(BadgeList.values()).anyMatch(v -> v.name().equals(badge)))) { + throw new BadgeNotFound(); + } + } + } } diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index d2f4693..bd774eb 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -15,6 +15,7 @@ public class Message { public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; public static String GET_MEMBER_INFO="사용자 별명 불러오기 성공했습니다."; public static String CHANGE_REPRESENTATIVE_BADGE_SUCCESS="대표뱃지 설정 성공했습니다."; + public static String CHANGE_PROFILE_BADGE_SUCCESS="프로필뱃지 선택 성공했습니다."; } From 2f6c3669ed621b65c727039614b08b268f9b614f Mon Sep 17 00:00:00 2001 From: gol2580 Date: Fri, 12 Jan 2024 14:16:47 +0900 Subject: [PATCH 10/72] [feat] getCollectedBadge --- .../profile/controller/badgeController.java | 9 ++- .../dto/Badge/CollectedBadgeResponseDto.java | 15 ++++ .../backend/domain/profile/entity/Badge.java | 53 ++++++++++++++ .../profile/repository/BadgeRepository.java | 1 + .../domain/profile/service/BadgeService.java | 71 ++++++++++++++++++- .../kimgreen/backend/response/Message.java | 1 + 6 files changed, 146 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java diff --git a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java index 29b5904..4c052df 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java @@ -29,11 +29,18 @@ public Response changeRepBadge(@RequestBody RepBadgeRequestDto repBadgeRequestDt return success(CHANGE_REPRESENTATIVE_BADGE_SUCCESS); } - @Operation(summary = "대표뱃지 설정하기") + @Operation(summary = "프로필뱃지 설정하기") @ResponseStatus(OK) @PatchMapping("/profile") public Response changeProfileBadges(@RequestBody ProfileBadgeRequestDto profileBadgeRequestDto) { badgeService.changeProfileBadge(profileBadgeRequestDto); return success(CHANGE_PROFILE_BADGE_SUCCESS); } + + @Operation(summary = "획득뱃지 상세정보 불러오기") + @ResponseStatus(OK) + @GetMapping("/collect") + public Response getCollectedBadgeInfo() { + return success(GET_COLLECTED_BADGE_INFO,badgeService.getCollectedBadgeInfo()); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java new file mode 100644 index 0000000..367d552 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java @@ -0,0 +1,15 @@ +package com.kimgreen.backend.domain.profile.dto.Badge; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class CollectedBadgeResponseDto { + private String badge; + private String badgeImg; +} diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index 1614a45..55051b3 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -51,6 +51,9 @@ public class Badge extends AuditEntity { @Column(name = "receipt_3_is_achieved", columnDefinition = "boolean default false") private boolean receipt3IsAchieved; @Column(name = "receipt_10_is_achieved", columnDefinition = "boolean default false") + @Column(name="receipt_3_is_achieved",columnDefinition = "boolean default false") + private boolean receipt3IsAchieved; + @Column(name="receipt_10_is_achieved",columnDefinition = "boolean default false") private boolean receipt10IsAchieved; @Column(name = "reusable_count", columnDefinition = "int default 0") @@ -58,6 +61,9 @@ public class Badge extends AuditEntity { @Column(name = "reusable_3_is_achieved", columnDefinition = "boolean default false") private boolean reusable3IsAchieved; @Column(name = "reusable_10_is_achieved", columnDefinition = "boolean default false") + @Column(name="reusable_3_is_achieved",columnDefinition = "boolean default false") + private boolean reusable3IsAchieved; + @Column(name="reusable_10_is_achieved",columnDefinition = "boolean default false") private boolean reusable10IsAchieved; @Column(name = "plastic_count", columnDefinition = "int default 0") @@ -65,6 +71,9 @@ public class Badge extends AuditEntity { @Column(name = "plastic_3_is_achieved", columnDefinition = "boolean default false") private boolean plastic3IsAchieved; @Column(name = "plastic_10_is_achieved", columnDefinition = "boolean default false") + @Column(name="plastic_3_is_achieved",columnDefinition = "boolean default false") + private boolean plastic3IsAchieved; + @Column(name="plastic_10_is_achieved",columnDefinition = "boolean default false") private boolean plastic10IsAchieved; @Column(name = "plogging_count", columnDefinition = "int default 0") @@ -72,6 +81,9 @@ public class Badge extends AuditEntity { @Column(name = "plogging_3_is_achieved", columnDefinition = "boolean default false") private boolean plogging3IsAchieved; @Column(name = "plogging_10_is_achieved", columnDefinition = "boolean default false") + @Column(name="plogging_3_is_achieved",columnDefinition = "boolean default false") + private boolean plogging3IsAchieved; + @Column(name="plogging_10_is_achieved",columnDefinition = "boolean default false") private boolean plogging10IsAchieved; @Column(name = "reform_count", columnDefinition = "int default 0") @@ -79,6 +91,9 @@ public class Badge extends AuditEntity { @Column(name = "reform_3_is_achieved", columnDefinition = "boolean default false") private boolean reform3IsAchieved; @Column(name = "reform_10_is_achieved", columnDefinition = "boolean default false") + @Column(name="reform_3_is_achieved",columnDefinition = "boolean default false") + private boolean reform3IsAchieved; + @Column(name="reform_10_is_achieved",columnDefinition = "boolean default false") private boolean reform10IsAchieved; @Column(name = "transport_count", columnDefinition = "int default 0") @@ -86,6 +101,9 @@ public class Badge extends AuditEntity { @Column(name = "transport_3_is_achieved", columnDefinition = "boolean default false") private boolean transport3IsAchieved; @Column(name = "transport_10_is_achieved", columnDefinition = "boolean default false") + @Column(name="transport_3_is_achieved",columnDefinition = "boolean default false") + private boolean transport3IsAchieved; + @Column(name="transport_10_is_achieved",columnDefinition = "boolean default false") private boolean transport10IsAchieved; @Column(name = "etc_count", columnDefinition = "int default 0") @@ -93,6 +111,9 @@ public class Badge extends AuditEntity { @Column(name = "etc_3_is_achieved", columnDefinition = "boolean default false") private boolean etc3IsAchieved; @Column(name = "etc_10_is_achieved", columnDefinition = "boolean default false") + @Column(name="etc_3_is_achieved",columnDefinition = "boolean default false") + private boolean etc3IsAchieved; + @Column(name="etc_10_is_achieved",columnDefinition = "boolean default false") private boolean etc10IsAchieved; @@ -101,4 +122,36 @@ public class Badge extends AuditEntity { @Column(name = "golden_is_achieved", columnDefinition = "boolean default false") private boolean goldenIsAchieved; + + String[] columnList = { + "adventurer_is_achieved", + "certification_10_is_achieved", + "certification_20_is_achieved", + "certification_50_is_achieved", + "etc_10_is_achieved", + "etc_20_is_achieved", + "etc_50_is_achieved", + "golden_is_achieved", + "mentee_is_achieved", + "mentor_is_achieved", + "plastic_10_is_achieved", + "plastic_20_is_achieved", + "plastic_50_is_achieved", + "plogging_10_is_achieved", + "plogging_20_is_achieved", + "plogging_50_is_achieved", + "receipt_10_is_achieved", + "receipt_20_is_achieved", + "receipt_50_is_achieved", + "reform_10_is_achieved", + "reform_20_is_achieved", + "reform_50_is_achieved", + "reusable_10_is_achieved", + "reusable_20_is_achieved", + "reusable_50_is_achieved", + "transport_10_is_achieved", + "transport_20_is_achieved", + "transport_50_is_achieved" + }; + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java b/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java index ba60c8f..f189e77 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java @@ -9,4 +9,5 @@ @Repository public interface BadgeRepository extends JpaRepository { public void deleteByMember(Member member); + public Badge findByMember(Member member); } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java index e2f36a0..64d5d0d 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -1,10 +1,13 @@ package com.kimgreen.backend.domain.profile.service; import com.kimgreen.backend.domain.BadgeList; +import com.kimgreen.backend.domain.community.service.S3Service; import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.profile.dto.Badge.CollectedBadgeResponseDto; import com.kimgreen.backend.domain.profile.dto.Badge.ProfileBadgeRequestDto; import com.kimgreen.backend.domain.profile.dto.Badge.RepBadgeRequestDto; +import com.kimgreen.backend.domain.profile.entity.Badge; import com.kimgreen.backend.domain.profile.entity.ProfileBadge; import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; import com.kimgreen.backend.domain.profile.repository.BadgeRepository; @@ -15,9 +18,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; @Service @AllArgsConstructor @@ -27,6 +28,7 @@ public class BadgeService { private final ProfileBadgeRepository profileBadgeRepository; private final RepresentativeBadgeRepository representativeBadgeRepository; private final MemberService memberService; + private final S3Service s3Service; @Transactional public void changeRepBadge(RepBadgeRequestDto repBadgeRequestDto) { @@ -48,6 +50,24 @@ public void changeProfileBadge(ProfileBadgeRequestDto profileBadgeRequestDto){ profileBadge.changeProfileBadge(badgeList); } + public List getCollectedBadgeInfo() { + Member member = memberService.getCurrentMember(); + Badge badge = badgeRepository.findByMember(member); + //를 저장한 map 반환 + Map badgeMap = getMap(badge); + //반환할 dto list 삽입 + List returnDto = new ArrayList<>(); + for(BadgeList b: badgeMap.keySet()) { + returnDto.add( + CollectedBadgeResponseDto.builder() + .badge(b.toString()) + .badgeImg(s3Service.getFullUrl(b.url)) + .build() + ); + } + return returnDto; + } + public List toEnumList(List badgeList) { List returnList = new ArrayList<>(); @@ -68,4 +88,49 @@ public void validateList(List badges) { } } } + + public Map getMap(Badge badge) { + Map map = new HashMap<>(); + + if(badge.isAdventurerIsAchieved()) {map.put(BadgeList.ADVENTURER,true);} + else {map.put(BadgeList.ADVENTURER,false);} + if(badge.isCertification10IsAchieved()){map.put(BadgeList.NORANG,true);} + else {map.put(BadgeList.NORANG,false);} + if(badge.isCertification20IsAchieved()){map.put(BadgeList.YEONDU,true);} + else {map.put(BadgeList.YEONDU,false);} + if(badge.isCertification50IsAchieved()){map.put(BadgeList.GREEN,true);} + else {map.put(BadgeList.GREEN,false);} + if(badge.isEtc3IsAchieved()){map.put(BadgeList.ETC_3,true);} + else {map.put(BadgeList.ETC_3,false);} + if(badge.isEtc10IsAchieved()){map.put(BadgeList.ETC_10,true);} + else {map.put(BadgeList.ETC_10,false);} + if(badge.isGoldenIsAchieved()){map.put(BadgeList.GOLDEN_KIMGREEN,true);} + else {map.put(BadgeList.GOLDEN_KIMGREEN,false);} + if(badge.isMenteeIsAchieved()){map.put(BadgeList.MENTEE,true);} + else {map.put(BadgeList.MENTEE,false);} + if(badge.isMentorIsAchieved()){map.put(BadgeList.MENTOR,true);} + else {map.put(BadgeList.MENTOR,false);} + if(badge.isPlastic3IsAchieved()){map.put(BadgeList.PLASTIC_3,true);} + else {map.put(BadgeList.PLASTIC_3,false);} + if(badge.isPlastic10IsAchieved()){map.put(BadgeList.PLASTIC_10,true);} + else {map.put(BadgeList.PLASTIC_10,false);} + if(badge.isPlogging3IsAchieved()){map.put(BadgeList.PLOGGING_3,true);} + else {map.put(BadgeList.PLOGGING_3,false);} + if(badge.isPlogging10IsAchieved()){map.put(BadgeList.PLOGGING_10,true);} + else {map.put(BadgeList.PLOGGING_10,false);} + if(badge.isReceipt3IsAchieved()){map.put(BadgeList.RECEIPT_3,true);} + else {map.put(BadgeList.RECEIPT_3,false);} + if(badge.isReceipt10IsAchieved()){map.put(BadgeList.RECEIPT_10,true);} + else {map.put(BadgeList.RECEIPT_10,false);} + if(badge.isReform3IsAchieved()){map.put(BadgeList.REFORM_3,true);} + else {map.put(BadgeList.REFORM_3,false);} + if(badge.isReform10IsAchieved()){map.put(BadgeList.REFORM_10,true);} + else {map.put(BadgeList.REFORM_10,false);} + if(badge.isReusable3IsAchieved()){map.put(BadgeList.REUSABLE_3,true);} + else {map.put(BadgeList.REUSABLE_3,false);} + if(badge.isReusable10IsAchieved()){map.put(BadgeList.REFORM_10,true);} + else {map.put(BadgeList.REFORM_10,false);} + return map; + + } } diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index bd774eb..1b50215 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -16,6 +16,7 @@ public class Message { public static String GET_MEMBER_INFO="사용자 별명 불러오기 성공했습니다."; public static String CHANGE_REPRESENTATIVE_BADGE_SUCCESS="대표뱃지 설정 성공했습니다."; public static String CHANGE_PROFILE_BADGE_SUCCESS="프로필뱃지 선택 성공했습니다."; + public static String GET_COLLECTED_BADGE_INFO="획득뱃지 상세정보 불러오기 성공했습니다."; } From 6d03a508069b55fcd2e04927484ba0015fc99191 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Fri, 12 Jan 2024 14:24:05 +0900 Subject: [PATCH 11/72] [fix] fix getCollectedBadge --- .../domain/profile/service/BadgeService.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java index 64d5d0d..2fc7d74 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -58,12 +58,14 @@ public List getCollectedBadgeInfo() { //반환할 dto list 삽입 List returnDto = new ArrayList<>(); for(BadgeList b: badgeMap.keySet()) { - returnDto.add( - CollectedBadgeResponseDto.builder() - .badge(b.toString()) - .badgeImg(s3Service.getFullUrl(b.url)) - .build() - ); + if(badgeMap.get(b)==true) { + returnDto.add( + CollectedBadgeResponseDto.builder() + .badge(b.toString()) + .badgeImg(s3Service.getFullUrl(b.url)) + .build() + ); + } } return returnDto; } From 3cdc1385d9caa1a8274e364229debc0273eb72a8 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Fri, 12 Jan 2024 16:49:34 +0900 Subject: [PATCH 12/72] [feat] get NotCollectedBadge --- .../CustomUserDetailsService.java | 1 + .../kimgreen/backend/domain/BadgeList.java | 55 +++++++------- .../profile/controller/badgeController.java | 6 ++ .../Badge/NotCollectedBadgeResponseDto.java | 17 +++++ .../backend/domain/profile/entity/Badge.java | 2 +- .../domain/profile/service/BadgeService.java | 71 ++++++++++++++++++- .../kimgreen/backend/response/Message.java | 1 + 7 files changed, 126 insertions(+), 27 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/CustomUserDetailsService.java b/src/main/java/com/kimgreen/backend/config/Authentication/CustomUserDetailsService.java index 107e410..c7a6978 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/CustomUserDetailsService.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/CustomUserDetailsService.java @@ -4,6 +4,7 @@ import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.repository.MemberRepository; import lombok.AllArgsConstructor; +import lombok.RequiredArgsConstructor; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; diff --git a/src/main/java/com/kimgreen/backend/domain/BadgeList.java b/src/main/java/com/kimgreen/backend/domain/BadgeList.java index 250b971..eb20de2 100644 --- a/src/main/java/com/kimgreen/backend/domain/BadgeList.java +++ b/src/main/java/com/kimgreen/backend/domain/BadgeList.java @@ -2,50 +2,57 @@ public enum BadgeList { BLANK("",""), - MENTOR("그린 멘토",5,"mentor.png"), - MENTEE("그린 멘티",5,"mentee.png"), - EARLYBIRD("얼리버드",3,"earlybird.png"), - NORANG("김노랑",10,"norang.png"), - YEONDU("김연두",20,"yeondu.png"), - GREEN("김그린",50,"green.png"), - RECEIPT_3("영수증도 전자로","electronic_receipt.png"), - RECEIPT_10("디지털 환경 지킴이",10,"digital_protector.png"), - REUSABLE_3("re: user",3,"re_user.png"), - REUSABLE_10("re: 마스터",10,"re_master.png"), - PLASTIC_3("자연과 친구하기",3,"eco_friend.png"), - PLASTIC_10("자연과 물아일체",10,"eco_one.png"), - PLOGGING_3("자연 속에 만 보 추구",3,"jamanchu.png"), - PLOGGING_10("클린로드의 개척자",10,"clean_road.png"), - REFORM_3("손재주 아티스트",3,"artist.png"), - REFORM_10("친환경 대가",10,"eco_master.png"), - TRANSPORT_3("탄소 헤이터",3,"C_hater.png"), - TRANSPORT_10("지구 세이버",10), - ETC_3("아마추어 기타리스트",3,"amateur_guitarist.png"), - ETC_10("프로 기타리스트",10,"pro_guitarist.png"), - ADVENTURER("환경 모험가","adventurer.png"), + MENTOR("그린 멘토",5,"mentor.png","질문카테고리 댓글 5회 이상"), + MENTEE("그린 멘티",5,"mentee.png","질문 카테고리 글 작성 5회 이상"), + EARLYBIRD("얼리버드",3,"earlybird.png","9시 이전에 인증글 3회이상 작성"), + NORANG("김노랑",10,"norang.png","인증글 10회 이상 작성"), + YEONDU("김연두",20,"yeondu.png","인증글 20회 이상 작성"), + GREEN("김그린",50,"green.png","인증글 50회 이상 작성"), + RECEIPT_3("영수증도 전자로","electronic_receipt.png","전자영수증 발급 인증글 3회 이상"), + RECEIPT_10("디지털 환경 지킴이",10,"digital_protector.png","전자영수증 발급 인증글 10회 이상"), + REUSABLE_3("re: user",3,"re_user.png","리유저블 활동 인증글 3회 이상"), + REUSABLE_10("re: 마스터",10,"re_master.png","리유저블 활동 인증글 10회 이상"), + PLASTIC_3("자연과 친구하기",3,"eco_friend.png","플라스틱 프리 인증글 3회 이상"), + PLASTIC_10("자연과 물아일체",10,"eco_one.png","플라스틱 프리 인증글 10회 이상"), + PLOGGING_3("자연 속에 만 보 추구",3,"jamanchu.png","플로깅 인증글 3회 이상"), + PLOGGING_10("클린로드의 개척자",10,"clean_road.png","플로깅 인증글 10회 이상"), + REFORM_3("손재주 아티스트",3,"artist.png","리폼 인증글 3회 이상"), + REFORM_10("친환경 대가",10,"eco_master.png","리폼 인증글 10회 이상"), + TRANSPORT_3("탄소 헤이터",3,"C_hater.png","대중교통, 자전거 인증글 3회 이상"), + TRANSPORT_10("지구 세이버",10,"earth_saver.png","대중교통, 자전거 인증글 10회 이상"), + ETC_3("아마추어 기타리스트",3,"amateur_guitarist.png","기타 인증글 3회 이상"), + ETC_10("프로 기타리스트",10,"pro_guitarist.png","기타 인증글 10회 이상"), + ADVENTURER("환경 모험가","adventurer.png","각 카테고리별 인증글 1회 이상"), DOCTOR("김그린 박사","doctor.png"), - GOLDEN_KIMGREEN("황금 김그린","golden_kimgreen.png"); + GOLDEN_KIMGREEN("황금 김그린","golden_kimgreen.png","모든 뱃지 획득"); public String name; public int goal; public String url; + public String content; private BadgeList(String name, int goal) { this.name = name; this.goal = goal; } + private BadgeList(String name, String content) { + this.name = name; + this.content = content; + } private BadgeList(String name) { this.name = name; } - private BadgeList(String name, String url) { + private BadgeList(String name, String url,String content) { this.name = name; this.url = url; + this.content = content; } - private BadgeList(String name, int goal, String url) { + private BadgeList(String name, int goal, String url,String content) { this.name = name; this.goal = goal; this.url = url; + this.content = content; } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java index 4c052df..c81949a 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java @@ -43,4 +43,10 @@ public Response changeProfileBadges(@RequestBody ProfileBadgeRequestDto profileB public Response getCollectedBadgeInfo() { return success(GET_COLLECTED_BADGE_INFO,badgeService.getCollectedBadgeInfo()); } + @Operation(summary = "미획득뱃지 상세정보 불러오기") + @ResponseStatus(OK) + @GetMapping("/not-collect") + public Response getNotCollectedBadgeInfo() { + return success(GET_NOT_COLLECTED_BADGE_INFO,badgeService.getNotCollectedBadgeInfo()); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java new file mode 100644 index 0000000..2f71c1c --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java @@ -0,0 +1,17 @@ +package com.kimgreen.backend.domain.profile.dto.Badge; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class NotCollectedBadgeResponseDto { + private String badgeImg; + private String content; + private int completeCount; + private int goal; +} diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index 55051b3..d28e777 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -154,4 +154,4 @@ public class Badge extends AuditEntity { "transport_50_is_achieved" }; -} \ No newline at end of file +} diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java index 2fc7d74..7850fa9 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -5,6 +5,7 @@ import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.service.MemberService; import com.kimgreen.backend.domain.profile.dto.Badge.CollectedBadgeResponseDto; +import com.kimgreen.backend.domain.profile.dto.Badge.NotCollectedBadgeResponseDto; import com.kimgreen.backend.domain.profile.dto.Badge.ProfileBadgeRequestDto; import com.kimgreen.backend.domain.profile.dto.Badge.RepBadgeRequestDto; import com.kimgreen.backend.domain.profile.entity.Badge; @@ -58,10 +59,10 @@ public List getCollectedBadgeInfo() { //반환할 dto list 삽입 List returnDto = new ArrayList<>(); for(BadgeList b: badgeMap.keySet()) { - if(badgeMap.get(b)==true) { + if(badgeMap.get(b)) { returnDto.add( CollectedBadgeResponseDto.builder() - .badge(b.toString()) + .badge(b.name) .badgeImg(s3Service.getFullUrl(b.url)) .build() ); @@ -70,6 +71,41 @@ public List getCollectedBadgeInfo() { return returnDto; } + public List getNotCollectedBadgeInfo() { + Member member = memberService.getCurrentMember(); + Badge badge = badgeRepository.findByMember(member); + //를 저장한 map 반환 + Map map = getMap(badge); + //를 저장한 map 반환 + Map countMap = getCountMap(map,badge); + for(BadgeList b: countMap.keySet()) { + System.out.println(b); + } + //반환할 dto list 삽입 + List returnDto = new ArrayList<>(); + for(BadgeList b: countMap.keySet()) { + System.out.println("inside the for"); + if(b==BadgeList.ADVENTURER || b==BadgeList.GOLDEN_KIMGREEN) { + returnDto.add( + NotCollectedBadgeResponseDto.builder() + .badgeImg(s3Service.getFullUrl(b.url)) + .content(b.content) + .goal(b.goal) + .build()); + } else { + returnDto.add( + NotCollectedBadgeResponseDto.builder() + .badgeImg(s3Service.getFullUrl(b.url)) + .content(b.content) + .completeCount(countMap.get(b)) + .goal(b.goal) + .build()); + } + } + return returnDto; + } + + public List toEnumList(List badgeList) { List returnList = new ArrayList<>(); @@ -135,4 +171,35 @@ public Map getMap(Badge badge) { return map; } + + public Map getCountMap(Map badgeMap,Badge badge) { + System.out.println("in the getCountMap"); + Map map = new HashMap<>(); + for(BadgeList badges: badgeMap.keySet()) { + System.out.println("in the getCountMap for"); + System.out.println("key: "+badges+" value: "+badgeMap.get(badges)); + if(badgeMap.get(badges)==false) { + System.out.println("in the getCountMap for if"); + if(badges.equals(BadgeList.NORANG)) {map.put(BadgeList.NORANG,badge.getCertificationCount());} + if(badges.equals(BadgeList.YEONDU)) {map.put(BadgeList.YEONDU,badge.getCertificationCount());} + if(badges.equals(BadgeList.GREEN)) {map.put(BadgeList.GREEN,badge.getCertificationCount());} + if(badges.equals(BadgeList.ETC_3)) {map.put(BadgeList.ETC_3,badge.getEtcCount());} + if(badges.equals(BadgeList.ETC_10)) {map.put(BadgeList.ETC_10,badge.getEtcCount());} + if(badges.equals(BadgeList.PLASTIC_3)) {map.put(BadgeList.PLASTIC_3,badge.getPlasticCount());} + if(badges.equals(BadgeList.PLASTIC_10)) {map.put(BadgeList.PLASTIC_10,badge.getPlasticCount());} + if(badges.equals(BadgeList.PLOGGING_3)) {map.put(BadgeList.PLOGGING_3,badge.getPloggingCount());} + if(badges.equals(BadgeList.PLOGGING_10)) {map.put(BadgeList.PLOGGING_10,badge.getPloggingCount());} + if(badges.equals(BadgeList.RECEIPT_3)) {map.put(BadgeList.RECEIPT_3,badge.getReceiptCount());} + if(badges.equals(BadgeList.RECEIPT_10)) {map.put(BadgeList.RECEIPT_10,badge.getReceiptCount());} + if(badges.equals(BadgeList.REFORM_3)) {map.put(BadgeList.REFORM_3,badge.getReformCount());} + if(badges.equals(BadgeList.REFORM_10)) {map.put(BadgeList.REFORM_10,badge.getReformCount());} + if(badges.equals(BadgeList.REUSABLE_3)) {map.put(BadgeList.REUSABLE_3,badge.getReusableCount());} + if(badges.equals(BadgeList.REUSABLE_10)) {map.put(BadgeList.REUSABLE_10,badge.getReusableCount());} + if(badges.equals(BadgeList.ADVENTURER)) {map.put(BadgeList.ADVENTURER,0);} + if(badges.equals(BadgeList.GOLDEN_KIMGREEN)) {map.put(BadgeList.GOLDEN_KIMGREEN,0);} + + } + } + return map; + } } diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 1b50215..2d95898 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -17,6 +17,7 @@ public class Message { public static String CHANGE_REPRESENTATIVE_BADGE_SUCCESS="대표뱃지 설정 성공했습니다."; public static String CHANGE_PROFILE_BADGE_SUCCESS="프로필뱃지 선택 성공했습니다."; public static String GET_COLLECTED_BADGE_INFO="획득뱃지 상세정보 불러오기 성공했습니다."; + public static String GET_NOT_COLLECTED_BADGE_INFO="미획득 뱃지 상세정보 불러오기 성공했습니다."; } From b09a8422698c2c9a233399666419d230246750cb Mon Sep 17 00:00:00 2001 From: gol2580 Date: Sat, 13 Jan 2024 13:43:16 +0900 Subject: [PATCH 13/72] [fix] get Badges : sort, update --- .../config/Authentication/JwtProvider.java | 2 +- .../kimgreen/backend/domain/BadgeList.java | 59 ++++++++-------- .../community/service/CommentService.java | 8 +++ .../dto/Badge/CollectedBadgeResponseDto.java | 4 ++ .../Badge/NotCollectedBadgeResponseDto.java | 4 ++ .../backend/domain/profile/entity/Badge.java | 16 ++++- .../domain/profile/service/BadgeService.java | 68 +++++++++++++------ 7 files changed, 108 insertions(+), 53 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtProvider.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtProvider.java index bf0ef65..160cca1 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtProvider.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtProvider.java @@ -29,7 +29,7 @@ public class JwtProvider { private Key secretKey; @Value("${jwt.secret-key}") String key; - private static final long EXPIRE_TIME=1000*60*2*30; //1분 + private static final long EXPIRE_TIME=1000*60*2*30*60; //1분 private static final long REFRESH_EXPIRE_TIME = 10*60*60*24*7; //7일 private static final String SUCCESS = "success"; private static final String EXPIRED = "expired"; diff --git a/src/main/java/com/kimgreen/backend/domain/BadgeList.java b/src/main/java/com/kimgreen/backend/domain/BadgeList.java index eb20de2..66c7b0c 100644 --- a/src/main/java/com/kimgreen/backend/domain/BadgeList.java +++ b/src/main/java/com/kimgreen/backend/domain/BadgeList.java @@ -1,54 +1,55 @@ package com.kimgreen.backend.domain; public enum BadgeList { - BLANK("",""), - MENTOR("그린 멘토",5,"mentor.png","질문카테고리 댓글 5회 이상"), - MENTEE("그린 멘티",5,"mentee.png","질문 카테고리 글 작성 5회 이상"), - EARLYBIRD("얼리버드",3,"earlybird.png","9시 이전에 인증글 3회이상 작성"), - NORANG("김노랑",10,"norang.png","인증글 10회 이상 작성"), - YEONDU("김연두",20,"yeondu.png","인증글 20회 이상 작성"), - GREEN("김그린",50,"green.png","인증글 50회 이상 작성"), - RECEIPT_3("영수증도 전자로","electronic_receipt.png","전자영수증 발급 인증글 3회 이상"), - RECEIPT_10("디지털 환경 지킴이",10,"digital_protector.png","전자영수증 발급 인증글 10회 이상"), - REUSABLE_3("re: user",3,"re_user.png","리유저블 활동 인증글 3회 이상"), - REUSABLE_10("re: 마스터",10,"re_master.png","리유저블 활동 인증글 10회 이상"), - PLASTIC_3("자연과 친구하기",3,"eco_friend.png","플라스틱 프리 인증글 3회 이상"), - PLASTIC_10("자연과 물아일체",10,"eco_one.png","플라스틱 프리 인증글 10회 이상"), - PLOGGING_3("자연 속에 만 보 추구",3,"jamanchu.png","플로깅 인증글 3회 이상"), - PLOGGING_10("클린로드의 개척자",10,"clean_road.png","플로깅 인증글 10회 이상"), - REFORM_3("손재주 아티스트",3,"artist.png","리폼 인증글 3회 이상"), - REFORM_10("친환경 대가",10,"eco_master.png","리폼 인증글 10회 이상"), - TRANSPORT_3("탄소 헤이터",3,"C_hater.png","대중교통, 자전거 인증글 3회 이상"), - TRANSPORT_10("지구 세이버",10,"earth_saver.png","대중교통, 자전거 인증글 10회 이상"), - ETC_3("아마추어 기타리스트",3,"amateur_guitarist.png","기타 인증글 3회 이상"), - ETC_10("프로 기타리스트",10,"pro_guitarist.png","기타 인증글 10회 이상"), - ADVENTURER("환경 모험가","adventurer.png","각 카테고리별 인증글 1회 이상"), - DOCTOR("김그린 박사","doctor.png"), - GOLDEN_KIMGREEN("황금 김그린","golden_kimgreen.png","모든 뱃지 획득"); + BLANK("","",1), + MENTOR("그린 멘토",5,"mentor.png","질문카테고리 댓글 5회 이상",2), + MENTEE("그린 멘티",5,"mentee.png","질문 카테고리 글 작성 5회 이상",3), + EARLYBIRD("얼리버드",3,"earlybird.png","9시 이전에 인증글 3회이상 작성",4), + NORANG("김노랑",10,"norang.png","인증글 10회 이상 작성",5), + YEONDU("김연두",20,"yeondu.png","인증글 20회 이상 작성",6), + GREEN("김그린",50,"green.png","인증글 50회 이상 작성",7), + RECEIPT_3("영수증도 전자로","electronic_receipt.png","전자영수증 발급 인증글 3회 이상",8), + RECEIPT_10("디지털 환경 지킴이",10,"digital_protector.png","전자영수증 발급 인증글 10회 이상",9), + REUSABLE_3("re: user",3,"re_user.png","리유저블 활동 인증글 3회 이상",10), + REUSABLE_10("re: 마스터",10,"re_master.png","리유저블 활동 인증글 10회 이상",11), + PLASTIC_3("자연과 친구하기",3,"eco_friend.png","플라스틱 프리 인증글 3회 이상",12), + PLASTIC_10("자연과 물아일체",10,"eco_one.png","플라스틱 프리 인증글 10회 이상",13), + PLOGGING_3("자연 속에 만 보 추구",3,"jamanchu.png","플로깅 인증글 3회 이상",14), + PLOGGING_10("클린로드의 개척자",10,"clean_road.png","플로깅 인증글 10회 이상",15), + REFORM_3("손재주 아티스트",3,"artist.png","리폼 인증글 3회 이상",16), + REFORM_10("친환경 대가",10,"eco_master.png","리폼 인증글 10회 이상",17), + TRANSPORT_3("탄소 헤이터",3,"C_hater.png","대중교통, 자전거 인증글 3회 이상",18), + TRANSPORT_10("지구 세이버",10,"earth_saver.png","대중교통, 자전거 인증글 10회 이상",19), + ETC_3("아마추어 기타리스트",3,"amateur_guitarist.png","기타 인증글 3회 이상",20), + ETC_10("프로 기타리스트",10,"pro_guitarist.png","기타 인증글 10회 이상",21), + ADVENTURER("환경 모험가","adventurer.png","각 카테고리별 인증글 1회 이상",22), + DOCTOR("김그린 박사","doctor.png",23), + GOLDEN_KIMGREEN("황금 김그린","golden_kimgreen.png","모든 뱃지 획득",24); public String name; public int goal; public String url; public String content; + public int number; - private BadgeList(String name, int goal) { + private BadgeList(String name, int goal,int number) { this.name = name; this.goal = goal; } - private BadgeList(String name, String content) { + private BadgeList(String name, String content,int number) { this.name = name; this.content = content; } - private BadgeList(String name) { + private BadgeList(String name,int number) { this.name = name; } - private BadgeList(String name, String url,String content) { + private BadgeList(String name, String url,String content, int number) { this.name = name; this.url = url; this.content = content; } - private BadgeList(String name, int goal, String url,String content) { + private BadgeList(String name, int goal, String url,String content, int number) { this.name = name; this.goal = goal; this.url = url; diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java b/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java index 3bc6473..433301a 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java @@ -1,7 +1,15 @@ package com.kimgreen.backend.domain.community.service; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.member.service.MemberService; +import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @Service +@AllArgsConstructor public class CommentService { + private final MemberService memberService; + private final PostRepository postRepository; + + } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java index 367d552..1e33a47 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java @@ -5,6 +5,8 @@ import lombok.Getter; import lombok.NoArgsConstructor; +import java.util.List; + @Getter @AllArgsConstructor @NoArgsConstructor @@ -12,4 +14,6 @@ public class CollectedBadgeResponseDto { private String badge; private String badgeImg; + } + diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java index 2f71c1c..6df3025 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java @@ -5,6 +5,8 @@ import lombok.Getter; import lombok.NoArgsConstructor; +import java.util.List; + @Getter @AllArgsConstructor @NoArgsConstructor @@ -14,4 +16,6 @@ public class NotCollectedBadgeResponseDto { private String content; private int completeCount; private int goal; + + } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index d28e777..1c68979 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -23,12 +23,13 @@ public class Badge extends AuditEntity { @JoinColumn(name = "member_id") private Member member; - @Column(name = "earlybird_count", columnDefinition = "int default 0") + @Column(name="earlybird_count",columnDefinition = "int default 0" ) private int earlybirdCount; - @Column(name = "ealrybird_is_achieved", columnDefinition = "boolean default false") + @Column(name="ealrybird_is_achieved",columnDefinition = "boolean default false") private boolean earlybirdIsAchieved; - @Column(name = "mentor_count", columnDefinition = "int default 0") + @Column(name="mentor_count",columnDefinition = "int default 0") + private int mentorCount; @Column(name = "mentor_is_achieved", columnDefinition = "boolean default false") private boolean mentorIsAchieved; @@ -123,6 +124,7 @@ public class Badge extends AuditEntity { @Column(name = "golden_is_achieved", columnDefinition = "boolean default false") private boolean goldenIsAchieved; + String[] columnList = { "adventurer_is_achieved", "certification_10_is_achieved", @@ -154,4 +156,12 @@ public class Badge extends AuditEntity { "transport_50_is_achieved" }; + public void updateGoldenAchieved() { + if(!this.isGoldenIsAchieved()) {this.goldenIsAchieved = true;} + } + public void updateGoldenNotAchieved() { + if(this.isGoldenIsAchieved()) {this.goldenIsAchieved=false;} + } + public void updateAdventurerAchieved() {if(!this.isAdventurerIsAchieved()) {this.adventurerIsAchieved = true;}} + public void updateAdventurerNotAchieved() {if(this.isAdventurerIsAchieved()) {this.adventurerIsAchieved=false;}} } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java index 7850fa9..a4e604e 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -54,6 +54,7 @@ public void changeProfileBadge(ProfileBadgeRequestDto profileBadgeRequestDto){ public List getCollectedBadgeInfo() { Member member = memberService.getCurrentMember(); Badge badge = badgeRepository.findByMember(member); + updateBadeInfos(badge); //를 저장한 map 반환 Map badgeMap = getMap(badge); //반환할 dto list 삽입 @@ -84,13 +85,12 @@ public List getNotCollectedBadgeInfo() { //반환할 dto list 삽입 List returnDto = new ArrayList<>(); for(BadgeList b: countMap.keySet()) { - System.out.println("inside the for"); if(b==BadgeList.ADVENTURER || b==BadgeList.GOLDEN_KIMGREEN) { returnDto.add( NotCollectedBadgeResponseDto.builder() .badgeImg(s3Service.getFullUrl(b.url)) .content(b.content) - .goal(b.goal) + .goal(-1) .build()); } else { returnDto.add( @@ -105,6 +105,25 @@ public List getNotCollectedBadgeInfo() { return returnDto; } + @Transactional + public void updateBadeInfos(Badge badge) { + if(badge.isEarlybirdIsAchieved()&&badge.isReform10IsAchieved()&&badge.isReusable10IsAchieved() + && badge.isAdventurerIsAchieved() && badge.isReceipt10IsAchieved() && badge.isPlastic10IsAchieved() + && badge.isTransport10IsAchieved() && badge.isPlogging10IsAchieved() && badge.isEtc10IsAchieved() + && badge.isMentorIsAchieved() && badge.isMenteeIsAchieved() && badge.isCertification50IsAchieved()) { + badge.updateGoldenAchieved(); + } else { + badge.updateGoldenNotAchieved(); + } + + if(badge.getEtcCount()>=1 && badge.getReformCount()>=1 && badge.getReceiptCount()>=1 && badge.getReusableCount()>=1 + && badge.getPlasticCount()>=1 && badge.getPloggingCount()>=1 && badge.getTransportCount()>=1) { + badge.updateAdventurerAchieved(); + } else { + badge.updateAdventurerNotAchieved(); + } + } + public List toEnumList(List badgeList) { @@ -128,22 +147,14 @@ public void validateList(List badges) { } public Map getMap(Badge badge) { - Map map = new HashMap<>(); + Map map = new LinkedHashMap<>(); - if(badge.isAdventurerIsAchieved()) {map.put(BadgeList.ADVENTURER,true);} - else {map.put(BadgeList.ADVENTURER,false);} if(badge.isCertification10IsAchieved()){map.put(BadgeList.NORANG,true);} else {map.put(BadgeList.NORANG,false);} if(badge.isCertification20IsAchieved()){map.put(BadgeList.YEONDU,true);} else {map.put(BadgeList.YEONDU,false);} if(badge.isCertification50IsAchieved()){map.put(BadgeList.GREEN,true);} else {map.put(BadgeList.GREEN,false);} - if(badge.isEtc3IsAchieved()){map.put(BadgeList.ETC_3,true);} - else {map.put(BadgeList.ETC_3,false);} - if(badge.isEtc10IsAchieved()){map.put(BadgeList.ETC_10,true);} - else {map.put(BadgeList.ETC_10,false);} - if(badge.isGoldenIsAchieved()){map.put(BadgeList.GOLDEN_KIMGREEN,true);} - else {map.put(BadgeList.GOLDEN_KIMGREEN,false);} if(badge.isMenteeIsAchieved()){map.put(BadgeList.MENTEE,true);} else {map.put(BadgeList.MENTEE,false);} if(badge.isMentorIsAchieved()){map.put(BadgeList.MENTOR,true);} @@ -168,23 +179,35 @@ public Map getMap(Badge badge) { else {map.put(BadgeList.REUSABLE_3,false);} if(badge.isReusable10IsAchieved()){map.put(BadgeList.REFORM_10,true);} else {map.put(BadgeList.REFORM_10,false);} + if(badge.isTransport3IsAchieved()){map.put(BadgeList.TRANSPORT_3,true);} + else {map.put(BadgeList.TRANSPORT_3,false);} + if(badge.isTransport10IsAchieved()){map.put(BadgeList.TRANSPORT_10,true);} + else {map.put(BadgeList.TRANSPORT_10,false);} + if(badge.isEtc3IsAchieved()){map.put(BadgeList.ETC_3,true);} + else {map.put(BadgeList.ETC_3,false);} + if(badge.isEtc10IsAchieved()){map.put(BadgeList.ETC_10,true);} + else {map.put(BadgeList.ETC_10,false);} + if(badge.isEarlybirdIsAchieved()){map.put(BadgeList.EARLYBIRD,true);} + else {map.put(BadgeList.EARLYBIRD,false);} + if(badge.isAdventurerIsAchieved()) {map.put(BadgeList.ADVENTURER,true);} + else {map.put(BadgeList.ADVENTURER,false);} + if(badge.isGoldenIsAchieved()){map.put(BadgeList.GOLDEN_KIMGREEN,true);} + else {map.put(BadgeList.GOLDEN_KIMGREEN,false);} return map; } public Map getCountMap(Map badgeMap,Badge badge) { - System.out.println("in the getCountMap"); - Map map = new HashMap<>(); + Map map = new LinkedHashMap<>(); for(BadgeList badges: badgeMap.keySet()) { - System.out.println("in the getCountMap for"); - System.out.println("key: "+badges+" value: "+badgeMap.get(badges)); + System.out.println("in for: "+badges); if(badgeMap.get(badges)==false) { - System.out.println("in the getCountMap for if"); + System.out.println("in false: "+badges); if(badges.equals(BadgeList.NORANG)) {map.put(BadgeList.NORANG,badge.getCertificationCount());} if(badges.equals(BadgeList.YEONDU)) {map.put(BadgeList.YEONDU,badge.getCertificationCount());} if(badges.equals(BadgeList.GREEN)) {map.put(BadgeList.GREEN,badge.getCertificationCount());} - if(badges.equals(BadgeList.ETC_3)) {map.put(BadgeList.ETC_3,badge.getEtcCount());} - if(badges.equals(BadgeList.ETC_10)) {map.put(BadgeList.ETC_10,badge.getEtcCount());} + if(badges.equals(BadgeList.MENTEE)) {map.put(BadgeList.MENTEE,badge.getMenteeCount());} + if(badges.equals(BadgeList.MENTOR)) {map.put(BadgeList.MENTOR,badge.getMentorCount());} if(badges.equals(BadgeList.PLASTIC_3)) {map.put(BadgeList.PLASTIC_3,badge.getPlasticCount());} if(badges.equals(BadgeList.PLASTIC_10)) {map.put(BadgeList.PLASTIC_10,badge.getPlasticCount());} if(badges.equals(BadgeList.PLOGGING_3)) {map.put(BadgeList.PLOGGING_3,badge.getPloggingCount());} @@ -195,8 +218,13 @@ public Map getCountMap(Map badgeMap,Badge if(badges.equals(BadgeList.REFORM_10)) {map.put(BadgeList.REFORM_10,badge.getReformCount());} if(badges.equals(BadgeList.REUSABLE_3)) {map.put(BadgeList.REUSABLE_3,badge.getReusableCount());} if(badges.equals(BadgeList.REUSABLE_10)) {map.put(BadgeList.REUSABLE_10,badge.getReusableCount());} - if(badges.equals(BadgeList.ADVENTURER)) {map.put(BadgeList.ADVENTURER,0);} - if(badges.equals(BadgeList.GOLDEN_KIMGREEN)) {map.put(BadgeList.GOLDEN_KIMGREEN,0);} + if(badges.equals(BadgeList.TRANSPORT_3)) {map.put(BadgeList.TRANSPORT_3,badge.getTransportCount());} + if(badges.equals(BadgeList.TRANSPORT_10)) {map.put(BadgeList.TRANSPORT_10,badge.getTransportCount());} + if(badges.equals(BadgeList.ETC_3)) {map.put(BadgeList.ETC_3,badge.getEtcCount());} + if(badges.equals(BadgeList.ETC_10)) {map.put(BadgeList.ETC_10,badge.getEtcCount());} + if(badges.equals(BadgeList.EARLYBIRD)) {map.put(BadgeList.EARLYBIRD,badge.getEarlybirdCount());} + if(badges.equals(BadgeList.ADVENTURER)) {map.put(BadgeList.ADVENTURER,-1);} + if(badges.equals(BadgeList.GOLDEN_KIMGREEN)) {map.put(BadgeList.GOLDEN_KIMGREEN,-1);} } } From 8a874c8d8146e1cfb768a0f1e2fb56f687bb442b Mon Sep 17 00:00:00 2001 From: gol2580 Date: Mon, 15 Jan 2024 11:09:46 +0900 Subject: [PATCH 14/72] [fix] change DB to RDS, delete test sout --- .../backend/domain/profile/service/BadgeService.java | 5 ----- src/main/resources/application.yml | 6 +++--- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java index a4e604e..2871c4e 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -79,9 +79,6 @@ public List getNotCollectedBadgeInfo() { Map map = getMap(badge); //를 저장한 map 반환 Map countMap = getCountMap(map,badge); - for(BadgeList b: countMap.keySet()) { - System.out.println(b); - } //반환할 dto list 삽입 List returnDto = new ArrayList<>(); for(BadgeList b: countMap.keySet()) { @@ -200,9 +197,7 @@ public Map getMap(Badge badge) { public Map getCountMap(Map badgeMap,Badge badge) { Map map = new LinkedHashMap<>(); for(BadgeList badges: badgeMap.keySet()) { - System.out.println("in for: "+badges); if(badgeMap.get(badges)==false) { - System.out.println("in false: "+badges); if(badges.equals(BadgeList.NORANG)) {map.put(BadgeList.NORANG,badge.getCertificationCount());} if(badges.equals(BadgeList.YEONDU)) {map.put(BadgeList.YEONDU,badge.getCertificationCount());} if(badges.equals(BadgeList.GREEN)) {map.put(BadgeList.GREEN,badge.getCertificationCount());} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index a762b34..906dcdc 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -2,9 +2,9 @@ spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver - url: ${DATASOURCE_URL} - username: ${DATASOURCE_USERNAME} - password: ${DATASOURCE_PASSWORD} + url: ${DATASOURCE_URL_RDS} + username: ${DATASOURCE_USERNAME_RDS} + password: ${DATASOURCE_PASSWORD_RDS} jpa: show-sql: true From 1b75217e4d98571baf18cd15f9e21b98805c6d74 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Mon, 15 Jan 2024 22:04:20 +0900 Subject: [PATCH 15/72] [feat] Notification --- .gitignore | 3 +- build.gradle | 4 + .../member/dto/Auth/LogInRequestDto.java | 1 + .../domain/member/service/AuthService.java | 6 +- .../controller/NotificationController.java | 29 ++++ .../dto/NotificationResponseDto.java | 26 +++ .../domain/notification/entity/FCMToken.java | 27 ++++ .../notification/entity/Notification.java | 28 ++++ .../repository/FCMTokenRepository.java | 9 ++ .../repository/NotificationRepository.java | 11 ++ .../notification/service/FCMService.java | 150 ++++++++++++++++++ .../service/NotificationService.java | 56 +++++++ .../exception/ConvertingJSONException.java | 4 + .../com/kimgreen/backend/response/Advice.java | 5 + .../kimgreen/backend/response/Message.java | 1 + src/main/resources/application.yml | 8 + 16 files changed, 366 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/notification/controller/NotificationController.java create mode 100644 src/main/java/com/kimgreen/backend/domain/notification/dto/NotificationResponseDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/notification/entity/FCMToken.java create mode 100644 src/main/java/com/kimgreen/backend/domain/notification/entity/Notification.java create mode 100644 src/main/java/com/kimgreen/backend/domain/notification/repository/FCMTokenRepository.java create mode 100644 src/main/java/com/kimgreen/backend/domain/notification/repository/NotificationRepository.java create mode 100644 src/main/java/com/kimgreen/backend/domain/notification/service/FCMService.java create mode 100644 src/main/java/com/kimgreen/backend/domain/notification/service/NotificationService.java create mode 100644 src/main/java/com/kimgreen/backend/exception/ConvertingJSONException.java diff --git a/.gitignore b/.gitignore index d3d34e2..93afc22 100644 --- a/.gitignore +++ b/.gitignore @@ -36,4 +36,5 @@ out/ ### VS Code ### .vscode/ -/src/main/resources/security.properties \ No newline at end of file +/src/main/resources/security.properties +/src/main/resources/kimgreen-f33e5-firebase-adminsdk-63srz-6817b2eec4.json \ No newline at end of file diff --git a/build.gradle b/build.gradle index 347bcbd..399fbc4 100644 --- a/build.gradle +++ b/build.gradle @@ -46,6 +46,10 @@ dependencies { //S3 implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE' + //FCM : push alarm + implementation group: 'com.google.firebase', name: 'firebase-admin', version: '6.8.1' + //implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.2.2' + } tasks.named('test') { diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/LogInRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/LogInRequestDto.java index 9e11f36..c76d971 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/LogInRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/LogInRequestDto.java @@ -10,4 +10,5 @@ public class LogInRequestDto { private String email; private String password; + private String fcmToken; } diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java index 3611d27..6e3d2ff 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java @@ -2,6 +2,7 @@ import com.kimgreen.backend.config.Authentication.JwtProvider; import com.kimgreen.backend.domain.BadgeList; +import com.kimgreen.backend.domain.notification.service.FCMService; import com.kimgreen.backend.domain.member.dto.Auth.ChangePasswordDto; import com.kimgreen.backend.domain.member.dto.Auth.LogInRequestDto; import com.kimgreen.backend.domain.member.dto.Auth.SignUpRequestDto; @@ -46,6 +47,7 @@ public class AuthService { private final MemberService memberService; private static final String SUCCESS = "success"; private static final String EXPIRED = "expired"; + private final FCMService FCMService; public void signUp(SignUpRequestDto signUpRequestDto) { String email = signUpRequestDto.getEmail(); @@ -80,6 +82,8 @@ public TokenDto logIn(LogInRequestDto dto) { .build(); // refresh token 저장 saveRefreshToken(email, generatedRefreshToken); + // FCM token 저장 + FCMService.saveToken(member,dto.getFcmToken()); return TokenDto.builder() @@ -97,7 +101,7 @@ public TokenDto tokenReissue(TokenDto tokenDto) { String email = authentication.getName(); // refresh token 검증 - if (StringUtils.hasText(refreshToken) && jwtProvider.validateToken(refreshToken) == SUCCESS) { + if (StringUtils.hasText(refreshToken) && jwtProvider.validateToken(refreshToken).equals(SUCCESS)) { System.out.println("getting new access token"); // access token 재발급 String newAccessToken = jwtProvider.generateAccessToken(authentication); diff --git a/src/main/java/com/kimgreen/backend/domain/notification/controller/NotificationController.java b/src/main/java/com/kimgreen/backend/domain/notification/controller/NotificationController.java new file mode 100644 index 0000000..979c890 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/notification/controller/NotificationController.java @@ -0,0 +1,29 @@ +package com.kimgreen.backend.domain.notification.controller; + +import com.kimgreen.backend.domain.notification.service.NotificationService; +import com.kimgreen.backend.response.Response; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; +import org.springdoc.core.annotations.ParameterObject; +import org.springframework.data.domain.Pageable; +import org.springframework.web.bind.annotation.*; + +import static com.kimgreen.backend.response.Message.*; +import static org.springframework.http.HttpStatus.OK; + +@Tag(name = "notification") +@RestController +@AllArgsConstructor +@RequestMapping(value="/notification") +public class NotificationController { + + private final NotificationService notificationService; + + @Operation(summary = "푸쉬알림 내역 보기") + @ResponseStatus(OK) + @GetMapping() + public Response getNotification(@ParameterObject Pageable pageable) { + return Response.success(SUCCESS_GET_NOTIFICATION,notificationService.getNotifications(pageable)); + } +} diff --git a/src/main/java/com/kimgreen/backend/domain/notification/dto/NotificationResponseDto.java b/src/main/java/com/kimgreen/backend/domain/notification/dto/NotificationResponseDto.java new file mode 100644 index 0000000..f6da5a2 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/notification/dto/NotificationResponseDto.java @@ -0,0 +1,26 @@ +package com.kimgreen.backend.domain.notification.dto; + +import com.kimgreen.backend.domain.notification.entity.Notification; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +@Builder +@AllArgsConstructor +@Getter +public class NotificationResponseDto { + private Long postId; + private String createdAt; + private String content; + + public static NotificationResponseDto getDto(Notification notification) { + return NotificationResponseDto.builder() + .content(notification.getContent()) + .postId(notification.getPostId()) + .createdAt(notification.getCreatedAt()) + .build(); + } +} diff --git a/src/main/java/com/kimgreen/backend/domain/notification/entity/FCMToken.java b/src/main/java/com/kimgreen/backend/domain/notification/entity/FCMToken.java new file mode 100644 index 0000000..d72d020 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/notification/entity/FCMToken.java @@ -0,0 +1,27 @@ +package com.kimgreen.backend.domain.notification.entity; + +import com.kimgreen.backend.domain.AuditEntity; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; + +@Entity +@Builder +@Getter +public class FCMToken extends AuditEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="fcm_token_id") + private Long fcmTokenId; + + @Column(name="receiver_id") + private String receiverId; + + @Column + private String fcmToken; + + public void updateToken(String token) { + this.fcmToken = token; + } + +} diff --git a/src/main/java/com/kimgreen/backend/domain/notification/entity/Notification.java b/src/main/java/com/kimgreen/backend/domain/notification/entity/Notification.java new file mode 100644 index 0000000..f79c9f7 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/notification/entity/Notification.java @@ -0,0 +1,28 @@ +package com.kimgreen.backend.domain.notification.entity; + +import com.kimgreen.backend.domain.AuditEntity; +import com.kimgreen.backend.domain.community.entity.Comment; +import com.kimgreen.backend.domain.member.entity.Member; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; + +@Entity +@Builder +@Getter +public class Notification extends AuditEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="fcm_token_id") + private Long fcmTokenId; + + @OneToOne + @JoinColumn(name="member_id") + private Member member; + + @Column + private String content; + + @Column(name="post_id") + private Long postId; +} diff --git a/src/main/java/com/kimgreen/backend/domain/notification/repository/FCMTokenRepository.java b/src/main/java/com/kimgreen/backend/domain/notification/repository/FCMTokenRepository.java new file mode 100644 index 0000000..cbf20c0 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/notification/repository/FCMTokenRepository.java @@ -0,0 +1,9 @@ +package com.kimgreen.backend.domain.notification.repository; + +import com.kimgreen.backend.domain.notification.entity.FCMToken; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FCMTokenRepository extends JpaRepository { + public FCMToken findByReceiverId(String email); + public boolean existsByReceiverId(String email); +} diff --git a/src/main/java/com/kimgreen/backend/domain/notification/repository/NotificationRepository.java b/src/main/java/com/kimgreen/backend/domain/notification/repository/NotificationRepository.java new file mode 100644 index 0000000..3c2fd5f --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/notification/repository/NotificationRepository.java @@ -0,0 +1,11 @@ +package com.kimgreen.backend.domain.notification.repository; + +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.notification.entity.Notification; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface NotificationRepository extends JpaRepository { + Page findAllByMember(Member member, Pageable pageable); +} diff --git a/src/main/java/com/kimgreen/backend/domain/notification/service/FCMService.java b/src/main/java/com/kimgreen/backend/domain/notification/service/FCMService.java new file mode 100644 index 0000000..d31a67a --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/notification/service/FCMService.java @@ -0,0 +1,150 @@ +package com.kimgreen.backend.domain.notification.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.firebase.FirebaseApp; +import com.google.firebase.FirebaseOptions; +import com.google.firebase.messaging.FirebaseMessaging; +import com.google.firebase.messaging.Message; +import com.google.firebase.messaging.Notification; +import com.kimgreen.backend.domain.notification.entity.FCMToken; +import com.kimgreen.backend.domain.notification.repository.FCMTokenRepository; +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.repository.MemberRepository; +import jakarta.annotation.PostConstruct; +import lombok.AllArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ClassPathResource; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.concurrent.ExecutionException; + +@Service +@AllArgsConstructor +public class FCMService { + @Value("${fcm.key.path}") + private String FCM_PRIVATE_KEY_PATH; + + // 권한 설정 + @Value("${fcm.key.scope}") + private String fireBaseScope; + + @Value(("{fcm.url}")) + private String FCM_URL; + private final ObjectMapper objectMapper; + private final FCMTokenRepository fcmTokenRepository; + private final MemberRepository memberRepository; + + // fcm 기본 설정 진행 + // 이 과정에서 access token은 firebase가 자동 처리 + @PostConstruct + public void init() { + try { + GoogleCredentials googleCredentials = GoogleCredentials + .fromStream(new ClassPathResource(FCM_PRIVATE_KEY_PATH).getInputStream()) + .createScoped(List.of(fireBaseScope)); + + FirebaseOptions options = new FirebaseOptions.Builder() + .setCredentials(googleCredentials) + .build(); + + if (FirebaseApp.getApps().isEmpty()) { + FirebaseApp.initializeApp(options); + } + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + } + + /** + * @param senderId : 댓글 단 사람의 email + * @param receiverId : 푸쉬 알림을 받을 클라이언트의 email -> FCM token 식별 + * @param content : 댓글 내용 + * */ + @Transactional + @Async + public void sendMessageTo(String senderId, String receiverId, String content) throws IOException{ + final FCMToken fcmToken = fcmTokenRepository.findByReceiverId(receiverId); + Message message = makeMessage(fcmToken,senderId,receiverId,content); + try { + String messageResponse = FirebaseMessaging.getInstance().sendAsync(message).get(); + System.out.println(messageResponse); + } catch (ExecutionException | InterruptedException e) { + e.printStackTrace(); + } + /* + String message = makeMessage(fcmToken.getFcmToken(),senderId,receiverId,content); + + OkHttpClient client = new OkHttpClient(); + RequestBody requestBody = RequestBody.create(message, MediaType.get("application/json; charset=utf-8")); + + Request request = new Request.Builder() + .url(FCM_URL) + .post(requestBody) + .addHeader(HttpHeaders.AUTHORIZATION, "Bearer "+getAccessToken()) + .addHeader(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8") + .build(); + + Response response = client.newCall(request).execute(); + + */ + + } + + public Message makeMessage(FCMToken token, String senderId, String receiverId, String content) { + Member receiver = memberRepository.findByEmail(receiverId); + Notification notification = new Notification("새 댓글이 작성되었습니다.", content); + Message message = com.google.firebase.messaging.Message.builder() + .setNotification(notification) + .setToken(token.getFcmToken()) + .putData("senderId",senderId) + .putData("receiverId",receiverId) + .putData("receiverName",receiver.getNickname()) + .build(); + return message; + /* + //Notification + Notification notification = new Notification("새 댓글이 작성되었습니다.", content); + //Data + Data messageData = new FCMMessageDto.Data(date,sender.getNickname(), senderId,receiverId, content); + + //Message : token + Notification + Data + Message message = Message.builder() + .token(FCMToken) + .notification(notification) + .data(messageData).build(); + //DTO : validate_only + Message + FCMMessageDto fcmMessageDto = FCMMessageDto.builder() + .validate_only(false) + .message(message) + .build(); + + try { + return objectMapper.writeValueAsString(fcmMessageDto); + } catch (JsonProcessingException e) { + throw new ConvertingJSONException(); + } + + */ + } + @Transactional + public void saveToken(Member member, String fcmToken) { + if(!fcmTokenRepository.existsByReceiverId(member.getEmail())) { + fcmTokenRepository.save(FCMToken.builder() + .fcmToken(fcmToken) + .receiverId(member.getEmail()) + .build()); + } else { + FCMToken tokenEntity = fcmTokenRepository.findByReceiverId(member.getEmail()); + tokenEntity.updateToken(fcmToken); + } + } + + +} diff --git a/src/main/java/com/kimgreen/backend/domain/notification/service/NotificationService.java b/src/main/java/com/kimgreen/backend/domain/notification/service/NotificationService.java new file mode 100644 index 0000000..2c05d3c --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/notification/service/NotificationService.java @@ -0,0 +1,56 @@ +package com.kimgreen.backend.domain.notification.service; + +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.repository.MemberRepository; +import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.notification.dto.NotificationResponseDto; +import com.kimgreen.backend.domain.notification.entity.Notification; +import com.kimgreen.backend.domain.notification.repository.NotificationRepository; +import lombok.AllArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.util.Optional; + +@Service +@AllArgsConstructor +public class NotificationService { + private final FCMService fcmService; + private final PostRepository postRepository; + private final MemberRepository memberRepository; + private final NotificationRepository notificationRepository; + private final MemberService memberService; + + + //댓글 작성하기 API에서 호출 + @Transactional + public void commentNotification(Long postId, String senderId, String receiverId,String content) { + Member sender = memberRepository.findByEmail(senderId); + Member receiver = memberRepository.findByEmail(receiverId); + Optional post = postRepository.findById(postId); + try{ + if(post.isPresent()) { + fcmService.sendMessageTo(senderId, receiverId, content); + notificationRepository.save(Notification.builder() + .member(receiver) + .content(content) + .postId(postId) + .build()); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Transactional(readOnly = true) + public Page getNotifications(Pageable pageable) { + Member member = memberService.getCurrentMember(); + Page notifications = notificationRepository.findAllByMember(member,pageable); + return notifications.map(NotificationResponseDto::getDto); + } +} diff --git a/src/main/java/com/kimgreen/backend/exception/ConvertingJSONException.java b/src/main/java/com/kimgreen/backend/exception/ConvertingJSONException.java new file mode 100644 index 0000000..67a0c26 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/exception/ConvertingJSONException.java @@ -0,0 +1,4 @@ +package com.kimgreen.backend.exception; + +public class ConvertingJSONException extends RuntimeException{ +} diff --git a/src/main/java/com/kimgreen/backend/response/Advice.java b/src/main/java/com/kimgreen/backend/response/Advice.java index 4333c53..370790c 100644 --- a/src/main/java/com/kimgreen/backend/response/Advice.java +++ b/src/main/java/com/kimgreen/backend/response/Advice.java @@ -45,4 +45,9 @@ public Response BadgeNotFoundResponse() { return Response.failure(HttpStatus.NOT_FOUND,"요청한 뱃지를 찾을 수 없습니다."); } + @ExceptionHandler(ConvertingJSONException.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public Response ConvertingJSONExceptionResponse() { + return Response.failure(HttpStatus.INTERNAL_SERVER_ERROR,"JSON 변환 에러"); + } } diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 2d95898..814167f 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -18,6 +18,7 @@ public class Message { public static String CHANGE_PROFILE_BADGE_SUCCESS="프로필뱃지 선택 성공했습니다."; public static String GET_COLLECTED_BADGE_INFO="획득뱃지 상세정보 불러오기 성공했습니다."; public static String GET_NOT_COLLECTED_BADGE_INFO="미획득 뱃지 상세정보 불러오기 성공했습니다."; + public static String SUCCESS_GET_NOTIFICATION ="푸시알림 내역 보기 성공했습니다."; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 906dcdc..0518c3e 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -45,3 +45,11 @@ cloud: auto: false stack: auto: false + + +# fcm : for push alarm +fcm: + key: + path: kimgreen-f33e5-firebase-adminsdk-63srz-6817b2eec4.json + scope: https://www.googleapis.com/auth/cloud-platform + From 60ff66d6a42278b6509f292a7d842a411b0cdec5 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Mon, 15 Jan 2024 22:26:24 +0900 Subject: [PATCH 16/72] =?UTF-8?q?[fix]=20=ED=9A=8C=EC=9B=90=ED=83=88?= =?UTF-8?q?=ED=87=B4=20-=20validatePassword=20=EC=B6=94=EA=B0=80=20&=20Log?= =?UTF-8?q?InRequestDto=20=EC=88=98=EC=A0=95(=ED=85=8C=EC=8A=A4=ED=8A=B8?= =?UTF-8?q?=20=EC=98=A4=EB=A5=98=20=EB=B0=A9=EC=A7=80)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../member/controller/MemberController.java | 5 +++-- .../dto/Auth/DeleteMemberRequestDto.java | 12 ++++++++++++ .../member/dto/Auth/LogInRequestDto.java | 2 +- .../domain/member/service/AuthService.java | 2 +- .../domain/member/service/MemberService.java | 19 +++++++++++++++++-- .../repository/FCMTokenRepository.java | 1 + .../notification/service/FCMService.java | 5 +++-- 7 files changed, 38 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/member/dto/Auth/DeleteMemberRequestDto.java diff --git a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java index e65b37d..b5e51ce 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java +++ b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java @@ -1,5 +1,6 @@ package com.kimgreen.backend.domain.member.controller; +import com.kimgreen.backend.domain.member.dto.Auth.DeleteMemberRequestDto; import com.kimgreen.backend.domain.member.dto.Auth.SignUpRequestDto; import com.kimgreen.backend.domain.member.service.MemberService; import com.kimgreen.backend.response.Response; @@ -32,8 +33,8 @@ public Response changeAlarm(@RequestParam String type) { @Operation(summary = "회원 탈퇴") @ResponseStatus(OK) @DeleteMapping() - public Response deleteMember() { - memberService.deleteMember(); + public Response deleteMember(@RequestBody DeleteMemberRequestDto deleteMemberRequestDto) { + memberService.deleteMember(deleteMemberRequestDto); return success(DELETE_MEMBER_SUCCESS); } diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/DeleteMemberRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/DeleteMemberRequestDto.java new file mode 100644 index 0000000..97ab258 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/DeleteMemberRequestDto.java @@ -0,0 +1,12 @@ +package com.kimgreen.backend.domain.member.dto.Auth; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class DeleteMemberRequestDto { + private String password; +} diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/LogInRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/LogInRequestDto.java index c76d971..785901f 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/LogInRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/LogInRequestDto.java @@ -10,5 +10,5 @@ public class LogInRequestDto { private String email; private String password; - private String fcmToken; + //private String fcmToken; } diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java index 6e3d2ff..d29e113 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java @@ -83,7 +83,7 @@ public TokenDto logIn(LogInRequestDto dto) { // refresh token 저장 saveRefreshToken(email, generatedRefreshToken); // FCM token 저장 - FCMService.saveToken(member,dto.getFcmToken()); + //FCMService.saveToken(member,dto.getFcmToken()); return TokenDto.builder() diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java index 6170cf0..458157a 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java @@ -1,20 +1,23 @@ package com.kimgreen.backend.domain.member.service; import com.kimgreen.backend.domain.community.service.S3Service; +import com.kimgreen.backend.domain.member.dto.Auth.DeleteMemberRequestDto; import com.kimgreen.backend.domain.member.dto.Member.MemberInfoResponse; import com.kimgreen.backend.domain.member.dto.Member.SettingInfoResponseDto; import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.entity.MemberProfileImg; -import com.kimgreen.backend.domain.member.entity.RefreshToken; import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; import com.kimgreen.backend.domain.member.repository.MemberRepository; import com.kimgreen.backend.domain.member.repository.RefreshTokenRepository; +import com.kimgreen.backend.domain.notification.repository.FCMTokenRepository; import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; import com.kimgreen.backend.domain.profile.repository.BadgeRepository; import com.kimgreen.backend.domain.profile.repository.ProfileBadgeRepository; import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; +import com.kimgreen.backend.exception.LogInFailurePassword; import lombok.RequiredArgsConstructor; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -30,6 +33,8 @@ public class MemberService { private final BadgeRepository badgeRepository; private final ProfileBadgeRepository profileBadgeRepository; private final S3Service s3Service; + private final FCMTokenRepository fcmTokenRepository; + private final PasswordEncoder passwordEncoder; public Member getCurrentMember() { @@ -46,13 +51,17 @@ public void changeAlarm(String type) { } @Transactional - public void deleteMember() { + public void deleteMember(DeleteMemberRequestDto dto) { Member member = getCurrentMember(); + validatePassword(dto.getPassword(),member); String email = member.getEmail(); if(refreshTokenRepository.existsByEmail(email)) { refreshTokenRepository.deleteByEmail(email); } + if(fcmTokenRepository.existsByReceiverId(email)) { + fcmTokenRepository.deleteByReceiverId(email); + } profileBadgeRepository.deleteByMember(member); badgeRepository.deleteByMember(member); representativeBadgeRepository.deleteByMember(member); @@ -137,4 +146,10 @@ public void deleteFromS3(String urlToDelete) { s3Service.delete(urlToDelete); } } + + public void validatePassword(String getPassword, Member member) { + if (!(passwordEncoder.matches(getPassword, member.getPassword()))) { + throw new LogInFailurePassword(); + } + } } diff --git a/src/main/java/com/kimgreen/backend/domain/notification/repository/FCMTokenRepository.java b/src/main/java/com/kimgreen/backend/domain/notification/repository/FCMTokenRepository.java index cbf20c0..d778384 100644 --- a/src/main/java/com/kimgreen/backend/domain/notification/repository/FCMTokenRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/notification/repository/FCMTokenRepository.java @@ -6,4 +6,5 @@ public interface FCMTokenRepository extends JpaRepository { public FCMToken findByReceiverId(String email); public boolean existsByReceiverId(String email); + public void deleteByReceiverId(String email); } diff --git a/src/main/java/com/kimgreen/backend/domain/notification/service/FCMService.java b/src/main/java/com/kimgreen/backend/domain/notification/service/FCMService.java index d31a67a..666f6c5 100644 --- a/src/main/java/com/kimgreen/backend/domain/notification/service/FCMService.java +++ b/src/main/java/com/kimgreen/backend/domain/notification/service/FCMService.java @@ -13,6 +13,7 @@ import com.kimgreen.backend.domain.member.repository.MemberRepository; import jakarta.annotation.PostConstruct; import lombok.AllArgsConstructor; +import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.scheduling.annotation.Async; @@ -26,7 +27,7 @@ import java.util.concurrent.ExecutionException; @Service -@AllArgsConstructor +@RequiredArgsConstructor public class FCMService { @Value("${fcm.key.path}") private String FCM_PRIVATE_KEY_PATH; @@ -37,7 +38,7 @@ public class FCMService { @Value(("{fcm.url}")) private String FCM_URL; - private final ObjectMapper objectMapper; + private final FCMTokenRepository fcmTokenRepository; private final MemberRepository memberRepository; From 4bf61f4793938c256338219a3cc736755f86ca48 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Tue, 16 Jan 2024 14:53:35 +0900 Subject: [PATCH 17/72] [fix] fix token error message --- Dockerfile | 19 +++++++++++++++++++ .../JwtAuthenticationEntryPoint.java | 10 ++++++---- .../Authentication/JwtExceptionFilter.java | 3 +-- .../config/Authentication/JwtFilter.java | 4 +++- .../backend/exception/TokenNotFound.java | 4 ++++ .../backend/exception/TokenNotValid.java | 4 ++++ .../com/kimgreen/backend/response/Advice.java | 12 ++++++++++++ 7 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 Dockerfile create mode 100644 src/main/java/com/kimgreen/backend/exception/TokenNotFound.java create mode 100644 src/main/java/com/kimgreen/backend/exception/TokenNotValid.java diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d5a0136 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +# docker에서 받아서 쓸 base img +FROM amazoncorretto:17.0.6 +# JAR_FILE 변수설정 : .jar 파일 위치 +ARG JAR_FILE=build/libs/backend-0.0.1-SNAPSHOT.jar +# 위에서 할당한 .jar를 app.jar이름으로 copy +COPY ${JAR_FILE} app.jar +# java 실행 시 parameter +# executable : java +# param : -jar, /app.jar +ENTRYPOINT ["java", "-jar", "/app.jar"] + +# 1. Dockerfile 기반 이미지 생성 +#docker build -t kimgreen . + +# 2. 이미지 기반 컨테이너 실행 +# docker run -d -p 8080:8080 kimgreen + +# 3. docker hub에 push +# docker push gol2580/kimgreen diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java index 1503a75..8331d6f 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.kimgreen.backend.exception.TokenNotValid; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -31,18 +32,19 @@ public void commence(HttpServletRequest request, if(exception!=null) { if (exception.equals(EXPIRED)) { - setResponse(response, EXPIRED); + setResponse(response,HttpStatus.UNAUTHORIZED.value(),"토큰이 유효하지 않습니다."); } if (exception.equals(DENIED)) { - setResponse(response, DENIED); + setResponse(response,HttpStatus.NOT_FOUND.value(), "토큰이 없습니다."); } } } - public void setResponse(HttpServletResponse response,String msg) throws IOException{ + public void setResponse(HttpServletResponse response,int status,String msg) throws IOException{ ObjectNode json = new ObjectMapper().createObjectNode(); + json.put("status",status); + json.put("success", false); json.put("message", msg); - json.put("code", HttpStatus.UNAUTHORIZED.value()); String newResponse = new ObjectMapper().writeValueAsString(json); response.getWriter().write(newResponse); } diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtExceptionFilter.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtExceptionFilter.java index 183c996..63c144c 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtExceptionFilter.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtExceptionFilter.java @@ -20,8 +20,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse try { filterChain.doFilter(request, response); // go to 'JwtAuthenticationFilter' } catch (JwtException ex) { - System.out.println("in t"); - setErrorResponse(HttpStatus.UNAUTHORIZED, response, ex); + ex.printStackTrace(); } } diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtFilter.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtFilter.java index 6a814c0..ad170af 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtFilter.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtFilter.java @@ -1,5 +1,7 @@ package com.kimgreen.backend.config.Authentication; +import com.kimgreen.backend.exception.TokenNotFound; +import com.kimgreen.backend.exception.TokenNotValid; import io.jsonwebtoken.ExpiredJwtException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -29,7 +31,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse Authentication authentication = jwtProvider.getAuthentication(accessToken); // access token 검증 - if (StringUtils.hasText(accessToken) && jwtProvider.validateToken(accessToken) == SUCCESS) { + if (StringUtils.hasText(accessToken) && jwtProvider.validateToken(accessToken).equals(SUCCESS)) { SecurityContextHolder.getContext().setAuthentication(authentication); // security context에 인증 정보 저장 } } catch (ExpiredJwtException e) { diff --git a/src/main/java/com/kimgreen/backend/exception/TokenNotFound.java b/src/main/java/com/kimgreen/backend/exception/TokenNotFound.java new file mode 100644 index 0000000..fba00b8 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/exception/TokenNotFound.java @@ -0,0 +1,4 @@ +package com.kimgreen.backend.exception; + +public class TokenNotFound extends RuntimeException{ +} diff --git a/src/main/java/com/kimgreen/backend/exception/TokenNotValid.java b/src/main/java/com/kimgreen/backend/exception/TokenNotValid.java new file mode 100644 index 0000000..f0297ca --- /dev/null +++ b/src/main/java/com/kimgreen/backend/exception/TokenNotValid.java @@ -0,0 +1,4 @@ +package com.kimgreen.backend.exception; + +public class TokenNotValid extends RuntimeException{ +} diff --git a/src/main/java/com/kimgreen/backend/response/Advice.java b/src/main/java/com/kimgreen/backend/response/Advice.java index 370790c..658e9f8 100644 --- a/src/main/java/com/kimgreen/backend/response/Advice.java +++ b/src/main/java/com/kimgreen/backend/response/Advice.java @@ -50,4 +50,16 @@ public Response BadgeNotFoundResponse() { public Response ConvertingJSONExceptionResponse() { return Response.failure(HttpStatus.INTERNAL_SERVER_ERROR,"JSON 변환 에러"); } + + @ExceptionHandler(TokenNotValid.class) + @ResponseStatus(HttpStatus.UNAUTHORIZED) + public Response TokenNotValidResponse() { + return Response.failure(HttpStatus.UNAUTHORIZED,"토큰이 유효하지 않습니다."); + } + @ExceptionHandler(TokenNotFound.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Response TokenNotFoundResponse() { + return Response.failure(HttpStatus.NOT_FOUND,"토큰이 없습니다."); + } + } From a982c1e307e25c7cf6b2eca4bc2252921bac9b1b Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Tue, 16 Jan 2024 19:17:39 +0900 Subject: [PATCH 18/72] Create github-action.yml --- .github/workflows/github-action.yml | 110 ++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 .github/workflows/github-action.yml diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml new file mode 100644 index 0000000..3333f4d --- /dev/null +++ b/.github/workflows/github-action.yml @@ -0,0 +1,110 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# This workflow will build a package using Gradle and then publish it to GitHub packages when a release is created +# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#Publishing-using-gradle + +name: CI/CD + +# event trigger +on: + push: + branches: + - main + +jobs: + CI-CD: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' # https://github.com/actions/setup-java + + ## gradle caching + - name: Gradle Caching + uses: actions/cache@v3 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- + + ## create application.properties + - name: make application.properties + run: | + cd ./src/main/resources + + # application.properties 파일 생성 + touch ./application.properties + + # GitHub-Actions에서 설정한 값을 application.properties 파일에 쓰기 + echo "${{ secrets.PROPERTIES }}" > ./application.properties + shell: bash + + - name: create firebase key + run: | + cd ./src/main/resources + touch ./kimgreen-f33e5-firebase-adminsdk-63srz-6817b2eec4.json + echo "${{ secrets.FIREBASE_KEY }}" > ./kimgreen-f33e5-firebase-adminsdk-63srz-6817b2eec4.json + + - name: Build with Gradle + run: ./gradlew build -x test + + + build: + + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'temurin' + server-id: github # Value of the distributionManagement/repository/id field of the pom.xml + settings-path: ${{ github.workspace }} # location for the settings.xml file + + - name: Build with Gradle + uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 + with: + arguments: build + + - name: Docker build & push + run: | + docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + docker build -t ${{ secrets.DOCKER_USERNAME }}/kimgreen . + docker push ${{ secrets.DOCKER_USERNAME }}/kimgreen + + - name: Deploy + uses: appleboy/ssh-action@v1.0.3 + with: + host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 DNS + username: ${{ secrets.USERNAME }} # ubuntu + password: ${{ secrets.PASSWORD }} + key: ${{ secrets.PRIVATE_KEY }} + script: | + sudo docker ps + sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker image prune -f + + + # The USERNAME and TOKEN need to correspond to the credentials environment variables used in + # the publishing section of your build.gradle + - name: Publish to GitHub Packages + uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 + with: + arguments: publish + env: + USERNAME: ${{ github.actor }} + TOKEN: ${{ secrets.GITHUB_TOKEN }} From efd20a474d9c8d2a5a5ef813b576c64dcdebd8cf Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Tue, 16 Jan 2024 19:30:48 +0900 Subject: [PATCH 19/72] Update github-action.yml --- .github/workflows/github-action.yml | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 3333f4d..6c52cc8 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -24,27 +24,17 @@ jobs: java-version: '17' distribution: 'temurin' # https://github.com/actions/setup-java - ## gradle caching - - name: Gradle Caching - uses: actions/cache@v3 - with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} - restore-keys: | - ${{ runner.os }}-gradle- - - ## create application.properties - - name: make application.properties + + ## create security.properties + - name: make security.properties run: | cd ./src/main/resources - # application.properties 파일 생성 - touch ./application.properties + # security.properties 파일 생성 + touch ./security.properties - # GitHub-Actions에서 설정한 값을 application.properties 파일에 쓰기 - echo "${{ secrets.PROPERTIES }}" > ./application.properties + # GitHub-Actions에서 설정한 값을 security.properties 파일에 쓰기 + echo "${{ secrets.PROPERTIES }}" > ./security.properties shell: bash - name: create firebase key From e687ba22f56f179089e71de6a226b2a4f6d0b201 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Tue, 16 Jan 2024 19:39:04 +0900 Subject: [PATCH 20/72] Update github-action.yml --- .github/workflows/github-action.yml | 67 ++++++++--------------------- 1 file changed, 17 insertions(+), 50 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 6c52cc8..533d70c 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -45,56 +45,23 @@ jobs: - name: Build with Gradle run: ./gradlew build -x test - - - build: - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - - steps: - - uses: actions/checkout@v3 - - name: Set up JDK 11 - uses: actions/setup-java@v3 - with: - java-version: '11' - distribution: 'temurin' - server-id: github # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Build with Gradle - uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 - with: - arguments: build - - name: Docker build & push - run: | - docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} - docker build -t ${{ secrets.DOCKER_USERNAME }}/kimgreen . - docker push ${{ secrets.DOCKER_USERNAME }}/kimgreen - - - name: Deploy - uses: appleboy/ssh-action@v1.0.3 - with: - host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 DNS - username: ${{ secrets.USERNAME }} # ubuntu - password: ${{ secrets.PASSWORD }} - key: ${{ secrets.PRIVATE_KEY }} - script: | - sudo docker ps - sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker image prune -f - + - name: Docker build & push + run: | + docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + docker build -t ${{ secrets.DOCKER_USERNAME }}/kimgreen . + docker push ${{ secrets.DOCKER_USERNAME }}/kimgreen - # The USERNAME and TOKEN need to correspond to the credentials environment variables used in - # the publishing section of your build.gradle - - name: Publish to GitHub Packages - uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 - with: - arguments: publish - env: - USERNAME: ${{ github.actor }} - TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Deploy + uses: appleboy/ssh-action@v1.0.3 + with: + host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 DNS + username: ${{ secrets.USERNAME }} # ubuntu + password: ${{ secrets.PASSWORD }} + key: ${{ secrets.PRIVATE_KEY }} + script: | + sudo docker ps + sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker image prune -f From 2d463daa26665e716772dc1367f18eaba4fc5011 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Tue, 16 Jan 2024 19:47:40 +0900 Subject: [PATCH 21/72] Update github-action.yml --- .github/workflows/github-action.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 533d70c..b109e70 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -58,7 +58,6 @@ jobs: with: host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 DNS username: ${{ secrets.USERNAME }} # ubuntu - password: ${{ secrets.PASSWORD }} key: ${{ secrets.PRIVATE_KEY }} script: | sudo docker ps From d28f6a450e3b6fc2c3cd06dc457162abc5746a10 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Wed, 17 Jan 2024 11:39:10 +0900 Subject: [PATCH 22/72] =?UTF-8?q?[fix]=20Reason=20enum=20=EB=B3=80?= =?UTF-8?q?=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 4 ++-- .../com/kimgreen/backend/domain/community/entity/Reason.java | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index d5a0136..d8a0521 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,10 +10,10 @@ COPY ${JAR_FILE} app.jar ENTRYPOINT ["java", "-jar", "/app.jar"] # 1. Dockerfile 기반 이미지 생성 -#docker build -t kimgreen . +#docker build -t gol2580/kimgreen . # 2. 이미지 기반 컨테이너 실행 -# docker run -d -p 8080:8080 kimgreen +# docker run -d -p 8080:8080 gol2580/kimgreen # 3. docker hub에 push # docker push gol2580/kimgreen diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/Reason.java b/src/main/java/com/kimgreen/backend/domain/community/entity/Reason.java index 3ea3352..f540b21 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/Reason.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/Reason.java @@ -1,7 +1,8 @@ package com.kimgreen.backend.domain.community.entity; public enum Reason { - WRONG_CATEGORY("잘못된 카테고리"); + FAKE("거짓 정보"), + ETC("기타"); private String content; private Reason(String content) { From 944d15e69c8a65dc01ee5741e1945fa4912360be Mon Sep 17 00:00:00 2001 From: gol2580 Date: Wed, 17 Jan 2024 11:59:29 +0900 Subject: [PATCH 23/72] =?UTF-8?q?[fix]=20LikeAlarm=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/member/controller/MemberController.java | 4 ++-- .../domain/member/dto/Auth/SignUpRequestDto.java | 2 +- .../backend/domain/member/entity/Member.java | 7 +++++-- .../backend/domain/member/service/MemberService.java | 12 ++---------- 4 files changed, 10 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java index b5e51ce..d293ce8 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java +++ b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java @@ -25,8 +25,8 @@ public class MemberController { @Operation(summary = "댓글 알림 변경") @ResponseStatus(OK) @PatchMapping("/alarm") - public Response changeAlarm(@RequestParam String type) { - memberService.changeAlarm(type); + public Response changeAlarm() { + memberService.changeCommentAlarm(); return success(CHANGE_ALARM_SUCCESS); } diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java index 701d123..f363b8c 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java @@ -19,7 +19,7 @@ public Member toMemberEntity(String email, String password, String nickname) { .email(email) .password(password) .nickname(nickname) - .commentAlarm(false).likeAlarm(false) + .commentAlarm(false) .role(Role.ROLE_USER) .build(); } diff --git a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java index 82fb212..9b0c311 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java +++ b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java @@ -49,11 +49,12 @@ public class Member extends AuditEntity { @Column(name="comment_alarm",columnDefinition = "boolean default false") private boolean commentAlarm; - @Column(name="like_alarm",columnDefinition = "boolean default false") - private boolean likeAlarm; + //@Column(name="like_alarm",columnDefinition = "boolean default false") + //private boolean likeAlarm; @Enumerated(EnumType.STRING) private Role role; + public void changePassword(String newPassword) { this.password = newPassword; } @@ -63,4 +64,6 @@ public void changeCommentAlarm(boolean b) { this.likeAlarm = b; } + public void changeNickname(String nickname) { this.nickname = nickname; } + } diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java index 458157a..7805699 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java @@ -41,15 +41,6 @@ public Member getCurrentMember() { return memberRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName()); } - @Transactional - public void changeAlarm(String type) { - if(type.equals("c")) { - changeCommentAlarm(); - } else if(type.equals("l")) { - changeLikeAlarm(); - } - } - @Transactional public void deleteMember(DeleteMemberRequestDto dto) { Member member = getCurrentMember(); @@ -78,6 +69,7 @@ public void changeCommentAlarm() { member.changeCommentAlarm(true); } } + /* @Transactional public void changeLikeAlarm() { Member member = getCurrentMember(); @@ -87,6 +79,7 @@ public void changeLikeAlarm() { member.changeLikeAlarm(true); } } + */ @Transactional public void changeNickname(String nickname) { @@ -126,7 +119,6 @@ public SettingInfoResponseDto getSettingInfo() { .profileBadge(representativeBadge.getRepresentativeBadge().name) .profileBadgeImg(badgeUrl) .commentAgreement(member.isCommentAlarm()) - .likeAgreement(member.isLikeAlarm()) .build(); } From b842a018c53335a0003bb633724bfd36c2b9f444 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Wed, 17 Jan 2024 12:08:28 +0900 Subject: [PATCH 24/72] =?UTF-8?q?[fix]=20=EA=B9=80=EA=B7=B8=EB=A6=B0?= =?UTF-8?q?=EB=B0=95=EC=82=AC=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/kimgreen/backend/domain/BadgeList.java | 3 ++- .../java/com/kimgreen/backend/domain/profile/entity/Badge.java | 2 ++ .../kimgreen/backend/domain/profile/service/BadgeService.java | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/kimgreen/backend/domain/BadgeList.java b/src/main/java/com/kimgreen/backend/domain/BadgeList.java index 66c7b0c..0e5d50b 100644 --- a/src/main/java/com/kimgreen/backend/domain/BadgeList.java +++ b/src/main/java/com/kimgreen/backend/domain/BadgeList.java @@ -23,7 +23,8 @@ public enum BadgeList { ETC_3("아마추어 기타리스트",3,"amateur_guitarist.png","기타 인증글 3회 이상",20), ETC_10("프로 기타리스트",10,"pro_guitarist.png","기타 인증글 10회 이상",21), ADVENTURER("환경 모험가","adventurer.png","각 카테고리별 인증글 1회 이상",22), - DOCTOR("김그린 박사","doctor.png",23), + SPROUT("새싹 김그린","eco_friend.png","튜토리얼 1회 열람",23), + //DOCTOR("김그린 박사","doctor.png",23), GOLDEN_KIMGREEN("황금 김그린","golden_kimgreen.png","모든 뱃지 획득",24); public String name; diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index 1c68979..a110584 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -117,6 +117,8 @@ public class Badge extends AuditEntity { @Column(name="etc_10_is_achieved",columnDefinition = "boolean default false") private boolean etc10IsAchieved; + @Column(name="sprout_is_achieved", columnDefinition = "boolean default true") + private boolean sproutIsAchieved; @Column(name = "adventurer_is_achieved", columnDefinition = "boolean default false") private boolean adventurerIsAchieved; diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java index 2871c4e..3811f8a 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -146,6 +146,8 @@ public void validateList(List badges) { public Map getMap(Badge badge) { Map map = new LinkedHashMap<>(); + if(badge.isSproutIsAchieved()) {map.put(BadgeList.SPROUT,true);} + else {map.put(BadgeList.SPROUT,false);} if(badge.isCertification10IsAchieved()){map.put(BadgeList.NORANG,true);} else {map.put(BadgeList.NORANG,false);} if(badge.isCertification20IsAchieved()){map.put(BadgeList.YEONDU,true);} @@ -198,6 +200,7 @@ public Map getCountMap(Map badgeMap,Badge Map map = new LinkedHashMap<>(); for(BadgeList badges: badgeMap.keySet()) { if(badgeMap.get(badges)==false) { + if(badges.equals(BadgeList.SPROUT)) {map.put(BadgeList.SPROUT,-1);} if(badges.equals(BadgeList.NORANG)) {map.put(BadgeList.NORANG,badge.getCertificationCount());} if(badges.equals(BadgeList.YEONDU)) {map.put(BadgeList.YEONDU,badge.getCertificationCount());} if(badges.equals(BadgeList.GREEN)) {map.put(BadgeList.GREEN,badge.getCertificationCount());} From 70e42490e42afaa6fa4fdbef67524b3ce1acfdb0 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Wed, 17 Jan 2024 13:43:15 +0900 Subject: [PATCH 25/72] [feat] postReport --- .../controller/ReportController.java | 28 +++++++++++++++++-- .../dto/report/ReportRequestDto.java | 24 ++++++++++++++++ .../community/service/ReportService.java | 22 +++++++++++++++ .../dto/Member/SettingInfoResponseDto.java | 2 -- .../backend/exception/PostNotFound.java | 4 +++ .../com/kimgreen/backend/response/Advice.java | 8 ++++-- .../kimgreen/backend/response/Message.java | 1 + 7 files changed, 83 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/community/dto/report/ReportRequestDto.java create mode 100644 src/main/java/com/kimgreen/backend/exception/PostNotFound.java diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/ReportController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/ReportController.java index 511130f..e5669e6 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/ReportController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/ReportController.java @@ -1,12 +1,36 @@ package com.kimgreen.backend.domain.community.controller; +import com.kimgreen.backend.domain.community.dto.report.ReportRequestDto; +import com.kimgreen.backend.domain.community.service.ReportService; +import com.kimgreen.backend.response.*; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; +import lombok.RequiredArgsConstructor; +import org.springdoc.core.annotations.ParameterObject; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; + +import static com.kimgreen.backend.response.Message.*; +import static com.kimgreen.backend.response.Response.*; +import static org.springframework.http.HttpStatus.OK; @Tag(name = "Report") @RestController @RequestMapping(value="/report") +@RequiredArgsConstructor public class ReportController { + + private final ReportService reportService; + + + @Operation(summary = "게시글 신고하기") + @ResponseStatus(OK) + @PostMapping() + public Response postReport(@ParameterObject Long postId, + @RequestBody ReportRequestDto reportRequestDto) { + reportService.postReport(postId,reportRequestDto); + return success(POST_REPORT_SUCCESS); + } + } diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/report/ReportRequestDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/report/ReportRequestDto.java new file mode 100644 index 0000000..25a482c --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/report/ReportRequestDto.java @@ -0,0 +1,24 @@ +package com.kimgreen.backend.domain.community.dto.report; + +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.Reason; +import com.kimgreen.backend.domain.community.entity.Report; +import com.kimgreen.backend.domain.member.entity.Member; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ReportRequestDto { + private String reason; + private String content; + + public Report toEntity(String reason, String content, Member member, Post post) { + return Report.builder() + .reason(Reason.valueOf(reason)) + .content(content) + .member(member) + .post(post) + .build(); + } +} diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/ReportService.java b/src/main/java/com/kimgreen/backend/domain/community/service/ReportService.java index d5af6d4..77a2ac1 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/ReportService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/ReportService.java @@ -1,7 +1,29 @@ package com.kimgreen.backend.domain.community.service; +import com.kimgreen.backend.domain.community.dto.report.ReportRequestDto; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.community.repository.ReportRepository; +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.exception.PostNotFound; +import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @Service +@AllArgsConstructor public class ReportService { + private final ReportRepository reportRepository; + private final MemberService memberService; + private final PostRepository postRepository; + + public void postReport(Long postId,ReportRequestDto reportRequestDto) { + Member member = memberService.getCurrentMember(); + Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); + reportRepository.save( + reportRequestDto.toEntity( + reportRequestDto.getReason(), reportRequestDto.getContent(), member,post + ) + ); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java index 9f1baf6..ad412ac 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java @@ -15,6 +15,4 @@ public class SettingInfoResponseDto { private String profileBadge; private String profileBadgeImg; private boolean commentAgreement; - private boolean likeAgreement; - } diff --git a/src/main/java/com/kimgreen/backend/exception/PostNotFound.java b/src/main/java/com/kimgreen/backend/exception/PostNotFound.java new file mode 100644 index 0000000..bccacec --- /dev/null +++ b/src/main/java/com/kimgreen/backend/exception/PostNotFound.java @@ -0,0 +1,4 @@ +package com.kimgreen.backend.exception; + +public class PostNotFound extends RuntimeException{ +} diff --git a/src/main/java/com/kimgreen/backend/response/Advice.java b/src/main/java/com/kimgreen/backend/response/Advice.java index 658e9f8..13da39f 100644 --- a/src/main/java/com/kimgreen/backend/response/Advice.java +++ b/src/main/java/com/kimgreen/backend/response/Advice.java @@ -14,7 +14,7 @@ public class Advice { @ResponseStatus(HttpStatus.CONFLICT) public Response DuplicateEmailResponse() { return Response.failure(HttpStatus.CONFLICT, "중복 이메일입니다."); -} + } @ExceptionHandler(LogInFailureEmail.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @@ -62,4 +62,8 @@ public Response TokenNotFoundResponse() { return Response.failure(HttpStatus.NOT_FOUND,"토큰이 없습니다."); } -} + @ExceptionHandler(PostNotFound.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Response PostNotFoundResponse(){return Response.failure(HttpStatus.NOT_FOUND, "요청한 게시글을 찾을 수 없습니다.");} + +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 814167f..08ab46e 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -19,6 +19,7 @@ public class Message { public static String GET_COLLECTED_BADGE_INFO="획득뱃지 상세정보 불러오기 성공했습니다."; public static String GET_NOT_COLLECTED_BADGE_INFO="미획득 뱃지 상세정보 불러오기 성공했습니다."; public static String SUCCESS_GET_NOTIFICATION ="푸시알림 내역 보기 성공했습니다."; + public static String POST_REPORT_SUCCESS="게시글 신고하기 성공했습니다."; } From 5a192344ee0c8b602102d733648ae01e95666f39 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Wed, 17 Jan 2024 14:47:18 +0900 Subject: [PATCH 26/72] github action test --- Dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Dockerfile b/Dockerfile index d8a0521..5c7d47c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,3 +17,4 @@ ENTRYPOINT ["java", "-jar", "/app.jar"] # 3. docker hub에 push # docker push gol2580/kimgreen +# push test From 1d5e117542de0db13cb42994c61a10b48d9ceef6 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 14:49:51 +0900 Subject: [PATCH 27/72] Update github-action.yml --- .github/workflows/github-action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index b109e70..1a83c02 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -11,7 +11,7 @@ name: CI/CD on: push: branches: - - main + - master jobs: CI-CD: From d5e1cdcae67237d2dd042afc8281a85a0227668a Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 15:07:58 +0900 Subject: [PATCH 28/72] Update github-action.yml --- .github/workflows/github-action.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 1a83c02..ef32aec 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -44,7 +44,9 @@ jobs: echo "${{ secrets.FIREBASE_KEY }}" > ./kimgreen-f33e5-firebase-adminsdk-63srz-6817b2eec4.json - name: Build with Gradle - run: ./gradlew build -x test + run: | + chmod +x ./gradlew + ./gradlew build -x test - name: Docker build & push From f7465f58e36d0d3cb5ee38e066ea0abe1b9b4d92 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 15:18:33 +0900 Subject: [PATCH 29/72] Update github-action.yml --- .github/workflows/github-action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index ef32aec..04541de 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -59,7 +59,7 @@ jobs: uses: appleboy/ssh-action@v1.0.3 with: host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 DNS - username: ${{ secrets.USERNAME }} # ubuntu + username: ${{ secrets.USERNAME }} key: ${{ secrets.PRIVATE_KEY }} script: | sudo docker ps From ee1b5ef282b3c980aed4a2ead50e60a11429c76f Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 15:21:53 +0900 Subject: [PATCH 30/72] Update github-action.yml --- .github/workflows/github-action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 04541de..6e85279 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -60,7 +60,7 @@ jobs: with: host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 DNS username: ${{ secrets.USERNAME }} - key: ${{ secrets.PRIVATE_KEY }} + key: ${{ secrets.PRIVATE_KEY }} # private key test script: | sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen From 11bb3f600db2d8f88b3780b0ac0d41cede39b6eb Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 16:12:29 +0900 Subject: [PATCH 31/72] Update github-action.yml --- .github/workflows/github-action.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 6e85279..170dae3 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -62,7 +62,8 @@ jobs: username: ${{ secrets.USERNAME }} key: ${{ secrets.PRIVATE_KEY }} # private key test script: | - sudo docker ps - sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker image prune -f + whoami + #sudo docker ps + #sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen + #sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen + #sudo docker image prune -f From 3d04cabdbcdf08827e41306e840cd6a260644fae Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 16:14:36 +0900 Subject: [PATCH 32/72] Update github-action.yml --- .github/workflows/github-action.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 170dae3..06cb5ec 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -63,7 +63,4 @@ jobs: key: ${{ secrets.PRIVATE_KEY }} # private key test script: | whoami - #sudo docker ps - #sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - #sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen - #sudo docker image prune -f + From 5f104d8bf062182fb9ae1b60d67ae1563176717f Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 16:18:45 +0900 Subject: [PATCH 33/72] Update github-action.yml --- .github/workflows/github-action.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 06cb5ec..1bc6455 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -62,5 +62,8 @@ jobs: username: ${{ secrets.USERNAME }} key: ${{ secrets.PRIVATE_KEY }} # private key test script: | - whoami + sudo docker ps + sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker image prune -f From e79a554fb07d496f0b75c892a0ff80fa46d5fcc2 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 16:24:42 +0900 Subject: [PATCH 34/72] Update github-action.yml --- .github/workflows/github-action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 1bc6455..91527c3 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -59,7 +59,7 @@ jobs: uses: appleboy/ssh-action@v1.0.3 with: host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 DNS - username: ${{ secrets.USERNAME }} + username: ${{ secrets.USERNAME }} # ubuntu-latest key: ${{ secrets.PRIVATE_KEY }} # private key test script: | sudo docker ps From 1dda3efa140468697766c874344b44f58e6850ac Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Wed, 17 Jan 2024 16:43:59 +0900 Subject: [PATCH 35/72] Update github-action.yml --- .github/workflows/github-action.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 91527c3..a125f8d 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -58,9 +58,9 @@ jobs: - name: Deploy uses: appleboy/ssh-action@v1.0.3 with: - host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 DNS - username: ${{ secrets.USERNAME }} # ubuntu-latest - key: ${{ secrets.PRIVATE_KEY }} # private key test + host: ${{ secrets.HOST}} # EC2 퍼블릭 IPv4 + username: ${{ secrets.USERNAME }} # ec2-user + key: ${{ secrets.PRIVATE_KEY }} # .pem script: | sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen From f64522c66553a8f9652e40c5e9232d967a608ca1 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Wed, 17 Jan 2024 23:34:56 +0900 Subject: [PATCH 36/72] [fix] fix AuditEntity : String to LocalDateTime --- .../java/com/kimgreen/backend/domain/AuditEntity.java | 10 ++++++---- .../notification/dto/NotificationResponseDto.java | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/AuditEntity.java b/src/main/java/com/kimgreen/backend/domain/AuditEntity.java index 0920ed7..874af6f 100644 --- a/src/main/java/com/kimgreen/backend/domain/AuditEntity.java +++ b/src/main/java/com/kimgreen/backend/domain/AuditEntity.java @@ -19,18 +19,20 @@ public class AuditEntity { @CreatedDate - private String createdAt; + private LocalDateTime createdAt; @LastModifiedDate - private String modifiedAt; + private LocalDateTime modifiedAt; @PrePersist public void prePersist() { - this.createdAt = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); + String formattedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); + this.createdAt = LocalDateTime.parse(formattedDate,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); this.modifiedAt = this.createdAt; } @PreUpdate public void onUpdate() { - this.modifiedAt = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); + String formattedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); + this.modifiedAt = LocalDateTime.parse(formattedDate,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); } } diff --git a/src/main/java/com/kimgreen/backend/domain/notification/dto/NotificationResponseDto.java b/src/main/java/com/kimgreen/backend/domain/notification/dto/NotificationResponseDto.java index f6da5a2..7a43636 100644 --- a/src/main/java/com/kimgreen/backend/domain/notification/dto/NotificationResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/notification/dto/NotificationResponseDto.java @@ -13,7 +13,7 @@ @Getter public class NotificationResponseDto { private Long postId; - private String createdAt; + private LocalDateTime createdAt; private String content; public static NotificationResponseDto getDto(Notification notification) { From 61b2b04a9692cfc54ca14e09f31a3f32682778bd Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 18 Jan 2024 02:04:07 +0900 Subject: [PATCH 37/72] [fix] docker-compose.yml --- docker-compose-dev.yml | 13 ---------- docker-compose.yml | 24 +++++++++++++++++++ .../community/repository/PostRepository.java | 13 +++++----- 3 files changed, 31 insertions(+), 19 deletions(-) delete mode 100644 docker-compose-dev.yml create mode 100644 docker-compose.yml diff --git a/docker-compose-dev.yml b/docker-compose-dev.yml deleted file mode 100644 index 6b6b17b..0000000 --- a/docker-compose-dev.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: '3.8' -services: - mysql: - image: mysql:8.0 - restart: always - ports: - - "3306:3306" - environment: - MYSQL_DATABASE: test - MYSQL_USER: user - MYSQL_PASSWORD: 1234 - MYSQL_ROOT_PASSWORD: 1234 - TZ: Asia/Seoul diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..fd619c5 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,24 @@ +version: '3.8' +services: + server: + image: ${DOCKER_USERNAME}/kimgreen + ports: + -8080:8080 + restart: always + environment: + DATASOURCE_URL_RDS=${DATASOURCE_URL_RDS} + DATASOURCE_USERNAME_RDS=${DATASOURCE_USERNAME_RDS} + DATASOURCE_PASSWORD_RDS=${DATASOURCE_PASSWORD_RDS} + jwt.secret-key=${jwt.secret-key} + aws.credentials.access-key=${aws.credentials.access-key} + aws.credentials.secret-key=${aws.credentials.secret-key} + aws.region.static=${aws.region.static} + aws.s3.bucket=${aws.s3.bucket} + fcm.url=${fcm.url} + TZ=Asia/Seoul + env_file: + - .env + + + +# docker run -d --name server -e TZ=Asia/Seoul -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java index 16a4f23..c5381a2 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java @@ -1,11 +1,12 @@ package com.kimgreen.backend.domain.community.repository; -import com.kimgreen.backend.domain.community.entity.Category; -import com.kimgreen.backend.domain.community.entity.Post; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; + import com.kimgreen.backend.domain.community.entity.Post; + import org.springframework.data.jpa.repository.JpaRepository; + import org.springframework.stereotype.Repository; + + import java.time.LocalDateTime; + import java.util.List; @Repository public interface PostRepository extends JpaRepository { - int countByCategory(Category category); //해당 카테고리에 속한 게시글 수 조회 -} +} \ No newline at end of file From 1ba4ed168d06508ca593f9645baa94fa6020ef7f Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 00:09:33 +0900 Subject: [PATCH 38/72] Update github-action.yml --- .github/workflows/github-action.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index a125f8d..cf3b87b 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -34,14 +34,14 @@ jobs: touch ./security.properties # GitHub-Actions에서 설정한 값을 security.properties 파일에 쓰기 - echo "${{ secrets.PROPERTIES }}" > ./security.properties + echo "${{ secrets.USERNAME }}" > ./security.properties shell: bash - name: create firebase key run: | cd ./src/main/resources touch ./kimgreen-f33e5-firebase-adminsdk-63srz-6817b2eec4.json - echo "${{ secrets.FIREBASE_KEY }}" > ./kimgreen-f33e5-firebase-adminsdk-63srz-6817b2eec4.json + echo "${{ secrets.USERNAME }}" > ./kimgreen-f33e5-firebase-adminsdk-63srz-6817b2eec4.json - name: Build with Gradle run: | @@ -64,6 +64,6 @@ jobs: script: | sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker run -d --name server -e TZ=Asia/Seoul -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen sudo docker image prune -f From e8c7a27dd96d4e2d676513103ddfe609d8b65193 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 01:59:04 +0900 Subject: [PATCH 39/72] Update github-action.yml --- .github/workflows/github-action.yml | 36 ++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index cf3b87b..85c434f 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -16,6 +16,19 @@ on: jobs: CI-CD: runs-on: ubuntu-latest + + # github action 내부에서 쓰는 변 + env: + DATASOURCE_URL_RDS: ${{ secrets.DATASOURCE_URL_RDS }} + DATASOURCE_USERNAME_RDS: ${{ secrets.DATASOURCE_USERNAME_RDS }} + jwt.secret-key: ${{ secrets.jwt.secret-key }} + aws.credentials.access-key: ${{ secrets. aws.credentials.access-key }} + aws.credentials.secret-key: ${{ secrets.aws.credentials.secret-key }} + aws.region.static: ${{ secrets.aws.region.static }} + aws.s3.bucket: ${{ secrets.aws.s3.bucket }} + fcm.url: ${{ secrets.fcm.url }} + + steps: - uses: actions/checkout@v3 - name: Set up JDK 17 @@ -24,18 +37,25 @@ jobs: java-version: '17' distribution: 'temurin' # https://github.com/actions/setup-java - - ## create security.properties - - name: make security.properties + ## create env file + - name: create env file run: | - cd ./src/main/resources + touch .env + echo "${{ secrets.PROPERTIES }}" >> .env + + + + ## delete : create security.properties + ##- name: make security.properties + ##run: | + ##cd ./src/main/resources # security.properties 파일 생성 - touch ./security.properties + ##touch ./security.properties # GitHub-Actions에서 설정한 값을 security.properties 파일에 쓰기 - echo "${{ secrets.USERNAME }}" > ./security.properties - shell: bash + ##echo "${{ secrets.USERNAME }}" > ./security.properties + ##shell: bash - name: create firebase key run: | @@ -64,6 +84,6 @@ jobs: script: | sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker run -d --name server -e TZ=Asia/Seoul -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker-compose up -d sudo docker image prune -f From 0070ed2c613edec4ac670fd65b2f0afa79fc5aef Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 02:35:19 +0900 Subject: [PATCH 40/72] Update github-action.yml --- .github/workflows/github-action.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 85c434f..d6d6c49 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -38,10 +38,10 @@ jobs: distribution: 'temurin' # https://github.com/actions/setup-java ## create env file - - name: create env file - run: | - touch .env - echo "${{ secrets.PROPERTIES }}" >> .env + ##- name: create env file + ##run: | + ##touch .env + ##echo "${{ secrets.PROPERTIES }}" >> .env @@ -84,6 +84,6 @@ jobs: script: | sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker-compose up -d + sudo docker run -d --name server -e TZ=Asia/Seoul -e DATASOURCE_URL_RDS=${{ secrets.DATASOURCE_URL_RDS }} -e DATASOURCE_USERNAME_RDS=${{ secrets.DATASOURCE_USERNAME_RDS }} -e DATASOURCE_PASSWORD_RDS=${{ secrets.DATASOURCE_PASSWORD_RDS }} -e JWT_SECRET_KEY=${{ secrets.JWT_SECRET_KEY }} -e AWS_CREDENTIALS_ACCESS_KEY=${{ secrets.AWS_CREDENTIALS_ACCESS_KEY }} -e AWS_CREDENTIALS_SECRET_KEY=${{ secrets.AWS_CREDENTIALS_SECRET_KEY }} -e AWS_REGION_STATIC=${{ secrets.AWS_REGION_STATIC }} -e AWS_S3_BUCKET=${{ secrets.AWS_S3_BUCKET }} -e FCM_URL=${{ secrets.FCM_URL }} -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen sudo docker image prune -f From ffc429a2c7850b0b6e95a9aa7ac49d66bef767c8 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 02:47:13 +0900 Subject: [PATCH 41/72] Update github-action.yml --- .github/workflows/github-action.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index d6d6c49..93feb6c 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -19,14 +19,14 @@ jobs: # github action 내부에서 쓰는 변 env: - DATASOURCE_URL_RDS: ${{ secrets.DATASOURCE_URL_RDS }} - DATASOURCE_USERNAME_RDS: ${{ secrets.DATASOURCE_USERNAME_RDS }} - jwt.secret-key: ${{ secrets.jwt.secret-key }} - aws.credentials.access-key: ${{ secrets. aws.credentials.access-key }} - aws.credentials.secret-key: ${{ secrets.aws.credentials.secret-key }} - aws.region.static: ${{ secrets.aws.region.static }} - aws.s3.bucket: ${{ secrets.aws.s3.bucket }} - fcm.url: ${{ secrets.fcm.url }} + #DATASOURCE_URL_RDS: ${{ secrets.DATASOURCE_URL_RDS }} + #DATASOURCE_USERNAME_RDS: ${{ secrets.DATASOURCE_USERNAME_RDS }} + #jwt.secret-key: ${{ secrets.jwt.secret-key }} + #aws.credentials.access-key: ${{ secrets. aws.credentials.access-key }} + #aws.credentials.secret-key: ${{ secrets.aws.credentials.secret-key }} + #aws.region.static: ${{ secrets.aws.region.static }} + #aws.s3.bucket: ${{ secrets.aws.s3.bucket }} + #fcm.url: ${{ secrets.fcm.url }} steps: From 4db7770aaec34ab768cfb7b47f3d9c56795800a7 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 02:48:01 +0900 Subject: [PATCH 42/72] Update github-action.yml --- .github/workflows/github-action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 93feb6c..b8e7af4 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest # github action 내부에서 쓰는 변 - env: + #env: #DATASOURCE_URL_RDS: ${{ secrets.DATASOURCE_URL_RDS }} #DATASOURCE_USERNAME_RDS: ${{ secrets.DATASOURCE_USERNAME_RDS }} #jwt.secret-key: ${{ secrets.jwt.secret-key }} From 95b3b045318db6b0772e7e59a0694ad8613321c7 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 11:29:10 +0900 Subject: [PATCH 43/72] Update github-action.yml --- .github/workflows/github-action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index b8e7af4..728d8dd 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -84,6 +84,6 @@ jobs: script: | sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker run -d --name server -e TZ=Asia/Seoul -e DATASOURCE_URL_RDS=${{ secrets.DATASOURCE_URL_RDS }} -e DATASOURCE_USERNAME_RDS=${{ secrets.DATASOURCE_USERNAME_RDS }} -e DATASOURCE_PASSWORD_RDS=${{ secrets.DATASOURCE_PASSWORD_RDS }} -e JWT_SECRET_KEY=${{ secrets.JWT_SECRET_KEY }} -e AWS_CREDENTIALS_ACCESS_KEY=${{ secrets.AWS_CREDENTIALS_ACCESS_KEY }} -e AWS_CREDENTIALS_SECRET_KEY=${{ secrets.AWS_CREDENTIALS_SECRET_KEY }} -e AWS_REGION_STATIC=${{ secrets.AWS_REGION_STATIC }} -e AWS_S3_BUCKET=${{ secrets.AWS_S3_BUCKET }} -e FCM_URL=${{ secrets.FCM_URL }} -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker run -d \--name server \-e TZ=Asia/Seoul \-e DATASOURCE_URL_RDS=${{ secrets.DATASOURCE_URL_RDS }} \-e DATASOURCE_USERNAME_RDS=${{ secrets.DATASOURCE_USERNAME_RDS }} \-e DATASOURCE_PASSWORD_RDS=${{ secrets.DATASOURCE_PASSWORD_RDS }} \-e JWT_SECRET_KEY=${{ secrets.JWT_SECRET_KEY }} \-e AWS_CREDENTIALS_ACCESS_KEY=${{ secrets.AWS_CREDENTIALS_ACCESS_KEY }} \-e AWS_CREDENTIALS_SECRET_KEY=${{ secrets.AWS_CREDENTIALS_SECRET_KEY }} \-e AWS_REGION_STATIC=${{ secrets.AWS_REGION_STATIC }} \-e AWS_S3_BUCKET=${{ secrets.AWS_S3_BUCKET }} \-e FCM_URL=${{ secrets.FCM_URL }} \-p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen sudo docker image prune -f From 1f0e4c4a8a342b6147790ecf1c25eed325c121d6 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 12:46:38 +0900 Subject: [PATCH 44/72] Update github-action.yml --- .github/workflows/github-action.yml | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 728d8dd..13a4f16 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -17,16 +17,7 @@ jobs: CI-CD: runs-on: ubuntu-latest - # github action 내부에서 쓰는 변 - #env: - #DATASOURCE_URL_RDS: ${{ secrets.DATASOURCE_URL_RDS }} - #DATASOURCE_USERNAME_RDS: ${{ secrets.DATASOURCE_USERNAME_RDS }} - #jwt.secret-key: ${{ secrets.jwt.secret-key }} - #aws.credentials.access-key: ${{ secrets. aws.credentials.access-key }} - #aws.credentials.secret-key: ${{ secrets.aws.credentials.secret-key }} - #aws.region.static: ${{ secrets.aws.region.static }} - #aws.s3.bucket: ${{ secrets.aws.s3.bucket }} - #fcm.url: ${{ secrets.fcm.url }} + steps: @@ -38,10 +29,10 @@ jobs: distribution: 'temurin' # https://github.com/actions/setup-java ## create env file - ##- name: create env file - ##run: | - ##touch .env - ##echo "${{ secrets.PROPERTIES }}" >> .env + - name: create env file + run: | + touch .env + echo "${{ secrets.PROPERTIES }}" >> .env @@ -84,6 +75,6 @@ jobs: script: | sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker run -d \--name server \-e TZ=Asia/Seoul \-e DATASOURCE_URL_RDS=${{ secrets.DATASOURCE_URL_RDS }} \-e DATASOURCE_USERNAME_RDS=${{ secrets.DATASOURCE_USERNAME_RDS }} \-e DATASOURCE_PASSWORD_RDS=${{ secrets.DATASOURCE_PASSWORD_RDS }} \-e JWT_SECRET_KEY=${{ secrets.JWT_SECRET_KEY }} \-e AWS_CREDENTIALS_ACCESS_KEY=${{ secrets.AWS_CREDENTIALS_ACCESS_KEY }} \-e AWS_CREDENTIALS_SECRET_KEY=${{ secrets.AWS_CREDENTIALS_SECRET_KEY }} \-e AWS_REGION_STATIC=${{ secrets.AWS_REGION_STATIC }} \-e AWS_S3_BUCKET=${{ secrets.AWS_S3_BUCKET }} \-e FCM_URL=${{ secrets.FCM_URL }} \-p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen + sudo docker-compose up sudo docker image prune -f From bd5d32b9e8de8f71dc454222521a2f721109c666 Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 12:53:44 +0900 Subject: [PATCH 45/72] Update github-action.yml --- .github/workflows/github-action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 13a4f16..8d8fa17 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -75,6 +75,6 @@ jobs: script: | sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker-compose up + sudo docker-compose up -d sudo docker image prune -f From ba835e512ac7c2d4bbc32514d6788e140a89080b Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 13:00:55 +0900 Subject: [PATCH 46/72] Update github-action.yml --- .github/workflows/github-action.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 8d8fa17..08d2974 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -73,6 +73,7 @@ jobs: username: ${{ secrets.USERNAME }} # ec2-user key: ${{ secrets.PRIVATE_KEY }} # .pem script: | + sudo systemctl start docker sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen sudo docker-compose up -d From 04392dae0e58754aa83e0839d07dab8bd21cd5bc Mon Sep 17 00:00:00 2001 From: gol2580 <86960201+gol2580@users.noreply.github.com> Date: Thu, 18 Jan 2024 13:53:26 +0900 Subject: [PATCH 47/72] Update github-action.yml --- .github/workflows/github-action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-action.yml b/.github/workflows/github-action.yml index 08d2974..b60df59 100644 --- a/.github/workflows/github-action.yml +++ b/.github/workflows/github-action.yml @@ -76,6 +76,6 @@ jobs: sudo systemctl start docker sudo docker ps sudo docker pull ${{ secrets.DOCKER_USERNAME }}/kimgreen - sudo docker-compose up -d + docker-compose up -d sudo docker image prune -f From ce0910659c554132be26b9a3a1dcf2dc6b0d4399 Mon Sep 17 00:00:00 2001 From: chae33 Date: Sat, 20 Jan 2024 23:00:11 +0900 Subject: [PATCH 48/72] [fix] merge issue --- .../JwtAuthenticationEntryPoint.java | 6 +- .../member/controller/MemberController.java | 9 +- .../member/dto/Auth/SignUpRequestDto.java | 11 ++- .../member/dto/Member/NicknameRequestDto.java | 12 +++ .../backend/domain/member/entity/Member.java | 15 ++- .../member/entity/MemberProfileImg.java | 11 ++- .../domain/member/service/AuthService.java | 6 +- .../domain/member/service/MemberService.java | 7 +- .../backend/domain/profile/entity/Badge.java | 93 ++++--------------- .../exception/MaxUploadSizeExceeded.java | 4 + 10 files changed, 81 insertions(+), 93 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/member/dto/Member/NicknameRequestDto.java create mode 100644 src/main/java/com/kimgreen/backend/exception/MaxUploadSizeExceeded.java diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java index 8331d6f..3ea05a2 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java @@ -27,9 +27,6 @@ public void commence(HttpServletRequest request, response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json; charset=UTF-8"); - if(exception.equals(EXPIRED)) { - setResponse(response,EXPIRED); - if(exception!=null) { if (exception.equals(EXPIRED)) { setResponse(response,HttpStatus.UNAUTHORIZED.value(),"토큰이 유효하지 않습니다."); @@ -38,6 +35,7 @@ public void commence(HttpServletRequest request, setResponse(response,HttpStatus.NOT_FOUND.value(), "토큰이 없습니다."); } } + } public void setResponse(HttpServletResponse response,int status,String msg) throws IOException{ @@ -48,4 +46,4 @@ public void setResponse(HttpServletResponse response,int status,String msg) thro String newResponse = new ObjectMapper().writeValueAsString(json); response.getWriter().write(newResponse); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java index d293ce8..8142863 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java +++ b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java @@ -2,13 +2,18 @@ import com.kimgreen.backend.domain.member.dto.Auth.DeleteMemberRequestDto; import com.kimgreen.backend.domain.member.dto.Auth.SignUpRequestDto; +import com.kimgreen.backend.domain.member.dto.Member.NicknameRequestDto; import com.kimgreen.backend.domain.member.service.MemberService; import com.kimgreen.backend.response.Response; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; +import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; import static com.kimgreen.backend.response.Message.*; import static com.kimgreen.backend.response.Response.success; @@ -67,4 +72,6 @@ public Response getSettingsInfo() { public Response getMemberInfo() { return success(GET_MEMBER_INFO, memberService.getMemberInfo()); } -} + + +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java index f363b8c..d92e3e1 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java @@ -1,6 +1,7 @@ package com.kimgreen.backend.domain.member.dto.Auth; import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.entity.MemberProfileImg; import com.kimgreen.backend.domain.member.entity.Role; import lombok.AllArgsConstructor; import lombok.Getter; @@ -23,4 +24,12 @@ public Member toMemberEntity(String email, String password, String nickname) { .role(Role.ROLE_USER) .build(); } -} + + public MemberProfileImg toMemberProfileImgEntity(Member member) { + return MemberProfileImg.builder() + .member(member) + .imgUrl("profile.jpg") + .title("basic_profile") + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/NicknameRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/NicknameRequestDto.java new file mode 100644 index 0000000..621cc10 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/NicknameRequestDto.java @@ -0,0 +1,12 @@ +package com.kimgreen.backend.domain.member.dto.Member; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class NicknameRequestDto { + private String nickname; +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java index 9b0c311..20d0fd6 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java +++ b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java @@ -54,16 +54,13 @@ public class Member extends AuditEntity { @Enumerated(EnumType.STRING) private Role role; - - public void changePassword(String newPassword) { - this.password = newPassword; - } - public void changeCommentAlarm(boolean b) { - this.commentAlarm = b; - }public void changeLikeAlarm(boolean b) { + public void changePassword(String newPassword) {this.password = newPassword;} + public void changeCommentAlarm(boolean b) {this.commentAlarm = b;} + /* + public void changeLikeAlarm(boolean b) { this.likeAlarm = b; } - + */ public void changeNickname(String nickname) { this.nickname = nickname; } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/entity/MemberProfileImg.java b/src/main/java/com/kimgreen/backend/domain/member/entity/MemberProfileImg.java index a8d9a23..4dc12b7 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/entity/MemberProfileImg.java +++ b/src/main/java/com/kimgreen/backend/domain/member/entity/MemberProfileImg.java @@ -25,4 +25,13 @@ public class MemberProfileImg extends AuditEntity { //기본이미지 url 넣기 @Column(name="img_url") private String imgUrl; -} + + @Column(name="title") + private String title; + + public void changeProfileImg(String imgUrl,String title) { + this.imgUrl = imgUrl; + this.title = title; + } + +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java index d29e113..898ce2a 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java @@ -9,6 +9,7 @@ import com.kimgreen.backend.domain.member.dto.Auth.TokenDto; import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.entity.RefreshToken; +import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; import com.kimgreen.backend.domain.member.repository.MemberRepository; import com.kimgreen.backend.domain.member.repository.RefreshTokenRepository; import com.kimgreen.backend.domain.profile.entity.Badge; @@ -37,6 +38,7 @@ public class AuthService { private final MemberRepository memberRepository; + private final MemberProfileImgRepository profileImgRepository; private final RefreshTokenRepository refreshTokenRepository; private final BadgeRepository badgeRepository; private final ProfileBadgeRepository profileBadgeRepository; @@ -55,8 +57,6 @@ public void signUp(SignUpRequestDto signUpRequestDto) { String nickname = signUpRequestDto.getName(); validateEmail(email); - - memberRepository.save(signUpRequestDto.toMemberEntity(email, passwordEncoder.encode(password),nickname)); saveMember(signUpRequestDto,email, password, nickname); } @@ -165,4 +165,4 @@ public void saveMember(SignUpRequestDto signUpRequestDto,String email, String pa .build()); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java index 7805699..b2bd76f 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java @@ -20,6 +20,10 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + @Service @RequiredArgsConstructor @@ -37,6 +41,7 @@ public class MemberService { private final PasswordEncoder passwordEncoder; + public Member getCurrentMember() { return memberRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName()); } @@ -144,4 +149,4 @@ public void validatePassword(String getPassword, Member member) { throw new LogInFailurePassword(); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index a110584..5838710 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -16,11 +16,11 @@ public class Badge extends AuditEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "badge_id") + @Column(name="badge_id") private Long memberId; @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "member_id") + @JoinColumn(name="member_id") private Member member; @Column(name="earlybird_count",columnDefinition = "int default 0" ) @@ -29,89 +29,67 @@ public class Badge extends AuditEntity { private boolean earlybirdIsAchieved; @Column(name="mentor_count",columnDefinition = "int default 0") - private int mentorCount; - @Column(name = "mentor_is_achieved", columnDefinition = "boolean default false") + @Column(name="mentor_is_achieved",columnDefinition = "boolean default false") private boolean mentorIsAchieved; - @Column(name = "mentee_count", columnDefinition = "int default 0") + @Column(name="mentee_count",columnDefinition = "int default 0") private int menteeCount; - @Column(name = "mentee_is_achieved", columnDefinition = "boolean default false") + @Column(name="mentee_is_achieved",columnDefinition = "boolean default false") private boolean menteeIsAchieved; - @Column(name = "certification_count", columnDefinition = "int default 0") + @Column(name="certification_count",columnDefinition = "int default 0") private int certificationCount; - @Column(name = "certification_10_is_achieved", columnDefinition = "boolean default false") + @Column(name="certification_10_is_achieved",columnDefinition = "boolean default false") private boolean certification10IsAchieved; - @Column(name = "certification_20_is_achieved", columnDefinition = "boolean default false") + @Column(name="certification_20_is_achieved",columnDefinition = "boolean default false") private boolean certification20IsAchieved; - @Column(name = "certification_50_is_achieved", columnDefinition = "boolean default false") + @Column(name="certification_50_is_achieved",columnDefinition = "boolean default false") private boolean certification50IsAchieved; - @Column(name = "receipt_count", columnDefinition = "int default 0") + @Column(name="receipt_count",columnDefinition = "int default 0") private int receiptCount; - @Column(name = "receipt_3_is_achieved", columnDefinition = "boolean default false") - private boolean receipt3IsAchieved; - @Column(name = "receipt_10_is_achieved", columnDefinition = "boolean default false") @Column(name="receipt_3_is_achieved",columnDefinition = "boolean default false") private boolean receipt3IsAchieved; @Column(name="receipt_10_is_achieved",columnDefinition = "boolean default false") private boolean receipt10IsAchieved; - @Column(name = "reusable_count", columnDefinition = "int default 0") + @Column(name="reusable_count",columnDefinition = "int default 0") private int reusableCount; - @Column(name = "reusable_3_is_achieved", columnDefinition = "boolean default false") - private boolean reusable3IsAchieved; - @Column(name = "reusable_10_is_achieved", columnDefinition = "boolean default false") @Column(name="reusable_3_is_achieved",columnDefinition = "boolean default false") private boolean reusable3IsAchieved; @Column(name="reusable_10_is_achieved",columnDefinition = "boolean default false") private boolean reusable10IsAchieved; - @Column(name = "plastic_count", columnDefinition = "int default 0") + @Column(name="plastic_count",columnDefinition = "int default 0") private int plasticCount; - @Column(name = "plastic_3_is_achieved", columnDefinition = "boolean default false") - private boolean plastic3IsAchieved; - @Column(name = "plastic_10_is_achieved", columnDefinition = "boolean default false") @Column(name="plastic_3_is_achieved",columnDefinition = "boolean default false") private boolean plastic3IsAchieved; @Column(name="plastic_10_is_achieved",columnDefinition = "boolean default false") private boolean plastic10IsAchieved; - @Column(name = "plogging_count", columnDefinition = "int default 0") + @Column(name="plogging_count",columnDefinition = "int default 0") private int ploggingCount; - @Column(name = "plogging_3_is_achieved", columnDefinition = "boolean default false") - private boolean plogging3IsAchieved; - @Column(name = "plogging_10_is_achieved", columnDefinition = "boolean default false") @Column(name="plogging_3_is_achieved",columnDefinition = "boolean default false") private boolean plogging3IsAchieved; @Column(name="plogging_10_is_achieved",columnDefinition = "boolean default false") private boolean plogging10IsAchieved; - @Column(name = "reform_count", columnDefinition = "int default 0") + @Column(name="reform_count",columnDefinition = "int default 0") private int reformCount; - @Column(name = "reform_3_is_achieved", columnDefinition = "boolean default false") - private boolean reform3IsAchieved; - @Column(name = "reform_10_is_achieved", columnDefinition = "boolean default false") @Column(name="reform_3_is_achieved",columnDefinition = "boolean default false") private boolean reform3IsAchieved; @Column(name="reform_10_is_achieved",columnDefinition = "boolean default false") private boolean reform10IsAchieved; - @Column(name = "transport_count", columnDefinition = "int default 0") + @Column(name="transport_count",columnDefinition = "int default 0") private int transportCount; - @Column(name = "transport_3_is_achieved", columnDefinition = "boolean default false") - private boolean transport3IsAchieved; - @Column(name = "transport_10_is_achieved", columnDefinition = "boolean default false") @Column(name="transport_3_is_achieved",columnDefinition = "boolean default false") private boolean transport3IsAchieved; @Column(name="transport_10_is_achieved",columnDefinition = "boolean default false") private boolean transport10IsAchieved; - @Column(name = "etc_count", columnDefinition = "int default 0") + @Column(name="etc_count",columnDefinition = "int default 0") private int etcCount; - @Column(name = "etc_3_is_achieved", columnDefinition = "boolean default false") - private boolean etc3IsAchieved; - @Column(name = "etc_10_is_achieved", columnDefinition = "boolean default false") @Column(name="etc_3_is_achieved",columnDefinition = "boolean default false") private boolean etc3IsAchieved; @Column(name="etc_10_is_achieved",columnDefinition = "boolean default false") @@ -120,44 +98,12 @@ public class Badge extends AuditEntity { @Column(name="sprout_is_achieved", columnDefinition = "boolean default true") private boolean sproutIsAchieved; - @Column(name = "adventurer_is_achieved", columnDefinition = "boolean default false") + @Column(name="adventurer_is_achieved",columnDefinition = "boolean default false") private boolean adventurerIsAchieved; - @Column(name = "golden_is_achieved", columnDefinition = "boolean default false") + @Column(name="golden_is_achieved",columnDefinition = "boolean default false") private boolean goldenIsAchieved; - - String[] columnList = { - "adventurer_is_achieved", - "certification_10_is_achieved", - "certification_20_is_achieved", - "certification_50_is_achieved", - "etc_10_is_achieved", - "etc_20_is_achieved", - "etc_50_is_achieved", - "golden_is_achieved", - "mentee_is_achieved", - "mentor_is_achieved", - "plastic_10_is_achieved", - "plastic_20_is_achieved", - "plastic_50_is_achieved", - "plogging_10_is_achieved", - "plogging_20_is_achieved", - "plogging_50_is_achieved", - "receipt_10_is_achieved", - "receipt_20_is_achieved", - "receipt_50_is_achieved", - "reform_10_is_achieved", - "reform_20_is_achieved", - "reform_50_is_achieved", - "reusable_10_is_achieved", - "reusable_20_is_achieved", - "reusable_50_is_achieved", - "transport_10_is_achieved", - "transport_20_is_achieved", - "transport_50_is_achieved" - }; - public void updateGoldenAchieved() { if(!this.isGoldenIsAchieved()) {this.goldenIsAchieved = true;} } @@ -166,4 +112,5 @@ public void updateGoldenNotAchieved() { } public void updateAdventurerAchieved() {if(!this.isAdventurerIsAchieved()) {this.adventurerIsAchieved = true;}} public void updateAdventurerNotAchieved() {if(this.isAdventurerIsAchieved()) {this.adventurerIsAchieved=false;}} -} + +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/exception/MaxUploadSizeExceeded.java b/src/main/java/com/kimgreen/backend/exception/MaxUploadSizeExceeded.java new file mode 100644 index 0000000..4bfe81d --- /dev/null +++ b/src/main/java/com/kimgreen/backend/exception/MaxUploadSizeExceeded.java @@ -0,0 +1,4 @@ +package com.kimgreen.backend.exception; + +public class MaxUploadSizeExceeded extends RuntimeException{ +} \ No newline at end of file From 070fdf84fa3de6208a57f18ae3b4eafd3e37da90 Mon Sep 17 00:00:00 2001 From: chae33 Date: Sun, 21 Jan 2024 11:53:27 +0900 Subject: [PATCH 49/72] [fix] merge issue --- .../domain/community/service/S3Service.java | 31 ++++++++++++++++--- .../member/controller/AuthController.java | 2 +- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java index c8bca48..2ae32b2 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java @@ -5,6 +5,8 @@ import com.kimgreen.backend.domain.community.entity.Post; import com.kimgreen.backend.domain.community.entity.PostImg; import com.kimgreen.backend.domain.community.repository.PostImgRepository; +import com.kimgreen.backend.domain.member.entity.MemberProfileImg; +import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @@ -18,13 +20,15 @@ @RequiredArgsConstructor public class S3Service { private final PostImgRepository postImgRepository; + private final MemberProfileImgRepository memberProfileImgRepository; private final AmazonS3 amazonS3; @Value("${cloud.aws.s3.bucket}") private String bucket; + //post에 첨부되는 이미지 업로드 public String saveFile(MultipartFile multipartFile) throws IOException { - String originalFilename = multipartFile.getOriginalFilename(); //사용자가 업로드한 파일명 - String createdFilename = createFileName(originalFilename); //겹치지 않게 랜덤 파일명 생성 + String originalFilename = multipartFile.getOriginalFilename(); + String createdFilename = createFileName(originalFilename); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(multipartFile.getSize()); @@ -32,8 +36,25 @@ public String saveFile(MultipartFile multipartFile) throws IOException { amazonS3.putObject(bucket, createdFilename, multipartFile.getInputStream(), metadata); - //return amazonS3.getUrl(bucket, createdFilename).toString(); //key? - return createdFilename; //createdFilename = key : S3URL+key 형식으로 불러오면 됨 + uploadDB(PostImg.builder() + .imgUrl(createdFilename) + .title(originalFilename) + .build()); + return createdFilename; + } + + //프로필 이미지 업로드 + public String saveProfileFile(MultipartFile multipartFile) throws IOException { + String originalFilename = multipartFile.getOriginalFilename(); + String createdFilename = createFileName(originalFilename); + + ObjectMetadata metadata = new ObjectMetadata(); + metadata.setContentLength(multipartFile.getSize()); + metadata.setContentType(multipartFile.getContentType()); + + amazonS3.putObject(bucket, createdFilename, multipartFile.getInputStream(), metadata); + + return createdFilename; } //삭제 @@ -54,4 +75,4 @@ public String getFullUrl(String key) { return amazonS3.getUrl(bucket,key).toString(); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/controller/AuthController.java b/src/main/java/com/kimgreen/backend/domain/member/controller/AuthController.java index 2f75adb..8bae3c6 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/controller/AuthController.java +++ b/src/main/java/com/kimgreen/backend/domain/member/controller/AuthController.java @@ -53,4 +53,4 @@ public Response changePassword(@RequestBody ChangePasswordDto changePasswordDto) return success(CHANGE_PASSWORD_SUCCESS); } -} +} \ No newline at end of file From 6ac353a77a8de3836aad0d4b2887474eeffedeef Mon Sep 17 00:00:00 2001 From: chae33 Date: Tue, 23 Jan 2024 12:55:41 +0900 Subject: [PATCH 50/72] [feat] writePost --- .../community/controller/PostController.java | 14 ++++---- .../community/dto/WritePostRequestDto.java | 7 ++-- ...MultipartJackson2HttpMessageConverter.java | 34 +++++++++++++++++++ .../domain/community/service/PostService.java | 8 ++--- .../kimgreen/backend/response/Message.java | 3 +- 5 files changed, 53 insertions(+), 13 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index 7056452..15e56b6 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -6,6 +6,7 @@ import com.kimgreen.backend.response.Response; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -31,18 +32,19 @@ public class PostController { @Operation(summary = "게시글 작성(인증)") @ResponseStatus(OK) @PostMapping(path="/check", consumes = MULTIPART_FORM_DATA_VALUE) - public Response writeCheckPost(@RequestBody WritePostRequestDto writePostRequestDto, - @RequestPart(name = "files") MultipartFile multipartFiles) throws IOException { //파일 필수 O + public Response writeCheckPost(@RequestPart(name = "jsonData") @Valid WritePostRequestDto writePostRequestDto, + @RequestPart(name = "Files") MultipartFile multipartFiles) throws IOException { //파일 필수 O postService.writeCheckPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); - return success(SUCCESS_TO_WRITE_POST); + return success(SUCCESS_TO_WRITE_CERTIFY_POST); } + @Operation(summary = "게시글 작성(일상)") @ResponseStatus(OK) @PostMapping(path="/daily", consumes = MULTIPART_FORM_DATA_VALUE) - public Response writeDailyPost(@RequestPart(name = "body(json)") WritePostRequestDto writePostRequestDto, - @RequestPart(name = "files", required = false) MultipartFile multipartFiles) throws IOException { //파일 필수 X + public Response writeDailyPost(@RequestPart(name = "jsonData") WritePostRequestDto writePostRequestDto, + @RequestPart(name = "Files", required = false) MultipartFile multipartFiles) throws IOException { //파일 필수 X postService.writeDailyPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); - return success(SUCCESS_TO_WRITE_POST); + return success(SUCCESS_TO_WRITE_DAILY_POST); } } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java index 5742d9a..a1c9557 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java @@ -3,6 +3,7 @@ import com.kimgreen.backend.domain.community.entity.Category; import com.kimgreen.backend.domain.community.entity.Post; import com.kimgreen.backend.domain.community.entity.Tag; +import com.kimgreen.backend.domain.member.entity.Member; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -14,16 +15,18 @@ public class WritePostRequestDto { private String category; private String content; - public Post toCertifyPostEntity(String category, String content) { + public Post toCertifyPostEntity(String category, String content, Member member) { return Post.builder() + .member(member) .category(Category.valueOf(category)) .content(content) .tag(Tag.CERTIFY) .build(); } - public Post toDailyPostEntity(String category, String content) { + public Post toDailyPostEntity(String category, String content, Member member) { return Post.builder() + .member(member) .category(Category.valueOf(category)) .content(content) .tag(Tag.DAILY) diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java b/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java new file mode 100644 index 0000000..b0e9c63 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java @@ -0,0 +1,34 @@ +package com.kimgreen.backend.domain.community.entity; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Type; + +@Component +public class MultipartJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter { + + /** + * Converter for support http request with header Content-Type: multipart/form-data + */ + public MultipartJackson2HttpMessageConverter(ObjectMapper objectMapper) { + super(objectMapper, MediaType.APPLICATION_OCTET_STREAM); + } + + @Override + public boolean canWrite(Class clazz, MediaType mediaType) { + return false; + } + + @Override + public boolean canWrite(Type type, Class clazz, MediaType mediaType) { + return false; + } + + @Override + protected boolean canWrite(MediaType mediaType) { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index d7f1d60..00c2e1d 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -24,14 +24,14 @@ public class PostService { private final PostImgRepository postImgRepository; @Transactional - public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member writer) throws IOException { + public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. // post를 먼저 저장 Post post = postRepository.save(writePostRequestDto.toCertifyPostEntity( writePostRequestDto.getCategory(), - writePostRequestDto.getContent())); + writePostRequestDto.getContent(), member)); //파일을 첨부한 경우 if(multipartFile != null){ @@ -41,14 +41,14 @@ public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFil } @Transactional - public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member writer) throws IOException { + public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. // post를 먼저 저장 Post post = postRepository.save(writePostRequestDto.toDailyPostEntity( writePostRequestDto.getCategory(), - writePostRequestDto.getContent())); + writePostRequestDto.getContent(), member)); //파일을 첨부한 경우 if(multipartFile != null){ diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 08ab46e..825870a 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -9,7 +9,8 @@ public class Message { public static String DELETE_MEMBER_SUCCESS="탈퇴하기 성공했습니다."; - public static String SUCCESS_TO_WRITE_POST="인증 게시글 작성 성공했습니다."; + public static String SUCCESS_TO_WRITE_CERTIFY_POST="인증 게시글 작성 성공했습니다."; + public static String SUCCESS_TO_WRITE_DAILY_POST="일상 게시글 작성 성공했습니다."; public static String CHANGE_NICKNAME_SUCCESS="닉네임 변경하기 성공했습니다."; public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; From c7fe744abc1163d91c31db3a27d61a74e7f6705b Mon Sep 17 00:00:00 2001 From: chae33 Date: Tue, 23 Jan 2024 19:45:02 +0900 Subject: [PATCH 51/72] =?UTF-8?q?[feat]=20getPost=20(=EC=9D=B4=EB=AF=B8?= =?UTF-8?q?=EC=A7=80=20=EC=A0=9C=EC=99=B8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...MultipartJackson2HttpMessageConverter.java | 2 +- .../community/controller/PostController.java | 27 +++++++++- .../community/dto/GetPostInfoResponseDto.java | 39 ++++++++++++++ .../domain/community/entity/Category.java | 4 +- .../community/repository/PostRepository.java | 1 + .../domain/community/service/PostService.java | 54 ++++++++++++------- .../kimgreen/backend/response/Message.java | 3 ++ 7 files changed, 106 insertions(+), 24 deletions(-) rename src/main/java/com/kimgreen/backend/domain/community/{entity => }/MultipartJackson2HttpMessageConverter.java (94%) create mode 100644 src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java b/src/main/java/com/kimgreen/backend/domain/community/MultipartJackson2HttpMessageConverter.java similarity index 94% rename from src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java rename to src/main/java/com/kimgreen/backend/domain/community/MultipartJackson2HttpMessageConverter.java index b0e9c63..09339c3 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java +++ b/src/main/java/com/kimgreen/backend/domain/community/MultipartJackson2HttpMessageConverter.java @@ -1,4 +1,4 @@ -package com.kimgreen.backend.domain.community.entity; +package com.kimgreen.backend.domain.community; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.MediaType; diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index 15e56b6..4de0f28 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -38,7 +38,6 @@ public Response writeCheckPost(@RequestPart(name = "jsonData") @Valid WritePostR return success(SUCCESS_TO_WRITE_CERTIFY_POST); } - @Operation(summary = "게시글 작성(일상)") @ResponseStatus(OK) @PostMapping(path="/daily", consumes = MULTIPART_FORM_DATA_VALUE) @@ -47,4 +46,30 @@ public Response writeDailyPost(@RequestPart(name = "jsonData") WritePostRequestD postService.writeDailyPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); return success(SUCCESS_TO_WRITE_DAILY_POST); } + + @Operation(summary = "게시글 상세 보기") + @ResponseStatus(OK) + @GetMapping("/{postId}") + public Response getPostInfoWithAuthMember(Long postId){ + return success(SUCCESS_TO_GET_POST, postService.getPostInfoWithAuthMember(postId, memberService.getCurrentMember())); + } + +/* @Operation(summary = "Delete post API", description = "put post id what you want to delete.") + @ResponseStatus(OK) + @DeleteMapping() + public Response deletePost(Long postId){ + postService.deletePost(postId, memberService.getCurrentMember()); + return Response.success(SUCCESS_TO_DELETE_POST); + } + @Operation(summary = "Edit post info API", description = "put post info what you want to edit.") + @ResponseStatus(OK) + @PutMapping(consumes = MULTIPART_FORM_DATA_VALUE) + public Response editPostInfo(Long postId, + @Valid @RequestPart(name = "body(json)") WritePostRequestDto editPostInfoRequestDto, + @RequestPart(name = "files", required = false) List multipartFiles){ + postService.editPostInfo(postId, editPostInfoRequestDto, multipartFiles, memberService.getCurrentMember()); + return Response.success(SUCCESS_TO_EDIT_POST); + }*/ + + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java new file mode 100644 index 0000000..7e5cc0e --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java @@ -0,0 +1,39 @@ +package com.kimgreen.backend.domain.community.dto; + +import com.kimgreen.backend.domain.community.entity.Post; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class GetPostInfoResponseDto { + private String writerNickname; + private String writerBadge; + private String content; + private Integer postId; + private String category; + private Integer likeCount; + private Integer commentCount; + private Boolean isLiked; + private Boolean isMine; + private String updatedAt; + + public static GetPostInfoResponseDto from(Post post, Boolean isWriter, Boolean liked, String badge){ + return GetPostInfoResponseDto.builder() + .writerNickname(post.getMember().getNickname()) + .writerBadge(badge) + .content(post.getContent()) + .category(String.valueOf(post.getCategory())) + .likeCount(post.getLikes().size()) + .commentCount(post.getComments().size()) + .isLiked(liked) + .isMine(isWriter) + .updatedAt(String.valueOf(post.getModifiedAt())) + .build(); + } + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/Category.java b/src/main/java/com/kimgreen/backend/domain/community/entity/Category.java index dd356b3..8e4615b 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/Category.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/Category.java @@ -13,10 +13,8 @@ public enum Category { DAILY("일상"); - - private String name; private Category(String name) { this.name=name; } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java index c5381a2..6b800e1 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java @@ -6,6 +6,7 @@ import java.time.LocalDateTime; import java.util.List; + import java.util.Optional; @Repository public interface PostRepository extends JpaRepository { diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index 00c2e1d..cc2cf96 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -1,19 +1,20 @@ package com.kimgreen.backend.domain.community.service; -import com.kimgreen.backend.domain.community.entity.Category; -import com.kimgreen.backend.domain.community.entity.Post; -import com.kimgreen.backend.domain.community.entity.PostImg; +import com.kimgreen.backend.domain.community.dto.GetPostInfoResponseDto; +import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; +import com.kimgreen.backend.domain.community.entity.*; import com.kimgreen.backend.domain.community.repository.PostImgRepository; import com.kimgreen.backend.domain.community.repository.PostRepository; import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; +import com.kimgreen.backend.exception.PostNotFound; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; -import org.springframework.web.multipart.MultipartFile; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; import java.io.IOException; -import java.util.List; @Service @RequiredArgsConstructor @@ -22,46 +23,61 @@ public class PostService { private final S3Service s3Service; private final PostRepository postRepository; private final PostImgRepository postImgRepository; + private final RepresentativeBadgeRepository representativeBadgeRepository; + //게시물 작성 @Transactional public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { - // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, - // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. - // post를 먼저 저장 Post post = postRepository.save(writePostRequestDto.toCertifyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent(), member)); - //파일을 첨부한 경우 if(multipartFile != null){ - // s3에 첨부파일을 저장하고, db에도 post_file을 저장 uploadPostFileList(multipartFile, post); } } @Transactional public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { - // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, - // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. - // post를 먼저 저장 Post post = postRepository.save(writePostRequestDto.toDailyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent(), member)); - //파일을 첨부한 경우 if(multipartFile != null){ - // s3에 첨부파일을 저장하고, db에도 post_file을 저장 uploadPostFileList(multipartFile, post); } } + // 게시글 상세정보 조회 @Transactional - public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { - // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, - // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. + public GetPostInfoResponseDto getPostInfoWithAuthMember(Long postId, Member currentMember) { + Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); + Member member = post.getMember(); + RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(member); + + return GetPostInfoResponseDto.from(post, + isWriter(post, currentMember), + isLiked(post, currentMember), + representativeBadge.getRepresentativeBadge().name); + } + @Transactional(readOnly = true) + public Boolean isWriter(Post post, Member currentMember){ + return post.getMember().getMemberId().equals(currentMember.getMemberId()); + } + + @Transactional(readOnly = true) + public Boolean isLiked(Post post, Member currentMember){ + for(Likes postLike : post.getLikes()){ + if(postLike.getLikeId().equals(currentMember.getMemberId())) return true; + } + return false; + } + + @Transactional + public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { PostImg postFile = postImgRepository.save(PostImg.builder() .imgUrl(s3Service.saveFile(multipartFile)) .title(multipartFile.getOriginalFilename()) diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 825870a..c07d088 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -11,6 +11,9 @@ public class Message { public static String SUCCESS_TO_WRITE_CERTIFY_POST="인증 게시글 작성 성공했습니다."; public static String SUCCESS_TO_WRITE_DAILY_POST="일상 게시글 작성 성공했습니다."; + public static String SUCCESS_TO_GET_POST="게시글 상세 보기 성공했습니다."; + + public static String CHANGE_NICKNAME_SUCCESS="닉네임 변경하기 성공했습니다."; public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; From 1e9204cf316816af616e12915f5bad63a1a37f4b Mon Sep 17 00:00:00 2001 From: chae33 Date: Wed, 17 Jan 2024 23:04:03 +0900 Subject: [PATCH 52/72] [feat] WritePost --- .../community/controller/PostController.java | 42 +++++++++++-- .../community/dto/WritePostRequestDto.java | 24 +++++++ .../backend/domain/community/entity/Post.java | 2 +- .../community/repository/PostRepository.java | 2 +- .../domain/community/service/PostService.java | 63 +++++++++++++++++++ .../domain/community/service/S3Service.java | 5 +- .../backend/domain/profile/entity/Badge.java | 2 +- .../kimgreen/backend/response/Message.java | 3 + 8 files changed, 133 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index a21d730..7056452 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -1,14 +1,48 @@ package com.kimgreen.backend.domain.community.controller; +import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; +import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.community.service.PostService; +import com.kimgreen.backend.response.Response; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; + +import static com.kimgreen.backend.response.Message.*; +import static com.kimgreen.backend.response.Response.*; +import static org.springframework.http.HttpStatus.OK; +import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; + @Tag(name = "Post") @RestController +@RequiredArgsConstructor @RequestMapping(value="/post") + public class PostController { -} + private final PostService postService; + private final MemberService memberService; + + @Operation(summary = "게시글 작성(인증)") + @ResponseStatus(OK) + @PostMapping(path="/check", consumes = MULTIPART_FORM_DATA_VALUE) + public Response writeCheckPost(@RequestBody WritePostRequestDto writePostRequestDto, + @RequestPart(name = "files") MultipartFile multipartFiles) throws IOException { //파일 필수 O + postService.writeCheckPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); + return success(SUCCESS_TO_WRITE_POST); + } + + @Operation(summary = "게시글 작성(일상)") + @ResponseStatus(OK) + @PostMapping(path="/daily", consumes = MULTIPART_FORM_DATA_VALUE) + public Response writeDailyPost(@RequestPart(name = "body(json)") WritePostRequestDto writePostRequestDto, + @RequestPart(name = "files", required = false) MultipartFile multipartFiles) throws IOException { //파일 필수 X + postService.writeDailyPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); + return success(SUCCESS_TO_WRITE_POST); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java new file mode 100644 index 0000000..d76c91b --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java @@ -0,0 +1,24 @@ +package com.kimgreen.backend.domain.community.dto; + +import com.kimgreen.backend.domain.community.entity.Category; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.Tag; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class WritePostRequestDto { + private String category; + private String content; + + public Post toPostEntity(String category, String content) { + return Post.builder() + .category(Category.valueOf(category)) + .content(content) + .tag(Tag.DAILY) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java index 3af4d6a..371973e 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java @@ -9,6 +9,7 @@ import lombok.NoArgsConstructor; import java.util.ArrayList; +import java.util.Calendar; import java.util.List; @Getter @@ -45,5 +46,4 @@ public class Post extends AuditEntity { private Category category; @Enumerated(EnumType.STRING) private Tag tag; - } diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java index 255f43a..316fab2 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java @@ -1,5 +1,6 @@ package com.kimgreen.backend.domain.community.repository; +import com.kimgreen.backend.domain.community.entity.Category; import com.kimgreen.backend.domain.community.entity.Post; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @@ -9,5 +10,4 @@ @Repository public interface PostRepository extends JpaRepository { - } diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index 4ad8a65..342e49a 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -1,7 +1,70 @@ package com.kimgreen.backend.domain.community.service; +import com.kimgreen.backend.domain.community.entity.Category; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.PostImg; +import com.kimgreen.backend.domain.community.repository.PostImgRepository; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.member.entity.Member; +import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.util.List; @Service +@RequiredArgsConstructor public class PostService { + + private final S3Service s3Service; + private final PostRepository postRepository; + private final PostImgRepository postImgRepository; + + @Transactional + public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member writer) throws IOException { + // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, + // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. + + // post를 먼저 저장 + Post post = postRepository.save(writePostRequestDto.toPostEntity( + writePostRequestDto.getCategory(), + writePostRequestDto.getContent())); + + //파일을 첨부한 경우 + if(multipartFile != null){ + // s3에 첨부파일을 저장하고, db에도 post_file을 저장 + uploadPostFileList(multipartFile, post); + } + } + + @Transactional + public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member writer) throws IOException { + // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, + // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. + + // post를 먼저 저장 + Post post = postRepository.save(writePostRequestDto.toPostEntity( + writePostRequestDto.getCategory(), + writePostRequestDto.getContent())); + + //파일을 첨부한 경우 + if(multipartFile != null){ + // s3에 첨부파일을 저장하고, db에도 post_file을 저장 + uploadPostFileList(multipartFile, post); + } + } + + @Transactional + public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { + // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, + // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. + + PostImg postFile = postImgRepository.save(PostImg.builder() + .imgUrl(s3Service.saveFile(multipartFile)) + .title(multipartFile.getOriginalFilename()) + .post(post).build()); + } } diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java index 90f4741..8344db7 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java @@ -27,8 +27,8 @@ public class S3Service { //post에 첨부되는 이미지 업로드 public String saveFile(MultipartFile multipartFile) throws IOException { - String originalFilename = multipartFile.getOriginalFilename(); - String createdFilename = createFileName(originalFilename); + String originalFilename = multipartFile.getOriginalFilename(); //사용자가 업로드한 파일명 + String createdFilename = createFileName(originalFilename); //겹치지 않게 랜덤 파일명 생성 ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(multipartFile.getSize()); @@ -69,7 +69,6 @@ public String createFileName(String fileName) { String fileExtension = fileName.substring(fileName.lastIndexOf(".")); return UUID.randomUUID().toString()+fileExtension; } - //실제 주소 얻기 public String getFullUrl(String key) { return amazonS3.getUrl(bucket,key).toString(); diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index f1d7557..5838710 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -113,4 +113,4 @@ public void updateGoldenNotAchieved() { public void updateAdventurerAchieved() {if(!this.isAdventurerIsAchieved()) {this.adventurerIsAchieved = true;}} public void updateAdventurerNotAchieved() {if(this.isAdventurerIsAchieved()) {this.adventurerIsAchieved=false;}} -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index ed44f04..a7ed786 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -24,4 +24,7 @@ public class Message { public static String DELETE_COMMENT_SUCCESS="댓글 삭제 성공했습니다."; public static String GET_COMMENT_SUCCESS="댓글 목록을 불러오는데 성공하였습니다."; + + public static String SUCCESS_TO_WRITE_POST="인증 게시글 작성 성공했습니다."; + } From 059a277398351795265852c2e72ddb27f108e6c5 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 14:39:28 +0900 Subject: [PATCH 53/72] [feat] changeNickname & changeProfileImg --- .../Authentication/JwtAuthenticationEntryPoint.java | 2 +- .../domain/community/dto/WritePostRequestDto.java | 10 +++++++++- .../backend/domain/community/service/PostService.java | 4 ++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java index ef3e37d..3ea05a2 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java @@ -46,4 +46,4 @@ public void setResponse(HttpServletResponse response,int status,String msg) thro String newResponse = new ObjectMapper().writeValueAsString(json); response.getWriter().write(newResponse); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java index d76c91b..5742d9a 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java @@ -14,7 +14,15 @@ public class WritePostRequestDto { private String category; private String content; - public Post toPostEntity(String category, String content) { + public Post toCertifyPostEntity(String category, String content) { + return Post.builder() + .category(Category.valueOf(category)) + .content(content) + .tag(Tag.CERTIFY) + .build(); + } + + public Post toDailyPostEntity(String category, String content) { return Post.builder() .category(Category.valueOf(category)) .content(content) diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index 342e49a..d7f1d60 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -29,7 +29,7 @@ public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFil // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. // post를 먼저 저장 - Post post = postRepository.save(writePostRequestDto.toPostEntity( + Post post = postRepository.save(writePostRequestDto.toCertifyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent())); @@ -46,7 +46,7 @@ public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFil // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. // post를 먼저 저장 - Post post = postRepository.save(writePostRequestDto.toPostEntity( + Post post = postRepository.save(writePostRequestDto.toDailyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent())); From c606731e136c5e949cdd8d4dc3d4d44d9a633f7b Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 17:35:28 +0900 Subject: [PATCH 54/72] [feat] getSettingInfo --- .../kimgreen/backend/domain/BadgeList.java | 2 +- .../domain/community/service/S3Service.java | 125 ++++++++---------- .../member/controller/MemberController.java | 5 +- .../dto/Member/SettingInfoResponseDto.java | 6 + .../domain/member/service/AuthService.java | 2 +- .../domain/member/service/MemberService.java | 2 +- .../domain/profile/entity/ProfileBadge.java | 2 +- .../profile/entity/RepresentativeBadge.java | 2 +- .../profile/repository/BadgeRepository.java | 2 +- .../repository/ProfileBadgeRepository.java | 2 +- 10 files changed, 68 insertions(+), 82 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/BadgeList.java b/src/main/java/com/kimgreen/backend/domain/BadgeList.java index 0e5d50b..ed189ce 100644 --- a/src/main/java/com/kimgreen/backend/domain/BadgeList.java +++ b/src/main/java/com/kimgreen/backend/domain/BadgeList.java @@ -57,4 +57,4 @@ private BadgeList(String name, int goal, String url,String content, int number) this.content = content; } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java index 8344db7..ed189ce 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java @@ -1,77 +1,60 @@ -package com.kimgreen.backend.domain.community.service; - -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.model.ObjectMetadata; -import com.kimgreen.backend.domain.community.entity.Post; -import com.kimgreen.backend.domain.community.entity.PostImg; -import com.kimgreen.backend.domain.community.repository.PostImgRepository; -import com.kimgreen.backend.domain.member.entity.MemberProfileImg; -import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; -import java.net.URL; -import java.util.UUID; - -@Service -@RequiredArgsConstructor -public class S3Service { - private final PostImgRepository postImgRepository; - private final MemberProfileImgRepository memberProfileImgRepository; - private final AmazonS3 amazonS3; - @Value("${cloud.aws.s3.bucket}") - private String bucket; - - //post에 첨부되는 이미지 업로드 - public String saveFile(MultipartFile multipartFile) throws IOException { - String originalFilename = multipartFile.getOriginalFilename(); //사용자가 업로드한 파일명 - String createdFilename = createFileName(originalFilename); //겹치지 않게 랜덤 파일명 생성 - - ObjectMetadata metadata = new ObjectMetadata(); - metadata.setContentLength(multipartFile.getSize()); - metadata.setContentType(multipartFile.getContentType()); - - amazonS3.putObject(bucket, createdFilename, multipartFile.getInputStream(), metadata); - - uploadDB(PostImg.builder() - .imgUrl(createdFilename) - .title(originalFilename) - .build()); - return createdFilename; +package com.kimgreen.backend.domain; + +public enum BadgeList { + BLANK("","",1), + MENTOR("그린 멘토",5,"mentor.png","질문카테고리 댓글 5회 이상",2), + MENTEE("그린 멘티",5,"mentee.png","질문 카테고리 글 작성 5회 이상",3), + EARLYBIRD("얼리버드",3,"earlybird.png","9시 이전에 인증글 3회이상 작성",4), + NORANG("김노랑",10,"norang.png","인증글 10회 이상 작성",5), + YEONDU("김연두",20,"yeondu.png","인증글 20회 이상 작성",6), + GREEN("김그린",50,"green.png","인증글 50회 이상 작성",7), + RECEIPT_3("영수증도 전자로","electronic_receipt.png","전자영수증 발급 인증글 3회 이상",8), + RECEIPT_10("디지털 환경 지킴이",10,"digital_protector.png","전자영수증 발급 인증글 10회 이상",9), + REUSABLE_3("re: user",3,"re_user.png","리유저블 활동 인증글 3회 이상",10), + REUSABLE_10("re: 마스터",10,"re_master.png","리유저블 활동 인증글 10회 이상",11), + PLASTIC_3("자연과 친구하기",3,"eco_friend.png","플라스틱 프리 인증글 3회 이상",12), + PLASTIC_10("자연과 물아일체",10,"eco_one.png","플라스틱 프리 인증글 10회 이상",13), + PLOGGING_3("자연 속에 만 보 추구",3,"jamanchu.png","플로깅 인증글 3회 이상",14), + PLOGGING_10("클린로드의 개척자",10,"clean_road.png","플로깅 인증글 10회 이상",15), + REFORM_3("손재주 아티스트",3,"artist.png","리폼 인증글 3회 이상",16), + REFORM_10("친환경 대가",10,"eco_master.png","리폼 인증글 10회 이상",17), + TRANSPORT_3("탄소 헤이터",3,"C_hater.png","대중교통, 자전거 인증글 3회 이상",18), + TRANSPORT_10("지구 세이버",10,"earth_saver.png","대중교통, 자전거 인증글 10회 이상",19), + ETC_3("아마추어 기타리스트",3,"amateur_guitarist.png","기타 인증글 3회 이상",20), + ETC_10("프로 기타리스트",10,"pro_guitarist.png","기타 인증글 10회 이상",21), + ADVENTURER("환경 모험가","adventurer.png","각 카테고리별 인증글 1회 이상",22), + SPROUT("새싹 김그린","eco_friend.png","튜토리얼 1회 열람",23), + //DOCTOR("김그린 박사","doctor.png",23), + GOLDEN_KIMGREEN("황금 김그린","golden_kimgreen.png","모든 뱃지 획득",24); + + public String name; + public int goal; + public String url; + public String content; + public int number; + + + private BadgeList(String name, int goal,int number) { + this.name = name; + this.goal = goal; } - - //프로필 이미지 업로드 - public String saveProfileFile(MultipartFile multipartFile) throws IOException { - String originalFilename = multipartFile.getOriginalFilename(); - String createdFilename = createFileName(originalFilename); - - ObjectMetadata metadata = new ObjectMetadata(); - metadata.setContentLength(multipartFile.getSize()); - metadata.setContentType(multipartFile.getContentType()); - - amazonS3.putObject(bucket, createdFilename, multipartFile.getInputStream(), metadata); - - return createdFilename; + private BadgeList(String name, String content,int number) { + this.name = name; + this.content = content; } - - //삭제 - public void delete(String url) { - amazonS3.deleteObject(bucket, url); + private BadgeList(String name,int number) { + this.name = name; } - //db에 저장 - 필요없으면 삭제 O - public void uploadDB(PostImg postImg) {postImgRepository.save(postImg);} - - //랜덤이름 생성 - public String createFileName(String fileName) { - String fileExtension = fileName.substring(fileName.lastIndexOf(".")); - return UUID.randomUUID().toString()+fileExtension; + private BadgeList(String name, String url,String content, int number) { + this.name = name; + this.url = url; + this.content = content; } - //실제 주소 얻기 - public String getFullUrl(String key) { - return amazonS3.getUrl(bucket,key).toString(); + private BadgeList(String name, int goal, String url,String content, int number) { + this.name = name; + this.goal = goal; + this.url = url; + this.content = content; } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java index 0e34e71..5debf10 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java +++ b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java @@ -71,7 +71,4 @@ public Response getSettingsInfo() { @GetMapping("/profile-name") public Response getMemberInfo() { return success(GET_MEMBER_INFO, memberService.getMemberInfo()); - } - - -} + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java index ad412ac..899f818 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java @@ -12,7 +12,13 @@ public class SettingInfoResponseDto { private String nickname; private String profileImg; + private String profileBadge; private String profileBadgeImg; private boolean commentAgreement; + + private String badge; + private String badgeImg; + private boolean commentAlarm; + private boolean likeAlarm; } diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java index f425f33..0e057e3 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java @@ -174,4 +174,4 @@ public void saveMember(SignUpRequestDto signUpRequestDto,String email, String pa .build()); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java index 8bee92e..9ec4fb9 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/MemberService.java @@ -155,4 +155,4 @@ public void validatePassword(String getPassword, Member member) { throw new LogInFailurePassword(); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java index 0261502..82eceeb 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/ProfileBadge.java @@ -49,4 +49,4 @@ public void changeProfileBadge(List badgeList) { this.profileBadge_5 = badgeList.get(4); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java index a58a430..080d5e2 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/RepresentativeBadge.java @@ -39,4 +39,4 @@ public void changeRepBadge(String badge) { } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java b/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java index f189e77..be2daac 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/repository/BadgeRepository.java @@ -10,4 +10,4 @@ public interface BadgeRepository extends JpaRepository { public void deleteByMember(Member member); public Badge findByMember(Member member); -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java b/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java index 8accfa1..4ec640c 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/repository/ProfileBadgeRepository.java @@ -10,4 +10,4 @@ public interface ProfileBadgeRepository extends JpaRepository { public void deleteByMember(Member member); public ProfileBadge findByMember(Member member); -} +} \ No newline at end of file From 9f8732f701847442bfd23c2aa7a5c46a8406a889 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 19:17:09 +0900 Subject: [PATCH 55/72] [feat] getMemberInfo --- .../backend/domain/member/controller/MemberController.java | 3 ++- src/main/java/com/kimgreen/backend/response/Message.java | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java index 5debf10..962e6cb 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java +++ b/src/main/java/com/kimgreen/backend/domain/member/controller/MemberController.java @@ -71,4 +71,5 @@ public Response getSettingsInfo() { @GetMapping("/profile-name") public Response getMemberInfo() { return success(GET_MEMBER_INFO, memberService.getMemberInfo()); - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index a7ed786..016a0f6 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -26,5 +26,8 @@ public class Message { public static String SUCCESS_TO_WRITE_POST="인증 게시글 작성 성공했습니다."; - + public static String CHANGE_NICKNAME_SUCCESS="닉네임 변경하기 성공했습니다."; + public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; + public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; + public static String GET_MEMBER_INFO="사용자 별명 불러오기 성공했습니다."; } From 2c81fc47b7900e1d55d6156d4c586325e756f897 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 11 Jan 2024 21:11:52 +0900 Subject: [PATCH 56/72] [fix] changeRepresentativeBadge - Exception --- .../backend/domain/profile/controller/badgeController.java | 2 +- src/main/java/com/kimgreen/backend/response/Advice.java | 4 ++-- src/main/java/com/kimgreen/backend/response/Message.java | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java index c81949a..333e237 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/controller/badgeController.java @@ -49,4 +49,4 @@ public Response getCollectedBadgeInfo() { public Response getNotCollectedBadgeInfo() { return success(GET_NOT_COLLECTED_BADGE_INFO,badgeService.getNotCollectedBadgeInfo()); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Advice.java b/src/main/java/com/kimgreen/backend/response/Advice.java index 04db0db..58cd0f6 100644 --- a/src/main/java/com/kimgreen/backend/response/Advice.java +++ b/src/main/java/com/kimgreen/backend/response/Advice.java @@ -14,7 +14,7 @@ public class Advice { @ResponseStatus(HttpStatus.CONFLICT) public Response DuplicateEmailResponse() { return Response.failure(HttpStatus.CONFLICT, "중복 이메일입니다."); -} + } @ExceptionHandler(LogInFailureEmail.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @@ -63,4 +63,4 @@ public Response LogInRequiredResponse() { return Response.failure(HttpStatus.NOT_FOUND, "토큰이 존재하지 않습니다. 로그인 후 이용해주세요."); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 016a0f6..5c7bbc8 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -30,4 +30,7 @@ public class Message { public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; public static String GET_MEMBER_INFO="사용자 별명 불러오기 성공했습니다."; + public static String CHANGE_REPRESENTATIVE_BADGE_SUCCESS="대표뱃지 설정 성공했습니다."; + + } From 6ccb8f77c49c3e456f5a01ea5de5cfe7d72cd7aa Mon Sep 17 00:00:00 2001 From: gol2580 Date: Fri, 12 Jan 2024 14:16:47 +0900 Subject: [PATCH 57/72] [feat] getCollectedBadge --- .../profile/dto/Badge/CollectedBadgeResponseDto.java | 1 - .../backend/domain/profile/service/BadgeService.java | 10 +++++----- .../java/com/kimgreen/backend/response/Message.java | 4 ++-- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java index 1e33a47..0b8880c 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java @@ -16,4 +16,3 @@ public class CollectedBadgeResponseDto { private String badgeImg; } - diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java index 3811f8a..a1b020e 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/BadgeService.java @@ -114,7 +114,7 @@ public void updateBadeInfos(Badge badge) { } if(badge.getEtcCount()>=1 && badge.getReformCount()>=1 && badge.getReceiptCount()>=1 && badge.getReusableCount()>=1 - && badge.getPlasticCount()>=1 && badge.getPloggingCount()>=1 && badge.getTransportCount()>=1) { + && badge.getPlasticCount()>=1 && badge.getPloggingCount()>=1 && badge.getTransportCount()>=1) { badge.updateAdventurerAchieved(); } else { badge.updateAdventurerNotAchieved(); @@ -127,9 +127,9 @@ public List toEnumList(List badgeList) { List returnList = new ArrayList<>(); for(String badge: badgeList) { returnList.add(Arrays.stream(BadgeList.values()) - .filter(v->v.name().equals(badge)) - .findAny() - .orElseThrow()); + .filter(v->v.name().equals(badge)) + .findAny() + .orElseThrow()); } return returnList; @@ -228,4 +228,4 @@ public Map getCountMap(Map badgeMap,Badge } return map; } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 5c7bbc8..4e0a127 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -31,6 +31,6 @@ public class Message { public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; public static String GET_MEMBER_INFO="사용자 별명 불러오기 성공했습니다."; public static String CHANGE_REPRESENTATIVE_BADGE_SUCCESS="대표뱃지 설정 성공했습니다."; - - + public static String CHANGE_PROFILE_BADGE_SUCCESS="프로필뱃지 선택 성공했습니다."; + public static String GET_COLLECTED_BADGE_INFO="획득뱃지 상세정보 불러오기 성공했습니다."; } From a9bf22483a01912c1aa3fb321351e4ad1379490b Mon Sep 17 00:00:00 2001 From: gol2580 Date: Fri, 12 Jan 2024 16:49:34 +0900 Subject: [PATCH 58/72] [feat] get NotCollectedBadge --- .../dto/Badge/NotCollectedBadgeResponseDto.java | 2 +- .../kimgreen/backend/domain/profile/entity/Badge.java | 2 +- .../java/com/kimgreen/backend/response/Message.java | 11 +---------- 3 files changed, 3 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java index 6df3025..2b053e6 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/NotCollectedBadgeResponseDto.java @@ -18,4 +18,4 @@ public class NotCollectedBadgeResponseDto { private int goal; -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index 5838710..f1d7557 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -113,4 +113,4 @@ public void updateGoldenNotAchieved() { public void updateAdventurerAchieved() {if(!this.isAdventurerIsAchieved()) {this.adventurerIsAchieved = true;}} public void updateAdventurerNotAchieved() {if(this.isAdventurerIsAchieved()) {this.adventurerIsAchieved=false;}} -} \ No newline at end of file +} diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 4e0a127..e4a785b 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -24,13 +24,4 @@ public class Message { public static String DELETE_COMMENT_SUCCESS="댓글 삭제 성공했습니다."; public static String GET_COMMENT_SUCCESS="댓글 목록을 불러오는데 성공하였습니다."; - - public static String SUCCESS_TO_WRITE_POST="인증 게시글 작성 성공했습니다."; - public static String CHANGE_NICKNAME_SUCCESS="닉네임 변경하기 성공했습니다."; - public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; - public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; - public static String GET_MEMBER_INFO="사용자 별명 불러오기 성공했습니다."; - public static String CHANGE_REPRESENTATIVE_BADGE_SUCCESS="대표뱃지 설정 성공했습니다."; - public static String CHANGE_PROFILE_BADGE_SUCCESS="프로필뱃지 선택 성공했습니다."; - public static String GET_COLLECTED_BADGE_INFO="획득뱃지 상세정보 불러오기 성공했습니다."; -} +} \ No newline at end of file From 13e4ac56d380c0d62d1fd8cef33eb80ba4408ec7 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Sat, 13 Jan 2024 13:43:16 +0900 Subject: [PATCH 59/72] [fix] get Badges : sort, update --- .../backend/domain/community/service/CommentService.java | 2 +- .../domain/profile/dto/Badge/CollectedBadgeResponseDto.java | 1 + .../java/com/kimgreen/backend/domain/profile/entity/Badge.java | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java b/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java index dbb24f5..bd0a0a7 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java @@ -85,4 +85,4 @@ public List getComment(Long postId){ return commentList; } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java index 0b8880c..1e33a47 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Badge/CollectedBadgeResponseDto.java @@ -16,3 +16,4 @@ public class CollectedBadgeResponseDto { private String badgeImg; } + diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index f1d7557..5838710 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -113,4 +113,4 @@ public void updateGoldenNotAchieved() { public void updateAdventurerAchieved() {if(!this.isAdventurerIsAchieved()) {this.adventurerIsAchieved = true;}} public void updateAdventurerNotAchieved() {if(this.isAdventurerIsAchieved()) {this.adventurerIsAchieved=false;}} -} +} \ No newline at end of file From 18b10c787bf1d0f6ac522a32c7fe2a808f819e0b Mon Sep 17 00:00:00 2001 From: gol2580 Date: Tue, 16 Jan 2024 14:53:35 +0900 Subject: [PATCH 60/72] [fix] fix token error message --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 5c7d47c..6523051 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,4 +17,4 @@ ENTRYPOINT ["java", "-jar", "/app.jar"] # 3. docker hub에 push # docker push gol2580/kimgreen -# push test +# push test \ No newline at end of file From 10a550405fbee857241102adaeb77ed091faa553 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Wed, 17 Jan 2024 11:59:29 +0900 Subject: [PATCH 61/72] =?UTF-8?q?[fix]=20LikeAlarm=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/kimgreen/backend/domain/member/entity/Member.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java index fdce1ad..20d0fd6 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java +++ b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java @@ -63,4 +63,4 @@ public void changeLikeAlarm(boolean b) { */ public void changeNickname(String nickname) { this.nickname = nickname; } -} +} \ No newline at end of file From a76bc0607412b27e2f16b9d9fb56e59f504b3cf2 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Wed, 17 Jan 2024 13:43:15 +0900 Subject: [PATCH 62/72] [feat] postReport --- .../domain/member/dto/Member/SettingInfoResponseDto.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java index 899f818..a116779 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/SettingInfoResponseDto.java @@ -12,13 +12,7 @@ public class SettingInfoResponseDto { private String nickname; private String profileImg; - private String profileBadge; private String profileBadgeImg; private boolean commentAgreement; - - private String badge; - private String badgeImg; - private boolean commentAlarm; - private boolean likeAlarm; -} +} \ No newline at end of file From 7f09cf6835711f1dcb07ad034378dba649bfc130 Mon Sep 17 00:00:00 2001 From: gol2580 Date: Thu, 18 Jan 2024 02:04:07 +0900 Subject: [PATCH 63/72] [fix] docker-compose.yml --- docker-compose.yml | 2 +- .../domain/community/repository/PostRepository.java | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 2a6d48c..e4df91e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,4 +21,4 @@ services: -# docker run -d --name server -e TZ=Asia/Seoul -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen +# docker run -d --name server -e TZ=Asia/Seoul -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/kimgreen \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java index 316fab2..14278a6 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java @@ -1,9 +1,11 @@ package com.kimgreen.backend.domain.community.repository; -import com.kimgreen.backend.domain.community.entity.Category; -import com.kimgreen.backend.domain.community.entity.Post; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; + import com.kimgreen.backend.domain.community.entity.Post; + import org.springframework.data.jpa.repository.JpaRepository; + import org.springframework.stereotype.Repository; + + import java.time.LocalDateTime; + import java.util.List; import java.time.LocalDateTime; import java.util.List; From 8fbc786a03cc89384363d49be51d79260317bb71 Mon Sep 17 00:00:00 2001 From: chae33 Date: Sat, 20 Jan 2024 23:00:11 +0900 Subject: [PATCH 64/72] [fix] merge issue --- .../backend/domain/member/dto/Auth/SignUpRequestDto.java | 2 +- .../backend/domain/member/dto/Member/NicknameRequestDto.java | 2 +- .../backend/domain/member/entity/MemberProfileImg.java | 1 - .../com/kimgreen/backend/exception/MaxUploadSizeExceeded.java | 4 ++-- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java index 1395369..d92e3e1 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Auth/SignUpRequestDto.java @@ -32,4 +32,4 @@ public MemberProfileImg toMemberProfileImgEntity(Member member) { .title("basic_profile") .build(); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/NicknameRequestDto.java b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/NicknameRequestDto.java index f99aaab..621cc10 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/dto/Member/NicknameRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/member/dto/Member/NicknameRequestDto.java @@ -9,4 +9,4 @@ @NoArgsConstructor public class NicknameRequestDto { private String nickname; -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/entity/MemberProfileImg.java b/src/main/java/com/kimgreen/backend/domain/member/entity/MemberProfileImg.java index 9d0fe34..0b04093 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/entity/MemberProfileImg.java +++ b/src/main/java/com/kimgreen/backend/domain/member/entity/MemberProfileImg.java @@ -33,5 +33,4 @@ public void changeProfileImg(String imgUrl,String title) { this.imgUrl = imgUrl; this.title = title; } - } diff --git a/src/main/java/com/kimgreen/backend/exception/MaxUploadSizeExceeded.java b/src/main/java/com/kimgreen/backend/exception/MaxUploadSizeExceeded.java index 058d151..21dcbf3 100644 --- a/src/main/java/com/kimgreen/backend/exception/MaxUploadSizeExceeded.java +++ b/src/main/java/com/kimgreen/backend/exception/MaxUploadSizeExceeded.java @@ -1,4 +1,4 @@ package com.kimgreen.backend.exception; -public class MaxUploadSizeExceeded extends RuntimeException{ -} +public class MaxUploadSizeExceeded extends RuntimeException { +} \ No newline at end of file From b77afd6b25fd2c6bc554530b852df49f11d73d74 Mon Sep 17 00:00:00 2001 From: chae33 Date: Sun, 21 Jan 2024 11:53:27 +0900 Subject: [PATCH 65/72] [fix] merge issue --- .../domain/community/service/S3Service.java | 124 ++++++++++-------- 1 file changed, 71 insertions(+), 53 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java index ed189ce..2ae32b2 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java @@ -1,60 +1,78 @@ -package com.kimgreen.backend.domain; - -public enum BadgeList { - BLANK("","",1), - MENTOR("그린 멘토",5,"mentor.png","질문카테고리 댓글 5회 이상",2), - MENTEE("그린 멘티",5,"mentee.png","질문 카테고리 글 작성 5회 이상",3), - EARLYBIRD("얼리버드",3,"earlybird.png","9시 이전에 인증글 3회이상 작성",4), - NORANG("김노랑",10,"norang.png","인증글 10회 이상 작성",5), - YEONDU("김연두",20,"yeondu.png","인증글 20회 이상 작성",6), - GREEN("김그린",50,"green.png","인증글 50회 이상 작성",7), - RECEIPT_3("영수증도 전자로","electronic_receipt.png","전자영수증 발급 인증글 3회 이상",8), - RECEIPT_10("디지털 환경 지킴이",10,"digital_protector.png","전자영수증 발급 인증글 10회 이상",9), - REUSABLE_3("re: user",3,"re_user.png","리유저블 활동 인증글 3회 이상",10), - REUSABLE_10("re: 마스터",10,"re_master.png","리유저블 활동 인증글 10회 이상",11), - PLASTIC_3("자연과 친구하기",3,"eco_friend.png","플라스틱 프리 인증글 3회 이상",12), - PLASTIC_10("자연과 물아일체",10,"eco_one.png","플라스틱 프리 인증글 10회 이상",13), - PLOGGING_3("자연 속에 만 보 추구",3,"jamanchu.png","플로깅 인증글 3회 이상",14), - PLOGGING_10("클린로드의 개척자",10,"clean_road.png","플로깅 인증글 10회 이상",15), - REFORM_3("손재주 아티스트",3,"artist.png","리폼 인증글 3회 이상",16), - REFORM_10("친환경 대가",10,"eco_master.png","리폼 인증글 10회 이상",17), - TRANSPORT_3("탄소 헤이터",3,"C_hater.png","대중교통, 자전거 인증글 3회 이상",18), - TRANSPORT_10("지구 세이버",10,"earth_saver.png","대중교통, 자전거 인증글 10회 이상",19), - ETC_3("아마추어 기타리스트",3,"amateur_guitarist.png","기타 인증글 3회 이상",20), - ETC_10("프로 기타리스트",10,"pro_guitarist.png","기타 인증글 10회 이상",21), - ADVENTURER("환경 모험가","adventurer.png","각 카테고리별 인증글 1회 이상",22), - SPROUT("새싹 김그린","eco_friend.png","튜토리얼 1회 열람",23), - //DOCTOR("김그린 박사","doctor.png",23), - GOLDEN_KIMGREEN("황금 김그린","golden_kimgreen.png","모든 뱃지 획득",24); - - public String name; - public int goal; - public String url; - public String content; - public int number; - - - private BadgeList(String name, int goal,int number) { - this.name = name; - this.goal = goal; +package com.kimgreen.backend.domain.community.service; + +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.model.ObjectMetadata; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.PostImg; +import com.kimgreen.backend.domain.community.repository.PostImgRepository; +import com.kimgreen.backend.domain.member.entity.MemberProfileImg; +import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.net.URL; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +public class S3Service { + private final PostImgRepository postImgRepository; + private final MemberProfileImgRepository memberProfileImgRepository; + private final AmazonS3 amazonS3; + @Value("${cloud.aws.s3.bucket}") + private String bucket; + + //post에 첨부되는 이미지 업로드 + public String saveFile(MultipartFile multipartFile) throws IOException { + String originalFilename = multipartFile.getOriginalFilename(); + String createdFilename = createFileName(originalFilename); + + ObjectMetadata metadata = new ObjectMetadata(); + metadata.setContentLength(multipartFile.getSize()); + metadata.setContentType(multipartFile.getContentType()); + + amazonS3.putObject(bucket, createdFilename, multipartFile.getInputStream(), metadata); + + uploadDB(PostImg.builder() + .imgUrl(createdFilename) + .title(originalFilename) + .build()); + return createdFilename; } - private BadgeList(String name, String content,int number) { - this.name = name; - this.content = content; + + //프로필 이미지 업로드 + public String saveProfileFile(MultipartFile multipartFile) throws IOException { + String originalFilename = multipartFile.getOriginalFilename(); + String createdFilename = createFileName(originalFilename); + + ObjectMetadata metadata = new ObjectMetadata(); + metadata.setContentLength(multipartFile.getSize()); + metadata.setContentType(multipartFile.getContentType()); + + amazonS3.putObject(bucket, createdFilename, multipartFile.getInputStream(), metadata); + + return createdFilename; } - private BadgeList(String name,int number) { - this.name = name; + + //삭제 + public void delete(String url) { + amazonS3.deleteObject(bucket, url); } - private BadgeList(String name, String url,String content, int number) { - this.name = name; - this.url = url; - this.content = content; + //db에 저장 - 필요없으면 삭제 O + public void uploadDB(PostImg postImg) {postImgRepository.save(postImg);} + + //랜덤이름 생성 + public String createFileName(String fileName) { + String fileExtension = fileName.substring(fileName.lastIndexOf(".")); + return UUID.randomUUID().toString()+fileExtension; } - private BadgeList(String name, int goal, String url,String content, int number) { - this.name = name; - this.goal = goal; - this.url = url; - this.content = content; + + //실제 주소 얻기 + public String getFullUrl(String key) { + return amazonS3.getUrl(bucket,key).toString(); } } \ No newline at end of file From 21f55440f34220a35331f9fdcecf513660462d61 Mon Sep 17 00:00:00 2001 From: chae33 Date: Tue, 23 Jan 2024 12:55:41 +0900 Subject: [PATCH 66/72] [feat] writePost --- .../community/controller/PostController.java | 14 ++++---- .../community/dto/WritePostRequestDto.java | 7 ++-- ...MultipartJackson2HttpMessageConverter.java | 34 +++++++++++++++++++ .../domain/community/service/PostService.java | 8 ++--- .../kimgreen/backend/response/Message.java | 4 +++ 5 files changed, 55 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index 7056452..15e56b6 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -6,6 +6,7 @@ import com.kimgreen.backend.response.Response; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -31,18 +32,19 @@ public class PostController { @Operation(summary = "게시글 작성(인증)") @ResponseStatus(OK) @PostMapping(path="/check", consumes = MULTIPART_FORM_DATA_VALUE) - public Response writeCheckPost(@RequestBody WritePostRequestDto writePostRequestDto, - @RequestPart(name = "files") MultipartFile multipartFiles) throws IOException { //파일 필수 O + public Response writeCheckPost(@RequestPart(name = "jsonData") @Valid WritePostRequestDto writePostRequestDto, + @RequestPart(name = "Files") MultipartFile multipartFiles) throws IOException { //파일 필수 O postService.writeCheckPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); - return success(SUCCESS_TO_WRITE_POST); + return success(SUCCESS_TO_WRITE_CERTIFY_POST); } + @Operation(summary = "게시글 작성(일상)") @ResponseStatus(OK) @PostMapping(path="/daily", consumes = MULTIPART_FORM_DATA_VALUE) - public Response writeDailyPost(@RequestPart(name = "body(json)") WritePostRequestDto writePostRequestDto, - @RequestPart(name = "files", required = false) MultipartFile multipartFiles) throws IOException { //파일 필수 X + public Response writeDailyPost(@RequestPart(name = "jsonData") WritePostRequestDto writePostRequestDto, + @RequestPart(name = "Files", required = false) MultipartFile multipartFiles) throws IOException { //파일 필수 X postService.writeDailyPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); - return success(SUCCESS_TO_WRITE_POST); + return success(SUCCESS_TO_WRITE_DAILY_POST); } } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java index 5742d9a..a1c9557 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/WritePostRequestDto.java @@ -3,6 +3,7 @@ import com.kimgreen.backend.domain.community.entity.Category; import com.kimgreen.backend.domain.community.entity.Post; import com.kimgreen.backend.domain.community.entity.Tag; +import com.kimgreen.backend.domain.member.entity.Member; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -14,16 +15,18 @@ public class WritePostRequestDto { private String category; private String content; - public Post toCertifyPostEntity(String category, String content) { + public Post toCertifyPostEntity(String category, String content, Member member) { return Post.builder() + .member(member) .category(Category.valueOf(category)) .content(content) .tag(Tag.CERTIFY) .build(); } - public Post toDailyPostEntity(String category, String content) { + public Post toDailyPostEntity(String category, String content, Member member) { return Post.builder() + .member(member) .category(Category.valueOf(category)) .content(content) .tag(Tag.DAILY) diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java b/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java new file mode 100644 index 0000000..b0e9c63 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java @@ -0,0 +1,34 @@ +package com.kimgreen.backend.domain.community.entity; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Type; + +@Component +public class MultipartJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter { + + /** + * Converter for support http request with header Content-Type: multipart/form-data + */ + public MultipartJackson2HttpMessageConverter(ObjectMapper objectMapper) { + super(objectMapper, MediaType.APPLICATION_OCTET_STREAM); + } + + @Override + public boolean canWrite(Class clazz, MediaType mediaType) { + return false; + } + + @Override + public boolean canWrite(Type type, Class clazz, MediaType mediaType) { + return false; + } + + @Override + protected boolean canWrite(MediaType mediaType) { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index d7f1d60..00c2e1d 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -24,14 +24,14 @@ public class PostService { private final PostImgRepository postImgRepository; @Transactional - public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member writer) throws IOException { + public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. // post를 먼저 저장 Post post = postRepository.save(writePostRequestDto.toCertifyPostEntity( writePostRequestDto.getCategory(), - writePostRequestDto.getContent())); + writePostRequestDto.getContent(), member)); //파일을 첨부한 경우 if(multipartFile != null){ @@ -41,14 +41,14 @@ public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFil } @Transactional - public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member writer) throws IOException { + public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. // post를 먼저 저장 Post post = postRepository.save(writePostRequestDto.toDailyPostEntity( writePostRequestDto.getCategory(), - writePostRequestDto.getContent())); + writePostRequestDto.getContent(), member)); //파일을 첨부한 경우 if(multipartFile != null){ diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index e4a785b..3d83fae 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -7,6 +7,10 @@ public class Message { public static String CHANGE_PASSWORD_SUCCESS="비밀번호 변경하기 성공했습니다."; public static String CHANGE_ALARM_SUCCESS="알림 설정 변경 성공했습니다."; public static String DELETE_MEMBER_SUCCESS="탈퇴하기 성공했습니다."; + + + public static String SUCCESS_TO_WRITE_CERTIFY_POST="인증 게시글 작성 성공했습니다."; + public static String SUCCESS_TO_WRITE_DAILY_POST="일상 게시글 작성 성공했습니다."; public static String CHANGE_NICKNAME_SUCCESS="닉네임 변경하기 성공했습니다."; public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; From 16215085085eaf6a57241e8c5f4e09bd91c95ad6 Mon Sep 17 00:00:00 2001 From: chae33 Date: Tue, 23 Jan 2024 19:45:02 +0900 Subject: [PATCH 67/72] =?UTF-8?q?[feat]=20getPost=20(=EC=9D=B4=EB=AF=B8?= =?UTF-8?q?=EC=A7=80=20=EC=A0=9C=EC=99=B8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...MultipartJackson2HttpMessageConverter.java | 2 +- .../community/controller/PostController.java | 27 +++++++++- .../community/dto/GetPostInfoResponseDto.java | 39 ++++++++++++++ .../domain/community/entity/Category.java | 4 +- .../community/repository/PostRepository.java | 1 + .../domain/community/service/PostService.java | 54 ++++++++++++------- .../kimgreen/backend/response/Message.java | 3 ++ 7 files changed, 106 insertions(+), 24 deletions(-) rename src/main/java/com/kimgreen/backend/domain/community/{entity => }/MultipartJackson2HttpMessageConverter.java (94%) create mode 100644 src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java b/src/main/java/com/kimgreen/backend/domain/community/MultipartJackson2HttpMessageConverter.java similarity index 94% rename from src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java rename to src/main/java/com/kimgreen/backend/domain/community/MultipartJackson2HttpMessageConverter.java index b0e9c63..09339c3 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/MultipartJackson2HttpMessageConverter.java +++ b/src/main/java/com/kimgreen/backend/domain/community/MultipartJackson2HttpMessageConverter.java @@ -1,4 +1,4 @@ -package com.kimgreen.backend.domain.community.entity; +package com.kimgreen.backend.domain.community; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.MediaType; diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index 15e56b6..4de0f28 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -38,7 +38,6 @@ public Response writeCheckPost(@RequestPart(name = "jsonData") @Valid WritePostR return success(SUCCESS_TO_WRITE_CERTIFY_POST); } - @Operation(summary = "게시글 작성(일상)") @ResponseStatus(OK) @PostMapping(path="/daily", consumes = MULTIPART_FORM_DATA_VALUE) @@ -47,4 +46,30 @@ public Response writeDailyPost(@RequestPart(name = "jsonData") WritePostRequestD postService.writeDailyPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); return success(SUCCESS_TO_WRITE_DAILY_POST); } + + @Operation(summary = "게시글 상세 보기") + @ResponseStatus(OK) + @GetMapping("/{postId}") + public Response getPostInfoWithAuthMember(Long postId){ + return success(SUCCESS_TO_GET_POST, postService.getPostInfoWithAuthMember(postId, memberService.getCurrentMember())); + } + +/* @Operation(summary = "Delete post API", description = "put post id what you want to delete.") + @ResponseStatus(OK) + @DeleteMapping() + public Response deletePost(Long postId){ + postService.deletePost(postId, memberService.getCurrentMember()); + return Response.success(SUCCESS_TO_DELETE_POST); + } + @Operation(summary = "Edit post info API", description = "put post info what you want to edit.") + @ResponseStatus(OK) + @PutMapping(consumes = MULTIPART_FORM_DATA_VALUE) + public Response editPostInfo(Long postId, + @Valid @RequestPart(name = "body(json)") WritePostRequestDto editPostInfoRequestDto, + @RequestPart(name = "files", required = false) List multipartFiles){ + postService.editPostInfo(postId, editPostInfoRequestDto, multipartFiles, memberService.getCurrentMember()); + return Response.success(SUCCESS_TO_EDIT_POST); + }*/ + + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java new file mode 100644 index 0000000..7e5cc0e --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java @@ -0,0 +1,39 @@ +package com.kimgreen.backend.domain.community.dto; + +import com.kimgreen.backend.domain.community.entity.Post; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class GetPostInfoResponseDto { + private String writerNickname; + private String writerBadge; + private String content; + private Integer postId; + private String category; + private Integer likeCount; + private Integer commentCount; + private Boolean isLiked; + private Boolean isMine; + private String updatedAt; + + public static GetPostInfoResponseDto from(Post post, Boolean isWriter, Boolean liked, String badge){ + return GetPostInfoResponseDto.builder() + .writerNickname(post.getMember().getNickname()) + .writerBadge(badge) + .content(post.getContent()) + .category(String.valueOf(post.getCategory())) + .likeCount(post.getLikes().size()) + .commentCount(post.getComments().size()) + .isLiked(liked) + .isMine(isWriter) + .updatedAt(String.valueOf(post.getModifiedAt())) + .build(); + } + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/Category.java b/src/main/java/com/kimgreen/backend/domain/community/entity/Category.java index dd356b3..8e4615b 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/Category.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/Category.java @@ -13,10 +13,8 @@ public enum Category { DAILY("일상"); - - private String name; private Category(String name) { this.name=name; } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java index 14278a6..2ab4316 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java @@ -6,6 +6,7 @@ import java.time.LocalDateTime; import java.util.List; + import java.util.Optional; import java.time.LocalDateTime; import java.util.List; diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index 00c2e1d..cc2cf96 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -1,19 +1,20 @@ package com.kimgreen.backend.domain.community.service; -import com.kimgreen.backend.domain.community.entity.Category; -import com.kimgreen.backend.domain.community.entity.Post; -import com.kimgreen.backend.domain.community.entity.PostImg; +import com.kimgreen.backend.domain.community.dto.GetPostInfoResponseDto; +import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; +import com.kimgreen.backend.domain.community.entity.*; import com.kimgreen.backend.domain.community.repository.PostImgRepository; import com.kimgreen.backend.domain.community.repository.PostRepository; import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; +import com.kimgreen.backend.exception.PostNotFound; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; -import org.springframework.web.multipart.MultipartFile; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; import java.io.IOException; -import java.util.List; @Service @RequiredArgsConstructor @@ -22,46 +23,61 @@ public class PostService { private final S3Service s3Service; private final PostRepository postRepository; private final PostImgRepository postImgRepository; + private final RepresentativeBadgeRepository representativeBadgeRepository; + //게시물 작성 @Transactional public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { - // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, - // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. - // post를 먼저 저장 Post post = postRepository.save(writePostRequestDto.toCertifyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent(), member)); - //파일을 첨부한 경우 if(multipartFile != null){ - // s3에 첨부파일을 저장하고, db에도 post_file을 저장 uploadPostFileList(multipartFile, post); } } @Transactional public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { - // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, - // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. - // post를 먼저 저장 Post post = postRepository.save(writePostRequestDto.toDailyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent(), member)); - //파일을 첨부한 경우 if(multipartFile != null){ - // s3에 첨부파일을 저장하고, db에도 post_file을 저장 uploadPostFileList(multipartFile, post); } } + // 게시글 상세정보 조회 @Transactional - public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { - // s3에 파일을 업로드 한 뒤 예외가 발생하면 db는 롤백이 되지만, - // 이미 s3에 저장된 이미지는 삭제되지 않는 문제가 있음. + public GetPostInfoResponseDto getPostInfoWithAuthMember(Long postId, Member currentMember) { + Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); + Member member = post.getMember(); + RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(member); + + return GetPostInfoResponseDto.from(post, + isWriter(post, currentMember), + isLiked(post, currentMember), + representativeBadge.getRepresentativeBadge().name); + } + @Transactional(readOnly = true) + public Boolean isWriter(Post post, Member currentMember){ + return post.getMember().getMemberId().equals(currentMember.getMemberId()); + } + + @Transactional(readOnly = true) + public Boolean isLiked(Post post, Member currentMember){ + for(Likes postLike : post.getLikes()){ + if(postLike.getLikeId().equals(currentMember.getMemberId())) return true; + } + return false; + } + + @Transactional + public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { PostImg postFile = postImgRepository.save(PostImg.builder() .imgUrl(s3Service.saveFile(multipartFile)) .title(multipartFile.getOriginalFilename()) diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 3d83fae..627aaad 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -11,6 +11,9 @@ public class Message { public static String SUCCESS_TO_WRITE_CERTIFY_POST="인증 게시글 작성 성공했습니다."; public static String SUCCESS_TO_WRITE_DAILY_POST="일상 게시글 작성 성공했습니다."; + public static String SUCCESS_TO_GET_POST="게시글 상세 보기 성공했습니다."; + + public static String CHANGE_NICKNAME_SUCCESS="닉네임 변경하기 성공했습니다."; public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; public static String CHANGE_PROFILE_IMG_SUCCESS="프로필 사진 변경하기 성공했습니다."; From 939befc83e4be320885a85e55613b80aac2cd9c5 Mon Sep 17 00:00:00 2001 From: chae33 Date: Mon, 29 Jan 2024 00:06:08 +0900 Subject: [PATCH 68/72] [fix] getPost --- .../community/controller/PostController.java | 50 ++++++++++++------- .../backend/domain/community/entity/Post.java | 5 ++ .../community/service/CommentService.java | 2 +- .../domain/community/service/PostService.java | 40 ++++++++++++--- .../kimgreen/backend/response/Message.java | 10 ++-- .../kimgreen/backend/response/Response.java | 2 +- 6 files changed, 78 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index 4de0f28..be37921 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -1,6 +1,7 @@ package com.kimgreen.backend.domain.community.controller; import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; +import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.service.MemberService; import com.kimgreen.backend.domain.community.service.PostService; import com.kimgreen.backend.response.Response; @@ -32,44 +33,57 @@ public class PostController { @Operation(summary = "게시글 작성(인증)") @ResponseStatus(OK) @PostMapping(path="/check", consumes = MULTIPART_FORM_DATA_VALUE) - public Response writeCheckPost(@RequestPart(name = "jsonData") @Valid WritePostRequestDto writePostRequestDto, - @RequestPart(name = "Files") MultipartFile multipartFiles) throws IOException { //파일 필수 O - postService.writeCheckPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); - return success(SUCCESS_TO_WRITE_CERTIFY_POST); + public Response writeCheckPost(@RequestPart(name = "jsonData") WritePostRequestDto writePostRequestDto, + @RequestPart(name = "File") MultipartFile multipartFile) throws IOException { //파일 필수 O + postService.writeCheckPost(writePostRequestDto, multipartFile, memberService.getCurrentMember()); + return success(WRITE_CERTIFY_POST_SUCCESS); } @Operation(summary = "게시글 작성(일상)") @ResponseStatus(OK) @PostMapping(path="/daily", consumes = MULTIPART_FORM_DATA_VALUE) public Response writeDailyPost(@RequestPart(name = "jsonData") WritePostRequestDto writePostRequestDto, - @RequestPart(name = "Files", required = false) MultipartFile multipartFiles) throws IOException { //파일 필수 X - postService.writeDailyPost(writePostRequestDto, multipartFiles, memberService.getCurrentMember()); - return success(SUCCESS_TO_WRITE_DAILY_POST); + @RequestPart(name = "File", required = false) MultipartFile multipartFile) throws IOException { //파일 필수 X + postService.writeDailyPost(writePostRequestDto, multipartFile, memberService.getCurrentMember()); + return success(WRITE_DAILY_POST_SUCCESS); } @Operation(summary = "게시글 상세 보기") @ResponseStatus(OK) - @GetMapping("/{postId}") + @GetMapping() public Response getPostInfoWithAuthMember(Long postId){ - return success(SUCCESS_TO_GET_POST, postService.getPostInfoWithAuthMember(postId, memberService.getCurrentMember())); + return success(GET_POST_SUCCESS, postService.getPostInfoWithAuthMember(postId, memberService.getCurrentMember())); } -/* @Operation(summary = "Delete post API", description = "put post id what you want to delete.") + @Operation(summary = "게시글 삭제하기") @ResponseStatus(OK) @DeleteMapping() - public Response deletePost(Long postId){ + public Response deletePost(@RequestParam("postId") Long postId){ postService.deletePost(postId, memberService.getCurrentMember()); - return Response.success(SUCCESS_TO_DELETE_POST); + return success(DELETE_POST_SUCCESS); } - @Operation(summary = "Edit post info API", description = "put post info what you want to edit.") + + @Operation(summary = "게시글 수정하기") @ResponseStatus(OK) @PutMapping(consumes = MULTIPART_FORM_DATA_VALUE) public Response editPostInfo(Long postId, - @Valid @RequestPart(name = "body(json)") WritePostRequestDto editPostInfoRequestDto, - @RequestPart(name = "files", required = false) List multipartFiles){ - postService.editPostInfo(postId, editPostInfoRequestDto, multipartFiles, memberService.getCurrentMember()); - return Response.success(SUCCESS_TO_EDIT_POST); - }*/ + @RequestPart(name = "body(json)") WritePostRequestDto editPostInfoRequestDto, + @RequestPart(name = "files", required = false) MultipartFile multipartFile) throws IOException { + + postService.editPost(postId, editPostInfoRequestDto, multipartFile, memberService.getCurrentMember()); + return success(EDIT_POST_SUCCESS); + } + /* @GetMapping("/post/edit/{id}") + public String edit(@PathVariable("id") Long id, Model model) { + BoardDto boardDto = boardService.findById(id); + model.addAttribute("post", boardDto); + return "board/edit.html"; + } + @PutMapping("/post/edit/{id}") + public String update(@PathVariable Long id, BoardUpdateDto requestDto){ + boardService.update(id,requestDto); + return "redirect:/board/list"; + }*/ } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java index 371973e..e142a0a 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java @@ -46,4 +46,9 @@ public class Post extends AuditEntity { private Category category; @Enumerated(EnumType.STRING) private Tag tag; + + public void update(String category, String content) { + this.category = Category.valueOf(category); + this.content = content; + } } diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java b/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java index bd0a0a7..80ac8f6 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java @@ -72,7 +72,7 @@ public List getComment(Long postId){ */ GetCommentDto getCommentDto1 = GetCommentDto.builder() .commentId(comment.getCommentId()) - .writerProfileImg(s3Service.getFullUrl(memberProfileImg.getImgUrl())) + .writerProfileImg(s3Service.getFullUrl(memberProfileImg.getImgUrl())) //프로필이미지 .writerNickname(comment.getMember().getNickname()) .writerBadge(representativeBadge.getRepresentativeBadge().name) .content(comment.getContent()) diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index cc2cf96..10a269b 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -6,21 +6,26 @@ import com.kimgreen.backend.domain.community.repository.PostImgRepository; import com.kimgreen.backend.domain.community.repository.PostRepository; import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.service.MemberService; import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; import com.kimgreen.backend.exception.PostNotFound; +import com.kimgreen.backend.exception.WrongPath; +import com.kimgreen.backend.response.Response; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; +import java.util.ArrayList; @Service @RequiredArgsConstructor public class PostService { private final S3Service s3Service; + private final MemberService memberService; private final PostRepository postRepository; private final PostImgRepository postImgRepository; private final RepresentativeBadgeRepository representativeBadgeRepository; @@ -49,6 +54,13 @@ public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFil uploadPostFileList(multipartFile, post); } } + @Transactional + public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { + PostImg postImg = postImgRepository.save(PostImg.builder() + .imgUrl(s3Service.saveFile(multipartFile)) + .title(multipartFile.getOriginalFilename()) + .post(post).build()); + } // 게시글 상세정보 조회 @Transactional @@ -76,11 +88,27 @@ public Boolean isLiked(Post post, Member currentMember){ return false; } + //게시글 삭제하기 @Transactional - public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { - PostImg postFile = postImgRepository.save(PostImg.builder() - .imgUrl(s3Service.saveFile(multipartFile)) - .title(multipartFile.getOriginalFilename()) - .post(post).build()); + public void deletePost(Long postId, Member currentMember){ + Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); + + postRepository.delete(post); + //postImgRepository.delete(post); + } + + @Transactional + public void editPost(Long postId, WritePostRequestDto editPostInfoRequestDto, MultipartFile multipartFile, Member currentMember) throws IOException { + Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); + + post.update(editPostInfoRequestDto.getCategory(), editPostInfoRequestDto.getContent()); + // 기존 게시글 db을 모두 삭제하는 코드 필요 + + + if(multipartFile != null){ + uploadPostFileList(multipartFile, post); + } + + //for(String fileUrl : fileUrls) s3Service.deleteFile(fileUrl); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index 627aaad..aaaa42b 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -8,11 +8,11 @@ public class Message { public static String CHANGE_ALARM_SUCCESS="알림 설정 변경 성공했습니다."; public static String DELETE_MEMBER_SUCCESS="탈퇴하기 성공했습니다."; - - public static String SUCCESS_TO_WRITE_CERTIFY_POST="인증 게시글 작성 성공했습니다."; - public static String SUCCESS_TO_WRITE_DAILY_POST="일상 게시글 작성 성공했습니다."; - public static String SUCCESS_TO_GET_POST="게시글 상세 보기 성공했습니다."; - + public static String WRITE_CERTIFY_POST_SUCCESS="인증 게시글 작성 성공했습니다."; + public static String WRITE_DAILY_POST_SUCCESS="일상 게시글 작성 성공했습니다."; + public static String GET_POST_SUCCESS="게시글 상세 보기 성공했습니다."; + public static String DELETE_POST_SUCCESS="게시글 삭제하기 성공했습니다."; + public static String EDIT_POST_SUCCESS="게시글 수정하기 성공했습니다."; public static String CHANGE_NICKNAME_SUCCESS="닉네임 변경하기 성공했습니다."; public static String GET_MEMBER_INFO_SETTING_SUCCESS="설정창 정보 불러오기 성공했습니다."; diff --git a/src/main/java/com/kimgreen/backend/response/Response.java b/src/main/java/com/kimgreen/backend/response/Response.java index b7730b3..e2fab75 100644 --- a/src/main/java/com/kimgreen/backend/response/Response.java +++ b/src/main/java/com/kimgreen/backend/response/Response.java @@ -28,7 +28,7 @@ public static Response success(String msg) { return new Response(true,OK.value(), msg,null); } public static Response success(String msg, Object data) { - return new Response(true,OK.value(), msg,data); + return new Response(true,OK.value(), msg, data); } public static Response failure(HttpStatus status,String msg) { From 098d280b34d6a8ce6959c3545361f62ad7b1f34d Mon Sep 17 00:00:00 2001 From: chae33 Date: Mon, 5 Feb 2024 02:22:48 +0900 Subject: [PATCH 69/72] [fix] --- .../config/Security/SecurityConfig.java | 2 +- .../kimgreen/backend/domain/AuditEntity.java | 2 +- .../kimgreen/backend/domain/BadgeList.java | 2 +- .../controller/CommentController.java | 2 +- .../community/controller/LikeController.java | 24 +- .../community/controller/PostController.java | 41 ++-- .../controller/ReportController.java | 4 +- .../community/dto/GetPostInfoResponseDto.java | 23 +- .../backend/domain/community/entity/Post.java | 8 + .../repository/CommentRepository.java | 6 +- .../community/repository/LikeRepository.java | 12 +- .../repository/PostImgRepository.java | 5 +- .../community/repository/PostRepository.java | 22 +- .../community/service/CommentService.java | 9 +- .../domain/community/service/LikeService.java | 38 +++- .../domain/community/service/PostService.java | 209 +++++++++++++++--- .../community/service/ReportService.java | 2 +- .../backend/domain/member/entity/Member.java | 2 + .../domain/member/service/AuthService.java | 17 +- .../profile/controller/profileController.java | 36 ++- .../dto/Calendar/CalendarDetailDto.java | 27 +++ .../Calendar/CalendarDetailRequestDto.java | 15 ++ .../Calendar/CalendarDetailResponseDto.java | 25 +++ .../dto/Calendar/CalendarResponseDto.java | 15 ++ .../profile/dto/Profile/GetProfileDto.java | 43 ++++ .../dto/Profile/GetProfilePostDto.java | 24 ++ .../backend/domain/profile/entity/Badge.java | 6 +- .../RepresentativeBadgeRepository.java | 2 +- .../profile/service/CalendarService.java | 148 ++++++++++++- .../profile/service/ProfileService.java | 113 +++++++++- .../kimgreen/backend/response/Message.java | 11 + 31 files changed, 789 insertions(+), 106 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailRequestDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailResponseDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarResponseDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetProfileDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetProfilePostDto.java diff --git a/src/main/java/com/kimgreen/backend/config/Security/SecurityConfig.java b/src/main/java/com/kimgreen/backend/config/Security/SecurityConfig.java index df1bd78..21130ee 100644 --- a/src/main/java/com/kimgreen/backend/config/Security/SecurityConfig.java +++ b/src/main/java/com/kimgreen/backend/config/Security/SecurityConfig.java @@ -129,4 +129,4 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http.build(); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/AuditEntity.java b/src/main/java/com/kimgreen/backend/domain/AuditEntity.java index 874af6f..8727634 100644 --- a/src/main/java/com/kimgreen/backend/domain/AuditEntity.java +++ b/src/main/java/com/kimgreen/backend/domain/AuditEntity.java @@ -35,4 +35,4 @@ public void onUpdate() { String formattedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); this.modifiedAt = LocalDateTime.parse(formattedDate,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); } - } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/BadgeList.java b/src/main/java/com/kimgreen/backend/domain/BadgeList.java index ed189ce..b28f34e 100644 --- a/src/main/java/com/kimgreen/backend/domain/BadgeList.java +++ b/src/main/java/com/kimgreen/backend/domain/BadgeList.java @@ -1,7 +1,7 @@ package com.kimgreen.backend.domain; public enum BadgeList { - BLANK("","",1), + BLANK("","","",1), MENTOR("그린 멘토",5,"mentor.png","질문카테고리 댓글 5회 이상",2), MENTEE("그린 멘티",5,"mentee.png","질문 카테고리 글 작성 5회 이상",3), EARLYBIRD("얼리버드",3,"earlybird.png","9시 이전에 인증글 3회이상 작성",4), diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/CommentController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/CommentController.java index 12594ce..a183744 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/CommentController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/CommentController.java @@ -45,4 +45,4 @@ public Response getComment(@RequestParam("postId") Long postId){ List commentList = commentService.getComment(postId); return success(GET_COMMENT_SUCCESS, commentList); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/LikeController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/LikeController.java index 544dbf3..603fca5 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/LikeController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/LikeController.java @@ -1,12 +1,30 @@ package com.kimgreen.backend.domain.community.controller; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.community.service.LikeService; +import com.kimgreen.backend.response.Response; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; + +import static com.kimgreen.backend.response.Message.*; +import static org.springframework.http.HttpStatus.*; @Tag(name = "Like") @RestController @RequestMapping(value="/post/like") +@AllArgsConstructor public class LikeController { -} + + private final LikeService likeService; + + @Operation(summary = "좋아요 누르기 or 취소하기") + @ResponseStatus(OK) + @PostMapping() + public Response setLike(@RequestParam("postId") Long postId) { + likeService.setLike(postId); + return Response.success(SET_LIKES_SUCCESS); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index be37921..90200ff 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -1,13 +1,15 @@ package com.kimgreen.backend.domain.community.controller; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; +import com.kimgreen.backend.domain.community.entity.Category; import com.kimgreen.backend.domain.member.entity.Member; import com.kimgreen.backend.domain.member.service.MemberService; import com.kimgreen.backend.domain.community.service.PostService; +import com.kimgreen.backend.domain.profile.repository.BadgeRepository; import com.kimgreen.backend.response.Response; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -29,6 +31,7 @@ public class PostController { private final PostService postService; private final MemberService memberService; + private final BadgeRepository badgeRepository; @Operation(summary = "게시글 작성(인증)") @ResponseStatus(OK) @@ -51,15 +54,30 @@ public Response writeDailyPost(@RequestPart(name = "jsonData") WritePostRequestD @Operation(summary = "게시글 상세 보기") @ResponseStatus(OK) @GetMapping() - public Response getPostInfoWithAuthMember(Long postId){ - return success(GET_POST_SUCCESS, postService.getPostInfoWithAuthMember(postId, memberService.getCurrentMember())); + public Response getPostInfo(Long postId){ + return success(GET_POST_SUCCESS, postService.getPostInfo(postId)); + } + + @Operation(summary = "게시글 목록 불러오기") + @ResponseStatus(OK) + @GetMapping("/{category}") + public Response getPostList(Category category, com.kimgreen.backend.domain.community.entity.Tag tag) { + return success(GET_POST_LIST_SUCCESS, postService.getPostlist(category, tag)); + } + + @JsonIgnore + @Operation(summary = "게시글 좋아요 상위목록 불러오기") + @ResponseStatus(OK) + @GetMapping("/best") + public Response getBestPostList() { + return Response.success(GET_BEST_POST_LIST_SUCCESS, postService.getBestPostList()); } @Operation(summary = "게시글 삭제하기") @ResponseStatus(OK) @DeleteMapping() public Response deletePost(@RequestParam("postId") Long postId){ - postService.deletePost(postId, memberService.getCurrentMember()); + postService.deletePost(postId); return success(DELETE_POST_SUCCESS); } @@ -70,20 +88,7 @@ public Response editPostInfo(Long postId, @RequestPart(name = "body(json)") WritePostRequestDto editPostInfoRequestDto, @RequestPart(name = "files", required = false) MultipartFile multipartFile) throws IOException { - postService.editPost(postId, editPostInfoRequestDto, multipartFile, memberService.getCurrentMember()); + postService.editPost(postId, editPostInfoRequestDto, multipartFile); return success(EDIT_POST_SUCCESS); } - - /* @GetMapping("/post/edit/{id}") - public String edit(@PathVariable("id") Long id, Model model) { - BoardDto boardDto = boardService.findById(id); - model.addAttribute("post", boardDto); - return "board/edit.html"; - } - - @PutMapping("/post/edit/{id}") - public String update(@PathVariable Long id, BoardUpdateDto requestDto){ - boardService.update(id,requestDto); - return "redirect:/board/list"; - }*/ } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/ReportController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/ReportController.java index e5669e6..273b9fa 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/ReportController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/ReportController.java @@ -28,9 +28,9 @@ public class ReportController { @ResponseStatus(OK) @PostMapping() public Response postReport(@ParameterObject Long postId, - @RequestBody ReportRequestDto reportRequestDto) { + @RequestBody ReportRequestDto reportRequestDto) { reportService.postReport(postId,reportRequestDto); return success(POST_REPORT_SUCCESS); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java index 7e5cc0e..00ae52f 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoResponseDto.java @@ -1,5 +1,6 @@ package com.kimgreen.backend.domain.community.dto; +import com.fasterxml.jackson.annotation.JsonInclude; import com.kimgreen.backend.domain.community.entity.Post; import lombok.AllArgsConstructor; @@ -11,29 +12,23 @@ @Builder @AllArgsConstructor @NoArgsConstructor +@JsonInclude public class GetPostInfoResponseDto { private String writerNickname; private String writerBadge; + private String writerProfileImg; + private String imgUrl; private String content; - private Integer postId; + private Long postId; private String category; + private String tag; private Integer likeCount; private Integer commentCount; private Boolean isLiked; private Boolean isMine; private String updatedAt; - public static GetPostInfoResponseDto from(Post post, Boolean isWriter, Boolean liked, String badge){ - return GetPostInfoResponseDto.builder() - .writerNickname(post.getMember().getNickname()) - .writerBadge(badge) - .content(post.getContent()) - .category(String.valueOf(post.getCategory())) - .likeCount(post.getLikes().size()) - .commentCount(post.getComments().size()) - .isLiked(liked) - .isMine(isWriter) - .updatedAt(String.valueOf(post.getModifiedAt())) - .build(); + public void setImgUrl(String fullUrl) { + this.imgUrl = fullUrl; } - } \ No newline at end of file +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java index e142a0a..74912e9 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java @@ -1,5 +1,6 @@ package com.kimgreen.backend.domain.community.entity; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.kimgreen.backend.domain.AuditEntity; import com.kimgreen.backend.domain.member.entity.Member; import jakarta.persistence.*; @@ -7,6 +8,7 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import org.hibernate.annotations.Formula; import java.util.ArrayList; import java.util.Calendar; @@ -27,6 +29,7 @@ public class Post extends AuditEntity { //ManyToOne @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "writer_id", nullable = false) + @JsonIgnore private Member member; //OneToOne @@ -47,6 +50,11 @@ public class Post extends AuditEntity { @Enumerated(EnumType.STRING) private Tag tag; + @JsonIgnore + @Formula("(SELECT COUNT(*) FROM likes l WHERE l.post_id = post_id)") + private int likeCount; + + @JsonIgnore public void update(String category, String content) { this.category = Category.valueOf(category); this.content = content; diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/CommentRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/CommentRepository.java index 8e5d879..898512b 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/CommentRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/CommentRepository.java @@ -2,8 +2,12 @@ import com.kimgreen.backend.domain.community.entity.Comment; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository public interface CommentRepository extends JpaRepository { -} + @Query("select count(*) from Comment c join Post p on c.post.postId=p.postId where p.postId= :id") + public Long countComment(@Param("id") Long postId); +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/LikeRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/LikeRepository.java index e440914..9091820 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/LikeRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/LikeRepository.java @@ -1,9 +1,19 @@ package com.kimgreen.backend.domain.community.repository; import com.kimgreen.backend.domain.community.entity.Likes; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.member.entity.Member; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.util.Optional; + @Repository public interface LikeRepository extends JpaRepository { -} + @Query("select count(*) from Likes l join Post p on l.post.postId=p.postId where p.postId= :id") + public Long countLike(@Param("id") Long postId); + + public Optional findByPostAndMember(Post post, Member member); +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostImgRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostImgRepository.java index 4e38114..0db1844 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostImgRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostImgRepository.java @@ -1,10 +1,11 @@ package com.kimgreen.backend.domain.community.repository; +import com.kimgreen.backend.domain.community.entity.Post; import com.kimgreen.backend.domain.community.entity.PostImg; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface PostImgRepository extends JpaRepository { - -} + public PostImg findByPost(Post post); +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java index 2ab4316..84ba79d 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java @@ -1,16 +1,22 @@ package com.kimgreen.backend.domain.community.repository; - import com.kimgreen.backend.domain.community.entity.Post; - import org.springframework.data.jpa.repository.JpaRepository; - import org.springframework.stereotype.Repository; - - import java.time.LocalDateTime; - import java.util.List; - import java.util.Optional; +import com.kimgreen.backend.domain.community.dto.GetPostInfoResponseDto; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.member.entity.Member; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; import java.time.LocalDateTime; import java.util.List; @Repository public interface PostRepository extends JpaRepository { -} + @Query("select p from Post p where p.member.memberId= :id and p.createdAt between :start and :end") + public List findAllBetweenDate(@Param("id") Long memberId, @Param("start") LocalDateTime start, @Param("end") LocalDateTime end); + public List findAllByCreatedAtBetween(LocalDateTime start, LocalDateTime end); + List findByMember(Member member); + + public List findTop3ByOrderByLikeCountDesc(); +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java b/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java index 80ac8f6..d5298e1 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/CommentService.java @@ -64,15 +64,10 @@ public List getComment(Long postId){ if (comment.getPost() == post){ MemberProfileImg memberProfileImg = memberProfileImgRepository.findByMember(comment.getMember()); RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(comment.getMember()); - /* - GetCommentDto.from(comment, - s3Service.getFullUrl(memberProfileImg.getImgUrl()), - representativeBadge.getRepresentativeBadge().name, - comment.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())); - */ + GetCommentDto getCommentDto1 = GetCommentDto.builder() .commentId(comment.getCommentId()) - .writerProfileImg(s3Service.getFullUrl(memberProfileImg.getImgUrl())) //프로필이미지 + .writerProfileImg(s3Service.getFullUrl(memberProfileImg.getImgUrl())) .writerNickname(comment.getMember().getNickname()) .writerBadge(representativeBadge.getRepresentativeBadge().name) .content(comment.getContent()) diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/LikeService.java b/src/main/java/com/kimgreen/backend/domain/community/service/LikeService.java index 80380db..88f4b24 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/LikeService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/LikeService.java @@ -1,7 +1,43 @@ package com.kimgreen.backend.domain.community.service; +import com.kimgreen.backend.domain.community.entity.Likes; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.repository.LikeRepository; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.exception.PostNotFound; +import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; @Service +@AllArgsConstructor public class LikeService { -} + + private final MemberService memberService; + private final PostRepository postRepository; + private final LikeRepository likeRepository; + + @Transactional + public void setLike(Long postId) { + Member member = memberService.getCurrentMember(); + Post post = postRepository.findById(postId).orElseThrow(()-> new PostNotFound()); + + Optional foundLike = likeRepository.findByPostAndMember(post,member); + if(foundLike.isEmpty()) { + postLike(member, post); + } else { + likeRepository.delete(foundLike.get()); + } + } + + public void postLike(Member member, Post post) { + likeRepository.save(Likes.builder() + .post(post) + .member(member) + .build()); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index 10a269b..b295267 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -6,19 +6,27 @@ import com.kimgreen.backend.domain.community.repository.PostImgRepository; import com.kimgreen.backend.domain.community.repository.PostRepository; import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.entity.MemberProfileImg; +import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.profile.entity.Badge; import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import com.kimgreen.backend.domain.profile.repository.BadgeRepository; import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; import com.kimgreen.backend.exception.PostNotFound; -import com.kimgreen.backend.exception.WrongPath; -import com.kimgreen.backend.response.Response; import lombok.RequiredArgsConstructor; +import org.codehaus.jackson.annotate.JsonIgnore; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; -import java.util.ArrayList; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.*; +import java.util.stream.Collectors; + +import static java.util.Arrays.stream; @Service @RequiredArgsConstructor @@ -28,32 +36,37 @@ public class PostService { private final MemberService memberService; private final PostRepository postRepository; private final PostImgRepository postImgRepository; + private final MemberProfileImgRepository memberProfileImgRepository; private final RepresentativeBadgeRepository representativeBadgeRepository; + private final BadgeRepository badgeRepository; //게시물 작성 @Transactional public void writeCheckPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { + Badge badge = badgeRepository.findByMember(member); Post post = postRepository.save(writePostRequestDto.toCertifyPostEntity( - writePostRequestDto.getCategory(), - writePostRequestDto.getContent(), member)); + writePostRequestDto.getCategory(), + writePostRequestDto.getContent(), member)); - if(multipartFile != null){ - uploadPostFileList(multipartFile, post); - } + uploadPostFileList(multipartFile, post); + updateBadgeCount(badge, post.getCategory(), post.getTag()); } @Transactional public void writeDailyPost(WritePostRequestDto writePostRequestDto, MultipartFile multipartFile, Member member) throws IOException { + Badge badge = badgeRepository.findByMember(member); Post post = postRepository.save(writePostRequestDto.toDailyPostEntity( writePostRequestDto.getCategory(), writePostRequestDto.getContent(), member)); - if(multipartFile != null){ + if (multipartFile != null) { uploadPostFileList(multipartFile, post); } + updateBadgeCount(badge, post.getCategory(), post.getTag()); } + @Transactional public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IOException { PostImg postImg = postImgRepository.save(PostImg.builder() @@ -62,53 +75,185 @@ public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IO .post(post).build()); } + //뱃지 카운트 + private void updateBadgeCount(Badge badge, Category category, Tag tag) { + + LocalDateTime currentTime = LocalDateTime.now(); + boolean isBefore9AM = currentTime.toLocalTime().isBefore(LocalTime.of(9, 0)); + + // 아침 9시 전에 인증 게시글이 작성된 경우 + if (isBefore9AM && tag.equals(Tag.CERTIFY)) { + badge.setEarlybirdCount(badge.getEarlybirdCount() + 1); + } + + if (tag.equals(Tag.CERTIFY)){ + badge.setCertificationCount(badge.getCertificationCount() +1); + if (category.equals(Category.RECEIPT)) { badge.setReceiptCount(badge.getReceiptCount() + 1);} + if (category.equals(Category.REUSABLE)) { badge.setReusableCount(badge.getReusableCount() + 1);} + if (category.equals(Category.PLASTIC)) { badge.setPlasticCount(badge.getPlasticCount() + 1);} + if (category.equals(Category.PLOGGING)) { badge.setPloggingCount(badge.getPloggingCount() + 1);} + if (category.equals(Category.REFORM)) { badge.setReformCount(badge.getReformCount() + 1);} + if (category.equals(Category.TRANSPORT)) { badge.setTransportCount(badge.getTransportCount() + 1);} + if (category.equals(Category.ETC)) { badge.setEtcCount(badge.getEtcCount() + 1);} + if (category.equals(Category.QUESTION)) { badge.setMentorCount(badge.getMentorCount() + 1);} + } + } + + + //뱃지조건에 따라 isAchieved update -> + // + 삭제했을 떄 처리 코드도 작성 + + + // 게시글 상세정보 조회 @Transactional - public GetPostInfoResponseDto getPostInfoWithAuthMember(Long postId, Member currentMember) { + public GetPostInfoResponseDto getPostInfo(Long postId) { Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); Member member = post.getMember(); - RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(member); - return GetPostInfoResponseDto.from(post, - isWriter(post, currentMember), - isLiked(post, currentMember), - representativeBadge.getRepresentativeBadge().name); - } + List likeList = post.getLikes(); + boolean isLiked = isLiked(likeList,member); - @Transactional(readOnly = true) - public Boolean isWriter(Post post, Member currentMember){ - return post.getMember().getMemberId().equals(currentMember.getMemberId()); + if(post.getPostImg()!= null) { + return GetPostInfoResponseDto.builder() + .writerNickname(post.getMember().getNickname()) + .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl())) + .imgUrl(s3Service.getFullUrl(postImgRepository.findByPost(post).getImgUrl())) + .content(post.getContent()) + .postId(post.getPostId()) + .category(String.valueOf(post.getCategory())) + .writerBadge(representativeBadgeRepository.findByMember(post.getMember()).getRepresentativeBadge().name) + .likeCount(post.getLikes().size()) + .commentCount(post.getComments().size()) + .isLiked(isLiked) + .isMine(post.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())) + .updatedAt(String.valueOf(post.getModifiedAt())) + .build(); + } + return GetPostInfoResponseDto.builder() + .writerNickname(post.getMember().getNickname()) + .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl())) + .content(post.getContent()) + .postId(post.getPostId()) + .category(String.valueOf(post.getCategory())) + .writerBadge(representativeBadgeRepository.findByMember(post.getMember()).getRepresentativeBadge().name) + .likeCount(post.getLikes().size()) + .commentCount(post.getComments().size()) + .isLiked(isLiked) + .isMine(post.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())) + .updatedAt(String.valueOf(post.getModifiedAt())) + .build(); } - @Transactional(readOnly = true) - public Boolean isLiked(Post post, Member currentMember){ - for(Likes postLike : post.getLikes()){ - if(postLike.getLikeId().equals(currentMember.getMemberId())) return true; + @Transactional + public List getPostlist(Category category, Tag tag) { + + List posts = postRepository.findAll(); + List postList = new ArrayList<>(); + + for (Post post : posts) { + + if (post.getTag() != Tag.DAILY || !post.getCategory().equals(category)) { + continue; + } + + Member member = post.getMember(); + List likeList = post.getLikes(); + boolean isLiked = isLiked(likeList, member); + + Optional optionalPostImg = Optional.ofNullable(postImgRepository.findByPost(post)); + String imgUrl = optionalPostImg.map(img -> s3Service.getFullUrl(img.getImgUrl())).orElse("defaultImageUrl"); + + GetPostInfoResponseDto getPostInfoResponseDto = GetPostInfoResponseDto.builder() + .writerNickname(post.getMember().getNickname()) + .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl())) + .content(post.getContent()) + .postId(post.getPostId()) + .category(String.valueOf(post.getCategory())) + .writerBadge(representativeBadgeRepository.findByMember(member).getRepresentativeBadge().name) + .likeCount(post.getLikes().size()) + .commentCount(post.getComments().size()) + .isLiked(isLiked) + .isMine(post.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())) + .updatedAt(String.valueOf(post.getModifiedAt())) + .build(); + + if (post.getPostImg() != null) { + getPostInfoResponseDto.setImgUrl(s3Service.getFullUrl(postImgRepository.findByPost(post).getImgUrl())); + } + postList.add(getPostInfoResponseDto); } - return false; + return postList; } //게시글 삭제하기 @Transactional - public void deletePost(Long postId, Member currentMember){ + public void deletePost(Long postId) { + Member member = memberService.getCurrentMember(); Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); - + // 게시글 삭제 postRepository.delete(post); - //postImgRepository.delete(post); } + //게시글 수정하기 @Transactional - public void editPost(Long postId, WritePostRequestDto editPostInfoRequestDto, MultipartFile multipartFile, Member currentMember) throws IOException { + public void editPost(Long postId, WritePostRequestDto editPostInfoRequestDto, MultipartFile + multipartFile) throws IOException { + + Member member = memberService.getCurrentMember(); Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); post.update(editPostInfoRequestDto.getCategory(), editPostInfoRequestDto.getContent()); - // 기존 게시글 db을 모두 삭제하는 코드 필요 - - if(multipartFile != null){ + if (multipartFile != null) { uploadPostFileList(multipartFile, post); } + } - //for(String fileUrl : fileUrls) s3Service.deleteFile(fileUrl); + public boolean isLiked(List likesList,Member member) { + for(Likes like : likesList) { + if(like.getLikeId().equals(member.getMemberId())) { + return true; + } + } + return false; + } + + //좋아요 상위 목록 불러오기 + @JsonIgnore + @Transactional + public List getBestPostList() { + List bestPost = postRepository.findTop3ByOrderByLikeCountDesc(); + List postList = new ArrayList<>(); + + for (Post post : bestPost) { + + Member member = post.getMember(); + List likeList = post.getLikes(); + boolean isLiked = isLiked(likeList, member); + + Optional optionalPostImg = Optional.ofNullable(postImgRepository.findByPost(post)); + String imgUrl = optionalPostImg.map(img -> s3Service.getFullUrl(img.getImgUrl())).orElse("defaultImageUrl"); + + GetPostInfoResponseDto getPostInfoResponseDto = GetPostInfoResponseDto.builder() + .writerNickname(post.getMember().getNickname()) + .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl())) + .content(post.getContent()) + .postId(post.getPostId()) + .category(String.valueOf(post.getCategory())) + .writerBadge(representativeBadgeRepository.findByMember(member).getRepresentativeBadge().name) + .likeCount(post.getLikes().size()) + .commentCount(post.getComments().size()) + .isLiked(isLiked) + .isMine(post.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())) + .updatedAt(String.valueOf(post.getModifiedAt())) + .build(); + + if (post.getPostImg() != null) { + getPostInfoResponseDto.setImgUrl(s3Service.getFullUrl(postImgRepository.findByPost(post).getImgUrl())); + } + postList.add(getPostInfoResponseDto); + } + return bestPost; } } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/ReportService.java b/src/main/java/com/kimgreen/backend/domain/community/service/ReportService.java index 77a2ac1..284bc24 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/ReportService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/ReportService.java @@ -26,4 +26,4 @@ public void postReport(Long postId,ReportRequestDto reportRequestDto) { ) ); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java index 20d0fd6..7d10701 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java +++ b/src/main/java/com/kimgreen/backend/domain/member/entity/Member.java @@ -1,5 +1,6 @@ package com.kimgreen.backend.domain.member.entity; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.kimgreen.backend.domain.AuditEntity; import com.kimgreen.backend.domain.community.entity.Comment; import com.kimgreen.backend.domain.community.entity.Likes; @@ -28,6 +29,7 @@ public class Member extends AuditEntity { //OneToMany @OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true) @Builder.Default + @JsonIgnore private List posts = new ArrayList<>(); @OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true) @Builder.Default diff --git a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java index 0e057e3..3316a1b 100644 --- a/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java +++ b/src/main/java/com/kimgreen/backend/domain/member/service/AuthService.java @@ -53,6 +53,7 @@ public class AuthService { private static final String EXPIRED = "expired"; private final FCMService FCMService; + @Transactional public void signUp(SignUpRequestDto signUpRequestDto) { String email = signUpRequestDto.getEmail(); String password = signUpRequestDto.getPassword(); @@ -60,6 +61,7 @@ public void signUp(SignUpRequestDto signUpRequestDto) { validateEmail(email); saveMember(signUpRequestDto,email, password, nickname); + updateSprout(memberRepository.findByEmail(email)); } @Transactional @@ -102,6 +104,7 @@ public TokenDto logIn(LogInRequestDto dto) { } + @Transactional public TokenDto tokenReissue(TokenDto tokenDto) { //어차피 accessToken 만료인 경우에 호출되기 때문에 AT는 검증할 필요X String accessToken = tokenDto.getAccessToken(); @@ -161,12 +164,19 @@ public void validateEmail(String email) { } } + @Transactional public void saveMember(SignUpRequestDto signUpRequestDto,String email, String password, String nickname) { memberRepository.save(signUpRequestDto.toMemberEntity(email, passwordEncoder.encode(password),nickname)); Member member = memberRepository.findByEmail(email); profileImgRepository.save(signUpRequestDto.toMemberProfileImgEntity(member)); badgeRepository.save(Badge.builder().member(member).build()); - profileBadgeRepository.save(ProfileBadge.builder().member(member).build()); + profileBadgeRepository.save(ProfileBadge.builder() + .member(member) + .profileBadge_1(BadgeList.BLANK) + .profileBadge_2(BadgeList.BLANK) + .profileBadge_3(BadgeList.BLANK) + .profileBadge_4(BadgeList.BLANK) + .profileBadge_5(BadgeList.BLANK).build()); representativeBadgeRepository.save( RepresentativeBadge.builder() .representativeBadge(BadgeList.BLANK) @@ -174,4 +184,9 @@ public void saveMember(SignUpRequestDto signUpRequestDto,String email, String pa .build()); } + @Transactional + public void updateSprout(Member member) { + badgeRepository.findByMember(member).setSproutIsAchieved(true); + } + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/controller/profileController.java b/src/main/java/com/kimgreen/backend/domain/profile/controller/profileController.java index e2dcb11..7d38ac6 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/controller/profileController.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/controller/profileController.java @@ -1,12 +1,40 @@ package com.kimgreen.backend.domain.profile.controller; +import com.kimgreen.backend.domain.profile.dto.Profile.GetProfilePostDto; +import com.kimgreen.backend.domain.profile.service.ProfileService; +import com.kimgreen.backend.response.Response; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import lombok.RequiredArgsConstructor; +import org.springdoc.core.annotations.ParameterObject; +import org.springframework.web.bind.annotation.*; + +import java.awt.print.Pageable; + +import static com.kimgreen.backend.response.Message.PROFILE_INFO_SUCCESS; +import static com.kimgreen.backend.response.Message.PROFILE_POSTS_SUCCESS; +import static com.kimgreen.backend.response.Response.success; +import static org.springframework.http.HttpStatus.OK; @Tag(name = "Profile") @RestController @RequestMapping(value="/profile") +@RequiredArgsConstructor + public class profileController { -} + private final ProfileService profileService; + + @Operation(summary = "프로필 글 목록 불러오기(특정 멤버가 쓴 글 목록 불러오기)") + @ResponseStatus(OK) + @GetMapping("/post") + public Response getProfilePosts(@RequestParam("memberId") Long memberId) { + return success(PROFILE_POSTS_SUCCESS, profileService.response(memberId)); + } + @Operation(summary = "프로필 정보 불러오기") + @ResponseStatus(OK) + @GetMapping() + public Response getProfileInfo(@RequestParam("memberId") Long memberId) { + return success(PROFILE_INFO_SUCCESS, profileService.getProfileInfo(memberId)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailDto.java new file mode 100644 index 0000000..edd46e2 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailDto.java @@ -0,0 +1,27 @@ +package com.kimgreen.backend.domain.profile.dto.Calendar; + +import com.kimgreen.backend.domain.community.entity.Post; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class CalendarDetailDto { + private Long postId; + private String writerNickname; + private String profileImg; + private String writerBadge; + private String content; + private int likeCount; + private Long commentCount; + private String imgUrl; + private Boolean isLiked; + +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailRequestDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailRequestDto.java new file mode 100644 index 0000000..0beb21f --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailRequestDto.java @@ -0,0 +1,15 @@ +package com.kimgreen.backend.domain.profile.dto.Calendar; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class CalendarDetailRequestDto { + private Long memberId; + private String date; +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailResponseDto.java new file mode 100644 index 0000000..08012b2 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarDetailResponseDto.java @@ -0,0 +1,25 @@ +package com.kimgreen.backend.domain.profile.dto.Calendar; + +import com.kimgreen.backend.domain.community.entity.Post; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class CalendarDetailResponseDto { + private int postCount; + private List contents; + + public static CalendarDetailResponseDto toDto(int count, List contents) { + return CalendarDetailResponseDto.builder() + .postCount(count) + .contents(contents) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarResponseDto.java new file mode 100644 index 0000000..47b375a --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Calendar/CalendarResponseDto.java @@ -0,0 +1,15 @@ +package com.kimgreen.backend.domain.profile.dto.Calendar; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class CalendarResponseDto { + private String date; + private int postCount; +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetProfileDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetProfileDto.java new file mode 100644 index 0000000..fa07ced --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetProfileDto.java @@ -0,0 +1,43 @@ +package com.kimgreen.backend.domain.profile.dto.Profile; + +import com.kimgreen.backend.domain.member.entity.Member; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Component +public class GetProfileDto { + private String nickname; + private String profileImg; + private String profileBadge; + private String profileBadgeImg; + private ArrayList badgeList; + private ArrayList badgeImgList; + private boolean isMine; + + public GetProfileDto from(Member member, + String profileImg, + String profileBadge, + String profileBadgeImg, + ArrayList badgeList, + ArrayList badgeImgList, + boolean isMine){ + return GetProfileDto.builder() + .nickname(member.getNickname()) + .profileImg(profileImg) + .profileBadge(profileBadge) + .profileBadgeImg(profileBadgeImg) + .badgeList(badgeList) + .badgeImgList(badgeImgList) + .isMine(isMine) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetProfilePostDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetProfilePostDto.java new file mode 100644 index 0000000..241d878 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetProfilePostDto.java @@ -0,0 +1,24 @@ +package com.kimgreen.backend.domain.profile.dto.Profile; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.stereotype.Component; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Component +public class GetProfilePostDto { + private Long postId; + private String writerNickname; + private String writerBadge; + private String writerProfileImg; + private String content; + private int likeCount; + private int commentCount; + private String imgUrl; + private boolean isLiked; +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index 5838710..a5cbac3 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -3,16 +3,14 @@ import com.kimgreen.backend.domain.AuditEntity; import com.kimgreen.backend.domain.member.entity.Member; import jakarta.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; +import lombok.*; @Getter @NoArgsConstructor @AllArgsConstructor @Entity @Builder +@Setter public class Badge extends AuditEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/com/kimgreen/backend/domain/profile/repository/RepresentativeBadgeRepository.java b/src/main/java/com/kimgreen/backend/domain/profile/repository/RepresentativeBadgeRepository.java index ff61e4b..e86209e 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/repository/RepresentativeBadgeRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/repository/RepresentativeBadgeRepository.java @@ -8,4 +8,4 @@ public interface RepresentativeBadgeRepository extends JpaRepository { public RepresentativeBadge findByMember(Member member); public void deleteByMember(Member member); -} +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java index 8c24412..ea590c7 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java @@ -1,9 +1,155 @@ package com.kimgreen.backend.domain.profile.service; +import com.kimgreen.backend.domain.community.entity.Comment; +import com.kimgreen.backend.domain.community.entity.Likes; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.PostImg; +import com.kimgreen.backend.domain.community.repository.CommentRepository; +import com.kimgreen.backend.domain.community.repository.LikeRepository; +import com.kimgreen.backend.domain.community.repository.PostImgRepository; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.community.service.S3Service; +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.entity.MemberProfileImg; +import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; +import com.kimgreen.backend.domain.member.repository.MemberRepository; +import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.profile.dto.Calendar.CalendarDetailDto; +import com.kimgreen.backend.domain.profile.dto.Calendar.CalendarDetailRequestDto; +import com.kimgreen.backend.domain.profile.dto.Calendar.CalendarDetailResponseDto; +import com.kimgreen.backend.domain.profile.dto.Calendar.CalendarResponseDto; +import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; +import javax.swing.text.DateFormatter; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + @Service @AllArgsConstructor public class CalendarService { -} + private final PostRepository postRepository; + private final MemberService memberService; + private final RepresentativeBadgeRepository representativeBadgeRepository; + private final PostImgRepository postImgRepository; + private final MemberProfileImgRepository memberProfileImgRepository; + private final S3Service s3Service; + private final LikeRepository likeRepository; + private final CommentRepository commentRepository; + private final MemberRepository memberRepository; + + public List getCalendar(Long memberId, String date) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDateTime localDateTime = LocalDate.parse(date, formatter).withDayOfMonth(1).atStartOfDay(); + LocalDateTime start = localDateTime; + LocalDateTime end = localDateTime.withDayOfMonth(start.toLocalDate().lengthOfMonth()).withHour(23).withMinute(59).withSecond(59); + + List postList = postRepository.findAllBetweenDate(memberId,start,end); + return getDtoList(postList); + } + + public CalendarDetailResponseDto getCalendarDetails(CalendarDetailRequestDto dto) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDateTime start = LocalDate.parse(dto.getDate(), formatter).atStartOfDay(); + LocalDateTime end = start.withHour(23).withMinute(59).withSecond(59); + List postList = postRepository.findAllByCreatedAtBetween(start,end); + return CalendarDetailResponseDto.toDto(postList.size(),getResult(postList)); + + } + + public List getDtoList(List postList) { + Map resultMap = new HashMap<>(); + for(Post post:postList) { + String key = post.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); + if(!resultMap.containsKey(key)) { + resultMap.put(key,1); + } else { + Integer value =resultMap.get(key); + resultMap.put(key,++value); + } + } + + return toList(resultMap); + } + + public List toList(Map maps) { + List result = new ArrayList<>(); + for(Map.Entry map :maps.entrySet()) { + result.add(CalendarResponseDto.builder() + .date(map.getKey()) + .postCount(map.getValue()) + .build()); + } + return result; + } + + public List getResult(List postList) { + CalendarDetailDto dto; + List result = new ArrayList<>(); + for(Post post : postList) { + Long postId = post.getPostId(); + Member member = post.getMember(); + RepresentativeBadge badge = representativeBadgeRepository.findByMember(member); + MemberProfileImg profileImg = memberProfileImgRepository.findByMember(member); + PostImg postImg = postImgRepository.findByPost(post); + List likeList = post.getLikes(); + boolean isLiked = isLiked(likeList,member); + //Long likes = likeRepository.countLike(postId); + Long comments = commentRepository.countComment(postId); + + + if(postImg==null) { + dto = dtoBuilderWithNoImg(postId,member.getNickname(),s3Service.getFullUrl(profileImg.getImgUrl()),badge.getRepresentativeBadge().name + ,post.getContent(),likeList.size(),comments,isLiked); + } else { + dto = dtoBuilderWithImg(postId, member.getNickname(), s3Service.getFullUrl(profileImg.getImgUrl()), badge.getRepresentativeBadge().name + , post.getContent(), likeList.size(), comments, s3Service.getFullUrl(postImg.getImgUrl()),isLiked); + } + + result.add(dto); + } + return result; + } + + public CalendarDetailDto dtoBuilderWithImg(Long postId, String nickname, String profileImg,String name,String content + ,int likes, Long comments, String postImg, boolean isLiked) { + return CalendarDetailDto.builder() + .postId(postId) + .writerNickname(nickname) + .profileImg(profileImg) + .writerBadge(name) + .content(content) + .likeCount(likes) + .commentCount(comments) + .imgUrl(postImg) + .isLiked(isLiked) + .build(); + } + + public CalendarDetailDto dtoBuilderWithNoImg(Long postId, String nickname, String profileImg,String name,String content + ,int likes, Long comments, boolean isLiked) { + return CalendarDetailDto.builder() + .postId(postId) + .writerNickname(nickname) + .profileImg(profileImg) + .writerBadge(name) + .content(content) + .likeCount(likes) + .commentCount(comments) + .isLiked(isLiked) + .build(); + } + + public boolean isLiked(List likesList,Member member) { + for(Likes like : likesList) { + if(like.getLikeId().equals(member.getMemberId())) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java index 5a8f07c..bbce6d7 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java @@ -1,7 +1,118 @@ package com.kimgreen.backend.domain.profile.service; +import com.kimgreen.backend.domain.BadgeList; +import com.kimgreen.backend.domain.community.entity.Likes; +import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.repository.PostImgRepository; +import com.kimgreen.backend.domain.community.repository.PostRepository; +import com.kimgreen.backend.domain.community.service.S3Service; +import com.kimgreen.backend.domain.member.entity.Member; +import com.kimgreen.backend.domain.member.entity.MemberProfileImg; +import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; +import com.kimgreen.backend.domain.member.repository.MemberRepository; +import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.profile.dto.Profile.GetProfileDto; +import com.kimgreen.backend.domain.profile.entity.ProfileBadge; +import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; +import com.kimgreen.backend.domain.profile.repository.ProfileBadgeRepository; +import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; +import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; +import com.kimgreen.backend.domain.profile.dto.Profile.GetProfilePostDto; + +import java.util.*; @Service +@AllArgsConstructor + + public class ProfileService { -} + private final MemberService memberService; + private final MemberRepository memberRepository; + private final GetProfileDto getProfileDto; + private final MemberProfileImgRepository memberProfileImgRepository; + private final S3Service s3Service; + private final RepresentativeBadgeRepository representativeBadgeRepository; + private final ProfileBadgeRepository profileBadgeRepository; + private final PostRepository postRepository; + private final PostImgRepository postImgRepository; + private final GetProfilePostDto getProfilePostDto; + + public List response(Long memberId){ + List list = new ArrayList<>(); + List allPostList = postRepository.findAll(); + List postList = new ArrayList<>(); + for(Post p : allPostList){ + if(p.getMember().getMemberId().equals(memberId)){ + postList.add(p); + } + } + for(Post p : postList) { + boolean isLiked = false; + for(Likes l : p.getLikes()){ + if(l.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())){ + isLiked = true; + break; + } + } + if(postImgRepository.findByPost(p) == null){ + list.add(GetProfilePostDto.builder() + .postId(p.getPostId()) + .writerNickname(p.getMember().getNickname()) + .writerBadge(representativeBadgeRepository.findByMember(p.getMember()).getRepresentativeBadge().name) + .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(p.getMember()).getImgUrl())) + .content(p.getContent()) + .likeCount(p.getLikes().size()) + .commentCount(p.getComments().size()) + .isLiked(isLiked).build()); + }else{ // 포스트이미지 있을때 + list.add(GetProfilePostDto.builder() + .postId(p.getPostId()) + .writerNickname(p.getMember().getNickname()) + .writerBadge(representativeBadgeRepository.findByMember(p.getMember()).getRepresentativeBadge().name) + .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(p.getMember()).getImgUrl())) + .content(p.getContent()) + .likeCount(p.getLikes().size()) + .commentCount(p.getComments().size()) + .imgUrl(s3Service.getFullUrl(postImgRepository.findByPost(p).getImgUrl())) + .isLiked(isLiked).build()); + } + + } + return list; + } + + public GetProfileDto getProfileInfo(Long memberId){ + Member member = memberRepository.findById(memberId).orElseThrow(); // 찾고싶은 멤버 + MemberProfileImg memberProfileImg = memberProfileImgRepository.findByMember(member); + RepresentativeBadge representativeBadge = representativeBadgeRepository.findByMember(member); + profileBadgeRepository.findByMember(member); + + ArrayList badgeList = new ArrayList<>(); + ArrayList badgeImgList = new ArrayList<>(); + + ProfileBadge profileBadge = profileBadgeRepository.findByMember(member); + ArrayList list = new ArrayList<>(); + list.add(profileBadge.getProfileBadge_1()); + list.add(profileBadge.getProfileBadge_2()); + list.add(profileBadge.getProfileBadge_3()); + list.add(profileBadge.getProfileBadge_4()); + list.add(profileBadge.getProfileBadge_5()); + for(BadgeList b : list){ + badgeList.add(b.name); + if(b != BadgeList.BLANK){ + badgeImgList.add(s3Service.getFullUrl(b.url)); + } + } + + return getProfileDto.from(member, + s3Service.getFullUrl(memberProfileImg.getImgUrl()), + representativeBadge.getRepresentativeBadge().name, + s3Service.getFullUrl(representativeBadge.getRepresentativeBadge().url), + badgeList, + badgeImgList, + memberId.equals(memberService.getCurrentMember().getMemberId()) + ); + } + +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index aaaa42b..f0dcfa8 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -1,5 +1,10 @@ package com.kimgreen.backend.response; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseStatus; + +import static org.springframework.http.HttpStatus.OK; + public class Message { public static String SIGN_UP_SUCCESS = "회원가입에 성공했습니다."; public static String LOG_IN_SUCCESS="로그인에 성공했습니다."; @@ -10,6 +15,8 @@ public class Message { public static String WRITE_CERTIFY_POST_SUCCESS="인증 게시글 작성 성공했습니다."; public static String WRITE_DAILY_POST_SUCCESS="일상 게시글 작성 성공했습니다."; + public static String GET_POST_LIST_SUCCESS="게시글 목록 불러오기 성공했습니다."; + public static String GET_BEST_POST_LIST_SUCCESS="게시글 좋아요 상위목록 불러오기 성공했습니다."; public static String GET_POST_SUCCESS="게시글 상세 보기 성공했습니다."; public static String DELETE_POST_SUCCESS="게시글 삭제하기 성공했습니다."; public static String EDIT_POST_SUCCESS="게시글 수정하기 성공했습니다."; @@ -31,4 +38,8 @@ public class Message { public static String DELETE_COMMENT_SUCCESS="댓글 삭제 성공했습니다."; public static String GET_COMMENT_SUCCESS="댓글 목록을 불러오는데 성공하였습니다."; + public static String SET_LIKES_SUCCESS="게시글 좋아요 or 취소하기 성공했습니다."; + public static String PROFILE_INFO_SUCCESS="프로필 불러오기 성공했습니다."; + public static String PROFILE_POSTS_SUCCESS="쓴 글 목록 불러오기 성공했습니다"; + } \ No newline at end of file From ae062b88de6b89f2e925532b711eb92d72c9d181 Mon Sep 17 00:00:00 2001 From: chae33 Date: Mon, 5 Feb 2024 09:09:50 +0900 Subject: [PATCH 70/72] [fix] --- .../domain/community/service/PostService.java | 57 ++++++++++++++++++- .../backend/domain/profile/entity/Badge.java | 2 +- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index b295267..f66f1d1 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -75,7 +75,7 @@ public void uploadPostFileList(MultipartFile multipartFile, Post post) throws IO .post(post).build()); } - //뱃지 카운트 + //뱃지 카운트 (게시글 작성) private void updateBadgeCount(Badge badge, Category category, Tag tag) { LocalDateTime currentTime = LocalDateTime.now(); @@ -97,11 +97,56 @@ private void updateBadgeCount(Badge badge, Category category, Tag tag) { if (category.equals(Category.ETC)) { badge.setEtcCount(badge.getEtcCount() + 1);} if (category.equals(Category.QUESTION)) { badge.setMentorCount(badge.getMentorCount() + 1);} } + updateIsAchieved(badge); } - //뱃지조건에 따라 isAchieved update -> - // + 삭제했을 떄 처리 코드도 작성 + + //isAchieved update + private void updateIsAchieved(Badge badge){ + if(badge.getEarlybirdCount() >= 3) { badge.setEarlybirdIsAchieved(true);} + + // 질문카테고리 댓글 n회 이상 → mentorCount + // 질문 카테고리 글 작성 n회 이상 → menteeCount + + if(badge.getReceiptCount() >= 3) { badge.setReceipt3IsAchieved(true); + if(badge.getReceiptCount() >= 10) { badge.setReceipt10IsAchieved(true);}} + if(badge.getReusableCount() >= 3) { badge.setReusable3IsAchieved(true); + if(badge.getReusableCount() >= 10) { badge.setReusable10IsAchieved(true);}} + if(badge.getPlasticCount() >= 3) { badge.setPlastic3IsAchieved(true); + if(badge.getPlasticCount() >= 10) { badge.setPlastic10IsAchieved(true);}} + if(badge.getPloggingCount() >= 3) { badge.setPlogging3IsAchieved(true); + if(badge.getPloggingCount() >= 10) { badge.setPlogging10IsAchieved(true);}} + if(badge.getReformCount() >= 3) { badge.setReform3IsAchieved(true); + if(badge.getReformCount() >= 10) { badge.setReform10IsAchieved(true);}} + if(badge.getTransportCount() >= 3) { badge.setTransport3IsAchieved(true); + if(badge.getTransportCount() >= 10) { badge.setTransport10IsAchieved(true);}} + if(badge.getEtcCount() >= 3) { badge.setEtc3IsAchieved(true); + if(badge.getEtcCount() >= 10) { badge.setEtc10IsAchieved(true);}} + } + + // 뱃지 카운트 (게시글 삭제) + private void decreaseBadgeCount(Badge badge, Category category, Tag tag) { + + LocalDateTime currentTime = LocalDateTime.now(); + boolean isBefore9AM = currentTime.toLocalTime().isBefore(LocalTime.of(9, 0)); + + if (isBefore9AM && tag.equals(Tag.CERTIFY)) { + badge.setEarlybirdCount(Math.max(badge.getEarlybirdCount() - 1, 0)); + } + if (tag.equals(Tag.CERTIFY)){ + badge.setCertificationCount(Math.max(badge.getCertificationCount() - 1, 0)); + if (category.equals(Category.RECEIPT)) { badge.setReceiptCount(Math.max(badge.getReceiptCount() - 1, 0));} + if (category.equals(Category.REUSABLE)) { badge.setReusableCount(Math.max(badge.getReusableCount() - 1, 0));} + if (category.equals(Category.PLASTIC)) { badge.setPlasticCount(Math.max(badge.getPlasticCount() - 1, 0));} + if (category.equals(Category.PLOGGING)) { badge.setPloggingCount(Math.max(badge.getPloggingCount() - 1, 0));} + if (category.equals(Category.REFORM)) { badge.setReformCount(Math.max(badge.getReformCount() - 1, 0));} + if (category.equals(Category.TRANSPORT)) { badge.setTransportCount(Math.max(badge.getTransportCount() - 1, 0));} + if (category.equals(Category.ETC)) { badge.setEtcCount(Math.max(badge.getEtcCount() - 1, 0));} + if (category.equals(Category.QUESTION)) { badge.setMentorCount(Math.max(badge.getMentorCount() - 1, 0));} + } + updateIsAchieved(badge); + } @@ -152,10 +197,12 @@ public List getPostlist(Category category, Tag tag) { List postList = new ArrayList<>(); for (Post post : posts) { +/* if (post.getTag() != Tag.DAILY || !post.getCategory().equals(category)) { continue; } +*/ Member member = post.getMember(); List likeList = post.getLikes(); @@ -191,8 +238,12 @@ public List getPostlist(Category category, Tag tag) { public void deletePost(Long postId) { Member member = memberService.getCurrentMember(); Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); + Badge badge = badgeRepository.findByMember(member); + // 게시글 삭제 postRepository.delete(post); + decreaseBadgeCount(badge, post.getCategory(), post.getTag()); + } //게시글 수정하기 diff --git a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java index a5cbac3..5032767 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/entity/Badge.java @@ -23,7 +23,7 @@ public class Badge extends AuditEntity { @Column(name="earlybird_count",columnDefinition = "int default 0" ) private int earlybirdCount; - @Column(name="ealrybird_is_achieved",columnDefinition = "boolean default false") + @Column(name="earlybird_is_achieved",columnDefinition = "boolean default false") private boolean earlybirdIsAchieved; @Column(name="mentor_count",columnDefinition = "int default 0") From 574a2ceb282b40bad624342669afe858090a7e5c Mon Sep 17 00:00:00 2001 From: chae33 Date: Mon, 5 Feb 2024 12:23:44 +0900 Subject: [PATCH 71/72] [fix] getMyPost/getMyComment --- .../JwtAuthenticationEntryPoint.java | 13 ++++- .../repository/CommentRepository.java | 7 ++- .../profile/controller/profileController.java | 16 +++++- .../dto/Profile/CommentResponseDto.java | 29 ++++++++++ .../dto/Profile/GetSettingPostDto.java | 48 ++++++++++++++++ .../profile/service/CalendarService.java | 2 +- .../profile/service/ProfileService.java | 57 +++++++++++++++++++ .../kimgreen/backend/response/Message.java | 3 +- 8 files changed, 169 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/CommentResponseDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetSettingPostDto.java diff --git a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java index 3ea05a2..82e0ac9 100644 --- a/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java +++ b/src/main/java/com/kimgreen/backend/config/Authentication/JwtAuthenticationEntryPoint.java @@ -18,6 +18,9 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { private static final String SUCCESS = "success"; private static final String EXPIRED = "expired"; private static final String DENIED = "denied"; + private static final String MALFORMED = "malformed"; + private static final String BLANK = "blank"; + private static final String MALFORMED_JWT = "malformed_jwt"; @Override public void commence(HttpServletRequest request, @@ -32,7 +35,15 @@ public void commence(HttpServletRequest request, setResponse(response,HttpStatus.UNAUTHORIZED.value(),"토큰이 유효하지 않습니다."); } if (exception.equals(DENIED)) { - setResponse(response,HttpStatus.NOT_FOUND.value(), "토큰이 없습니다."); + setResponse(response,HttpStatus.NOT_FOUND.value(), "잘못된 형식의 요청입니다."); + } + if (exception.equals(MALFORMED)) { + setResponse(response,HttpStatus.BAD_REQUEST.value(), "Bearer 형식이 존재하지 않습니다."); + } + if(exception.equals(BLANK)) { + setResponse(response,HttpStatus.BAD_REQUEST.value(), "토큰이 존재하지 않습니다."); + }if(exception.equals(MALFORMED_JWT)) { + setResponse(response,HttpStatus.BAD_REQUEST.value(), "잘못된 형식의 토큰입니다."); } } diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/CommentRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/CommentRepository.java index 898512b..a78ee01 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/CommentRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/CommentRepository.java @@ -1,13 +1,18 @@ package com.kimgreen.backend.domain.community.repository; import com.kimgreen.backend.domain.community.entity.Comment; +import com.kimgreen.backend.domain.member.entity.Member; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.util.List; + @Repository public interface CommentRepository extends JpaRepository { @Query("select count(*) from Comment c join Post p on c.post.postId=p.postId where p.postId= :id") public Long countComment(@Param("id") Long postId); -} \ No newline at end of file + List findByMember(Member member); +} + diff --git a/src/main/java/com/kimgreen/backend/domain/profile/controller/profileController.java b/src/main/java/com/kimgreen/backend/domain/profile/controller/profileController.java index 7d38ac6..b37554f 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/controller/profileController.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/controller/profileController.java @@ -11,8 +11,7 @@ import java.awt.print.Pageable; -import static com.kimgreen.backend.response.Message.PROFILE_INFO_SUCCESS; -import static com.kimgreen.backend.response.Message.PROFILE_POSTS_SUCCESS; +import static com.kimgreen.backend.response.Message.*; import static com.kimgreen.backend.response.Response.success; import static org.springframework.http.HttpStatus.OK; @@ -36,5 +35,18 @@ public Response getProfilePosts(@RequestParam("memberId") Long memberId) { public Response getProfileInfo(@RequestParam("memberId") Long memberId) { return success(PROFILE_INFO_SUCCESS, profileService.getProfileInfo(memberId)); } + @Operation(summary = "설정창 내가 쓴 댓글 불러오기") + @ResponseStatus(OK) + @GetMapping("/setting/comment") + public Response getMyComment() { + return success(GET_MY_COMMENT_SUCCESS,profileService.getMyComment()); + } + + @Operation(summary = "설정창 내가 쓴 글 불러오기") + @ResponseStatus(OK) + @GetMapping("/setting/post") + public Response getMyPost() {return success(GET_MY_POST_SUCCESS, profileService.getMyPost());} + + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/CommentResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/CommentResponseDto.java new file mode 100644 index 0000000..17510dd --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/CommentResponseDto.java @@ -0,0 +1,29 @@ +package com.kimgreen.backend.domain.profile.dto.Profile; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.stereotype.Component; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class CommentResponseDto { + private Long commentId; + private Long postId; + private String writerBadge; + private String writerNickname; + private String comment; + + public static CommentResponseDto toDto(Long commentId, Long postId, String writerBadge, String writerNickname, String comment) { + return CommentResponseDto.builder() + .commentId(commentId) + .postId(postId) + .writerBadge(writerBadge) + .writerNickname(writerNickname) + .comment(comment) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetSettingPostDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetSettingPostDto.java new file mode 100644 index 0000000..944e095 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/GetSettingPostDto.java @@ -0,0 +1,48 @@ +package com.kimgreen.backend.domain.profile.dto.Profile; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class GetSettingPostDto { + private Long postId; + private String writerNickname; + private String writerBadge; + private String writerProfileImg; + private String content; + private Long likeCount; + private Long commentCount; + private String imgUrl; + private boolean isLiked; + + public static GetSettingPostDto toDto(Long postId, String content, String writerBadge, String writerNickname, String writerProfileImg, Long likeCount, Long commentCount, String imgUrl, boolean isLiked) { + return GetSettingPostDto.builder() + .postId(postId) + .content(content) + .writerBadge(writerBadge) + .writerNickname(writerNickname) + .writerProfileImg(writerProfileImg) + .likeCount(likeCount) + .commentCount(commentCount) + .imgUrl(imgUrl) + .isLiked(isLiked) + .build(); + } + public static GetSettingPostDto toDto(Long postId, String content, String writerBadge, String writerNickname, String writerProfileImg, Long likeCount, Long commentCount, boolean isLiked) { + return GetSettingPostDto.builder() + .postId(postId) + .content(content) + .writerBadge(writerBadge) + .writerNickname(writerNickname) + .writerProfileImg(writerProfileImg) + .likeCount(likeCount) + .commentCount(commentCount) + .isLiked(isLiked) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java index ea590c7..013b6ca 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/CalendarService.java @@ -146,7 +146,7 @@ public CalendarDetailDto dtoBuilderWithNoImg(Long postId, String nickname, Strin public boolean isLiked(List likesList,Member member) { for(Likes like : likesList) { - if(like.getLikeId().equals(member.getMemberId())) { + if(like.getMember().getMemberId().equals(member.getMemberId())) { return true; } } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java b/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java index bbce6d7..7fe715c 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/service/ProfileService.java @@ -1,8 +1,12 @@ package com.kimgreen.backend.domain.profile.service; import com.kimgreen.backend.domain.BadgeList; +import com.kimgreen.backend.domain.community.entity.Comment; import com.kimgreen.backend.domain.community.entity.Likes; import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.PostImg; +import com.kimgreen.backend.domain.community.repository.CommentRepository; +import com.kimgreen.backend.domain.community.repository.LikeRepository; import com.kimgreen.backend.domain.community.repository.PostImgRepository; import com.kimgreen.backend.domain.community.repository.PostRepository; import com.kimgreen.backend.domain.community.service.S3Service; @@ -11,11 +15,14 @@ import com.kimgreen.backend.domain.member.repository.MemberProfileImgRepository; import com.kimgreen.backend.domain.member.repository.MemberRepository; import com.kimgreen.backend.domain.member.service.MemberService; +import com.kimgreen.backend.domain.profile.dto.Profile.CommentResponseDto; import com.kimgreen.backend.domain.profile.dto.Profile.GetProfileDto; +import com.kimgreen.backend.domain.profile.dto.Profile.GetSettingPostDto; import com.kimgreen.backend.domain.profile.entity.ProfileBadge; import com.kimgreen.backend.domain.profile.entity.RepresentativeBadge; import com.kimgreen.backend.domain.profile.repository.ProfileBadgeRepository; import com.kimgreen.backend.domain.profile.repository.RepresentativeBadgeRepository; +import com.kimgreen.backend.exception.PostNotFound; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import com.kimgreen.backend.domain.profile.dto.Profile.GetProfilePostDto; @@ -37,6 +44,8 @@ public class ProfileService { private final PostRepository postRepository; private final PostImgRepository postImgRepository; private final GetProfilePostDto getProfilePostDto; + private final CommentRepository commentRepository; + private final LikeRepository likeRepository; public List response(Long memberId){ List list = new ArrayList<>(); @@ -115,4 +124,52 @@ public GetProfileDto getProfileInfo(Long memberId){ ); } + public List getMyComment() { + Member member = memberService.getCurrentMember(); + String writer = member.getNickname(); + String writerBadge = representativeBadgeRepository.findByMember(member).getRepresentativeBadge().name; + List comments = commentRepository.findByMember(member); + + List dto = new ArrayList<>(); + for(Comment comment : comments) { + Post post = postRepository.findById(comment.getPost().getPostId()).orElseThrow(PostNotFound::new); + CommentResponseDto commentDto = CommentResponseDto.toDto(comment.getCommentId(),post.getPostId(),writerBadge,writer,comment.getContent()); + dto.add(commentDto); + } + return dto; + } + + public List getMyPost() { + Member member = memberService.getCurrentMember(); + String writer = member.getNickname(); + String writerBadge = representativeBadgeRepository.findByMember(member).getRepresentativeBadge().name; + String writerProfileImg = s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl()); + List posts = postRepository.findByMember(member); + + List dto = new ArrayList<>(); + for (Post post : posts) { + Long countLike = likeRepository.countLike(post.getPostId()); + List likes = post.getLikes(); + boolean isLiked = isLiked(likes, member); + Long countComment = commentRepository.countComment(post.getPostId()); + PostImg postImg = postImgRepository.findByPost(post); + if (postImg != null) { + dto.add(GetSettingPostDto.toDto(post.getPostId(), post.getContent(), writerBadge, writer, writerProfileImg, countLike, countComment, s3Service.getFullUrl(postImg.getImgUrl()),isLiked)); + } else { + dto.add(GetSettingPostDto.toDto(post.getPostId(), post.getContent(), writerBadge, writer, writerProfileImg, countLike, countComment,isLiked)); + } + + } + return dto; + } + + public boolean isLiked(List likesList, Member member) { + for(Likes like : likesList) { + if(like.getMember().getMemberId().equals(member.getMemberId())) { + return true; + } + } + return false; + } + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/response/Message.java b/src/main/java/com/kimgreen/backend/response/Message.java index f0dcfa8..83edee3 100644 --- a/src/main/java/com/kimgreen/backend/response/Message.java +++ b/src/main/java/com/kimgreen/backend/response/Message.java @@ -41,5 +41,6 @@ public class Message { public static String SET_LIKES_SUCCESS="게시글 좋아요 or 취소하기 성공했습니다."; public static String PROFILE_INFO_SUCCESS="프로필 불러오기 성공했습니다."; public static String PROFILE_POSTS_SUCCESS="쓴 글 목록 불러오기 성공했습니다"; - + public static String GET_MY_COMMENT_SUCCESS = "내가 쓴 댓글 보기 성공했습니다."; + public static String GET_MY_POST_SUCCESS = "내가 쓴 글 보기 성공했습니다."; } \ No newline at end of file From b4aa27e2983eb2dc16b041bed72c4612b6829bef Mon Sep 17 00:00:00 2001 From: gol2580 Date: Mon, 5 Feb 2024 13:42:58 +0900 Subject: [PATCH 72/72] [fix] post services --- .../community/controller/PostController.java | 13 +- .../community/dto/BestPostResponseDto.java | 15 +++ .../community/dto/GetPostInfoRequestDto.java | 18 +++ .../backend/domain/community/entity/Post.java | 3 +- .../domain/community/entity/PostImg.java | 6 +- .../community/repository/PostRepository.java | 10 ++ .../domain/community/service/PostService.java | 115 ++++++++++-------- .../domain/community/service/S3Service.java | 5 - .../dto/Profile/CommentResponseDto.java | 3 +- .../backend/exception/MemberNotFound.java | 4 + .../com/kimgreen/backend/response/Advice.java | 40 +++++- 11 files changed, 160 insertions(+), 72 deletions(-) create mode 100644 src/main/java/com/kimgreen/backend/domain/community/dto/BestPostResponseDto.java create mode 100644 src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoRequestDto.java create mode 100644 src/main/java/com/kimgreen/backend/exception/MemberNotFound.java diff --git a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java index 90200ff..7d6deac 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java +++ b/src/main/java/com/kimgreen/backend/domain/community/controller/PostController.java @@ -1,6 +1,7 @@ package com.kimgreen.backend.domain.community.controller; import com.fasterxml.jackson.annotation.JsonIgnore; +import com.kimgreen.backend.domain.community.dto.GetPostInfoRequestDto; import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; import com.kimgreen.backend.domain.community.entity.Category; import com.kimgreen.backend.domain.member.entity.Member; @@ -13,6 +14,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import com.kimgreen.backend.domain.community.entity.*; import java.io.IOException; @@ -26,7 +28,6 @@ @RestController @RequiredArgsConstructor @RequestMapping(value="/post") - public class PostController { private final PostService postService; @@ -54,15 +55,17 @@ public Response writeDailyPost(@RequestPart(name = "jsonData") WritePostRequestD @Operation(summary = "게시글 상세 보기") @ResponseStatus(OK) @GetMapping() - public Response getPostInfo(Long postId){ + public Response getPostInfo(@RequestParam(name="postId") Long postId){ return success(GET_POST_SUCCESS, postService.getPostInfo(postId)); } @Operation(summary = "게시글 목록 불러오기") @ResponseStatus(OK) - @GetMapping("/{category}") - public Response getPostList(Category category, com.kimgreen.backend.domain.community.entity.Tag tag) { - return success(GET_POST_LIST_SUCCESS, postService.getPostlist(category, tag)); + @GetMapping("/list") + public Response getPostList(@RequestParam(name="category", required = false) Category category, + @RequestParam(name="tag", required = false) com.kimgreen.backend.domain.community.entity.Tag tag, + @RequestParam(name="search", required = false) String search) { + return success(GET_POST_LIST_SUCCESS, postService.getPostlist(category, tag, search)); } @JsonIgnore diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/BestPostResponseDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/BestPostResponseDto.java new file mode 100644 index 0000000..8d835b8 --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/BestPostResponseDto.java @@ -0,0 +1,15 @@ +package com.kimgreen.backend.domain.community.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class BestPostResponseDto { + private Long postId; + private String content; +} diff --git a/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoRequestDto.java b/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoRequestDto.java new file mode 100644 index 0000000..b31f6bc --- /dev/null +++ b/src/main/java/com/kimgreen/backend/domain/community/dto/GetPostInfoRequestDto.java @@ -0,0 +1,18 @@ +package com.kimgreen.backend.domain.community.dto; + +import com.kimgreen.backend.domain.community.entity.Category; +import com.kimgreen.backend.domain.community.entity.Tag; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class GetPostInfoRequestDto { + private Category category; + private Tag tag; + private String search; +} diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java index 74912e9..cdc4a87 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/Post.java @@ -50,11 +50,10 @@ public class Post extends AuditEntity { @Enumerated(EnumType.STRING) private Tag tag; - @JsonIgnore + @Formula("(SELECT COUNT(*) FROM likes l WHERE l.post_id = post_id)") private int likeCount; - @JsonIgnore public void update(String category, String content) { this.category = Category.valueOf(category); this.content = content; diff --git a/src/main/java/com/kimgreen/backend/domain/community/entity/PostImg.java b/src/main/java/com/kimgreen/backend/domain/community/entity/PostImg.java index 0125093..468588a 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/entity/PostImg.java +++ b/src/main/java/com/kimgreen/backend/domain/community/entity/PostImg.java @@ -2,16 +2,14 @@ import com.kimgreen.backend.domain.AuditEntity; import jakarta.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; +import lombok.*; @Getter @NoArgsConstructor @AllArgsConstructor @Entity @Builder +@Setter public class PostImg extends AuditEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java index 84ba79d..79d87b1 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java +++ b/src/main/java/com/kimgreen/backend/domain/community/repository/PostRepository.java @@ -1,7 +1,9 @@ package com.kimgreen.backend.domain.community.repository; import com.kimgreen.backend.domain.community.dto.GetPostInfoResponseDto; +import com.kimgreen.backend.domain.community.entity.Category; import com.kimgreen.backend.domain.community.entity.Post; +import com.kimgreen.backend.domain.community.entity.Tag; import com.kimgreen.backend.domain.member.entity.Member; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -19,4 +21,12 @@ public interface PostRepository extends JpaRepository { List findByMember(Member member); public List findTop3ByOrderByLikeCountDesc(); + List findByContentContaining(String content); + List findByTagAndContentContaining(Tag tag, String content); + List findByCategoryAndContentContaining(Category category, String content); + List findByCategoryAndTagAndContentContaining(Category category, Tag tag,String content); + List findByTag(Tag tag); + List findByCategory(Category category); + List findByCategoryAndTag(Category category, Tag tag); + } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java index f66f1d1..7597dff 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/PostService.java @@ -1,5 +1,7 @@ package com.kimgreen.backend.domain.community.service; +import com.kimgreen.backend.domain.community.dto.BestPostResponseDto; +import com.kimgreen.backend.domain.community.dto.GetPostInfoRequestDto; import com.kimgreen.backend.domain.community.dto.GetPostInfoResponseDto; import com.kimgreen.backend.domain.community.dto.WritePostRequestDto; import com.kimgreen.backend.domain.community.entity.*; @@ -23,6 +25,7 @@ import java.io.IOException; import java.time.LocalDateTime; import java.time.LocalTime; +import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; @@ -165,6 +168,7 @@ public GetPostInfoResponseDto getPostInfo(Long postId) { .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl())) .imgUrl(s3Service.getFullUrl(postImgRepository.findByPost(post).getImgUrl())) .content(post.getContent()) + .tag(post.getTag().toString()) .postId(post.getPostId()) .category(String.valueOf(post.getCategory())) .writerBadge(representativeBadgeRepository.findByMember(post.getMember()).getRepresentativeBadge().name) @@ -172,7 +176,7 @@ public GetPostInfoResponseDto getPostInfo(Long postId) { .commentCount(post.getComments().size()) .isLiked(isLiked) .isMine(post.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())) - .updatedAt(String.valueOf(post.getModifiedAt())) + .updatedAt(post.getModifiedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) .build(); } return GetPostInfoResponseDto.builder() @@ -180,53 +184,49 @@ public GetPostInfoResponseDto getPostInfo(Long postId) { .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl())) .content(post.getContent()) .postId(post.getPostId()) + .tag(post.getTag().toString()) .category(String.valueOf(post.getCategory())) .writerBadge(representativeBadgeRepository.findByMember(post.getMember()).getRepresentativeBadge().name) .likeCount(post.getLikes().size()) .commentCount(post.getComments().size()) .isLiked(isLiked) .isMine(post.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())) - .updatedAt(String.valueOf(post.getModifiedAt())) + .updatedAt(post.getModifiedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) .build(); } - @Transactional - public List getPostlist(Category category, Tag tag) { - List posts = postRepository.findAll(); + @Transactional(readOnly = true) + public List getPostlist(Category category, Tag tag, String search) { + List postList = new ArrayList<>(); + List posts = findPosts(category,tag,search); for (Post post : posts) { -/* - - if (post.getTag() != Tag.DAILY || !post.getCategory().equals(category)) { - continue; - } -*/ Member member = post.getMember(); List likeList = post.getLikes(); boolean isLiked = isLiked(likeList, member); + PostImg postImg = postImgRepository.findByPost(post); - Optional optionalPostImg = Optional.ofNullable(postImgRepository.findByPost(post)); - String imgUrl = optionalPostImg.map(img -> s3Service.getFullUrl(img.getImgUrl())).orElse("defaultImageUrl"); GetPostInfoResponseDto getPostInfoResponseDto = GetPostInfoResponseDto.builder() .writerNickname(post.getMember().getNickname()) .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl())) .content(post.getContent()) .postId(post.getPostId()) - .category(String.valueOf(post.getCategory())) + .category(post.getCategory().toString()) + .tag(post.getTag().toString()) .writerBadge(representativeBadgeRepository.findByMember(member).getRepresentativeBadge().name) .likeCount(post.getLikes().size()) .commentCount(post.getComments().size()) .isLiked(isLiked) .isMine(post.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())) - .updatedAt(String.valueOf(post.getModifiedAt())) + .updatedAt(post.getModifiedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))) .build(); - if (post.getPostImg() != null) { - getPostInfoResponseDto.setImgUrl(s3Service.getFullUrl(postImgRepository.findByPost(post).getImgUrl())); + if (postImg!= null) { + getPostInfoResponseDto.setImgUrl(s3Service.getFullUrl(postImg.getImgUrl())); } postList.add(getPostInfoResponseDto); } @@ -239,7 +239,8 @@ public void deletePost(Long postId) { Member member = memberService.getCurrentMember(); Post post = postRepository.findById(postId).orElseThrow(PostNotFound::new); Badge badge = badgeRepository.findByMember(member); - + //이미지 삭제 + deletePostImg(post); // 게시글 삭제 postRepository.delete(post); decreaseBadgeCount(badge, post.getCategory(), post.getTag()); @@ -256,14 +257,30 @@ public void editPost(Long postId, WritePostRequestDto editPostInfoRequestDto, Mu post.update(editPostInfoRequestDto.getCategory(), editPostInfoRequestDto.getContent()); + if (multipartFile != null) { - uploadPostFileList(multipartFile, post); + PostImg postImg = postImgRepository.findByPost(post); + //postImg 원래 존재하면 + if(postImg!=null) { + s3Service.delete(postImg.getImgUrl()); + postImg.setImgUrl(s3Service.saveFile(multipartFile)); + } + //postImg 존재하지 않았으면 + else { + uploadPostFileList(multipartFile,post); + } + } else { + PostImg postImg = postImgRepository.findByPost(post); + if(postImg!=null) { + s3Service.delete(postImg.getImgUrl()); + postImgRepository.delete(postImg); + } } } public boolean isLiked(List likesList,Member member) { for(Likes like : likesList) { - if(like.getLikeId().equals(member.getMemberId())) { + if(like.getMember().getMemberId().equals(member.getMemberId())) { return true; } } @@ -271,40 +288,38 @@ public boolean isLiked(List likesList,Member member) { } //좋아요 상위 목록 불러오기 - @JsonIgnore @Transactional - public List getBestPostList() { + public List getBestPostList() { List bestPost = postRepository.findTop3ByOrderByLikeCountDesc(); - List postList = new ArrayList<>(); - - for (Post post : bestPost) { - - Member member = post.getMember(); - List likeList = post.getLikes(); - boolean isLiked = isLiked(likeList, member); - - Optional optionalPostImg = Optional.ofNullable(postImgRepository.findByPost(post)); - String imgUrl = optionalPostImg.map(img -> s3Service.getFullUrl(img.getImgUrl())).orElse("defaultImageUrl"); + List result = new ArrayList<>(); - GetPostInfoResponseDto getPostInfoResponseDto = GetPostInfoResponseDto.builder() - .writerNickname(post.getMember().getNickname()) - .writerProfileImg(s3Service.getFullUrl(memberProfileImgRepository.findByMember(member).getImgUrl())) - .content(post.getContent()) - .postId(post.getPostId()) - .category(String.valueOf(post.getCategory())) - .writerBadge(representativeBadgeRepository.findByMember(member).getRepresentativeBadge().name) - .likeCount(post.getLikes().size()) - .commentCount(post.getComments().size()) - .isLiked(isLiked) - .isMine(post.getMember().getMemberId().equals(memberService.getCurrentMember().getMemberId())) - .updatedAt(String.valueOf(post.getModifiedAt())) - .build(); + for(Post post : bestPost) { + result.add(BestPostResponseDto.builder() + .postId(post.getPostId()) + .content(post.getContent()) + .build()); + } + return result; + } - if (post.getPostImg() != null) { - getPostInfoResponseDto.setImgUrl(s3Service.getFullUrl(postImgRepository.findByPost(post).getImgUrl())); - } - postList.add(getPostInfoResponseDto); + public void deletePostImg(Post post) { + PostImg postImg = postImgRepository.findByPost(post); + if(postImg!=null) { + s3Service.delete(s3Service.getFullUrl(postImg.getImgUrl())); + postImgRepository.delete(postImg); } - return bestPost; + } + + public List findPosts(Category category, Tag tag, String search) { + + if(category==null && tag==null && search==null) {return postRepository.findAll();} + if(category==null && tag==null && search!=null) {return postRepository.findByContentContaining(search);} + if(category==null && tag!=null && search!=null) {return postRepository.findByTagAndContentContaining(tag, search);} + if(category!=null && tag==null && search!=null) {return postRepository.findByCategoryAndContentContaining(category, search);} + if(category!=null && tag!=null && search!=null) {return postRepository.findByCategoryAndTagAndContentContaining(category,tag,search);} + if(category==null && tag!=null && search==null) {return postRepository.findByTag(tag);} + if(category!=null && tag==null && search==null) {return postRepository.findByCategory(category);} + if(category!=null && tag!=null && search==null) {return postRepository.findByCategoryAndTag(category,tag);} + return new ArrayList<>(); } } \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java index 2ae32b2..4b72cc2 100644 --- a/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java +++ b/src/main/java/com/kimgreen/backend/domain/community/service/S3Service.java @@ -35,11 +35,6 @@ public String saveFile(MultipartFile multipartFile) throws IOException { metadata.setContentType(multipartFile.getContentType()); amazonS3.putObject(bucket, createdFilename, multipartFile.getInputStream(), metadata); - - uploadDB(PostImg.builder() - .imgUrl(createdFilename) - .title(originalFilename) - .build()); return createdFilename; } diff --git a/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/CommentResponseDto.java b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/CommentResponseDto.java index fb3e41e..17510dd 100644 --- a/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/CommentResponseDto.java +++ b/src/main/java/com/kimgreen/backend/domain/profile/dto/Profile/CommentResponseDto.java @@ -25,4 +25,5 @@ public static CommentResponseDto toDto(Long commentId, Long postId, String write .writerNickname(writerNickname) .comment(comment) .build(); - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/src/main/java/com/kimgreen/backend/exception/MemberNotFound.java b/src/main/java/com/kimgreen/backend/exception/MemberNotFound.java new file mode 100644 index 0000000..3c358bb --- /dev/null +++ b/src/main/java/com/kimgreen/backend/exception/MemberNotFound.java @@ -0,0 +1,4 @@ +package com.kimgreen.backend.exception; + +public class MemberNotFound extends RuntimeException{ +} diff --git a/src/main/java/com/kimgreen/backend/response/Advice.java b/src/main/java/com/kimgreen/backend/response/Advice.java index f3c5989..2f56bcd 100644 --- a/src/main/java/com/kimgreen/backend/response/Advice.java +++ b/src/main/java/com/kimgreen/backend/response/Advice.java @@ -1,10 +1,7 @@ package com.kimgreen.backend.response; -import com.kimgreen.backend.exception.DuplicateEmail; -import com.kimgreen.backend.exception.LogInFailureEmail; -import com.kimgreen.backend.exception.LogInFailurePassword; -import com.kimgreen.backend.exception.RefreshTokenExpired; +import com.kimgreen.backend.exception.*; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @@ -17,7 +14,7 @@ public class Advice { @ResponseStatus(HttpStatus.CONFLICT) public Response DuplicateEmailResponse() { return Response.failure(HttpStatus.CONFLICT, "중복 이메일입니다."); -} + } @ExceptionHandler(LogInFailureEmail.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @@ -36,8 +33,41 @@ public Response RefreshTokenExpiredResponse() { return Response.failure(HttpStatus.UNAUTHORIZED, "리프레시 토큰이 유효하지 않습니다."); } + @ExceptionHandler(MaxUploadSizeExceeded.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public Response MaxUploadSizeExceededResponse() { + return Response.failure(HttpStatus.INTERNAL_SERVER_ERROR, "파일 업로드 최대 용량을 초과했습니다.: 50MB"); + } + + @ExceptionHandler(BadgeNotFound.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Response BadgeNotFoundResponse() { + return Response.failure(HttpStatus.NOT_FOUND,"요청한 뱃지를 찾을 수 없습니다."); + } + @ExceptionHandler(PostNotFound.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Response PostNotFoundResponse() { + return Response.failure(HttpStatus.NOT_FOUND, "요청한 게시글을 찾을 수 없습니다."); + } + @ExceptionHandler(WrongPath.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Response WrongPath() { + return Response.failure(HttpStatus.NOT_FOUND, "잘못된 경로입니다."); + } + + @ExceptionHandler(LogInRequiredException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Response LogInRequiredResponse() { + return Response.failure(HttpStatus.NOT_FOUND, "토큰이 존재하지 않습니다. 로그인 후 이용해주세요."); + } + + @ExceptionHandler(MemberNotFound.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Response MemberNotFoundResponse() { + return Response.failure(HttpStatus.NOT_FOUND, "요청한 멤버가 존재하지 않습니다."); + } }