Skip to content

Commit

Permalink
feature / Record add API(read, update, delete, recent read, report) #14
Browse files Browse the repository at this point in the history
  • Loading branch information
SeWooooong committed Mar 24, 2023
1 parent 99ca826 commit a771830
Show file tree
Hide file tree
Showing 15 changed files with 402 additions and 6 deletions.
4 changes: 4 additions & 0 deletions src/main/java/com/todaysgym/todaysgym/post/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,8 @@ public class Post extends BaseTimeEntity {

@OneToMany(mappedBy = "post", cascade = {CascadeType.ALL}, orphanRemoval = true)
private List<PostPhoto> photoList = new ArrayList<>();

public void deleteRecord(){
this.record = null;
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package com.todaysgym.todaysgym.post;

import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface PostRepository extends JpaRepository<Post, Long> {
Optional<Post> getByPostId(Long postId);

@Query("select p from Post p where p.record.recordId = :recordId")
List<Post> findPostByRecord(@Param("recordId") Long recordId);
}
25 changes: 25 additions & 0 deletions src/main/java/com/todaysgym/todaysgym/post/PostService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.todaysgym.todaysgym.post;

import com.todaysgym.todaysgym.config.exception.BaseException;
import com.todaysgym.todaysgym.post.PostRepository;
import com.todaysgym.todaysgym.record.photo.RecordPhotoRepository;
import com.todaysgym.todaysgym.record.photo.RecordPhotoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.todaysgym.todaysgym.config.exception.errorCode.RecordErrorCode.EMPTY_RECORD;

@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;

/**
* 기록과 관련된 게시글 조회 후 기록 null로 변경
*/
public List<Post> deleteRecord(Long recordId){
return postRepository.findPostByRecord(recordId);
}
}
5 changes: 4 additions & 1 deletion src/main/java/com/todaysgym/todaysgym/record/Record.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,13 @@ public void createPhotoList(RecordPhoto recordPhoto){
photoList.add(recordPhoto);
recordPhoto.createRecord(this);
}

public void addTagList(Tag tag){
tagList.add(tag);
tag.createRecord(this);
}
public void updateRecord(String content){
this.content = content;
}
public void addReport(){ this.report++; }

}
55 changes: 55 additions & 0 deletions src/main/java/com/todaysgym/todaysgym/record/RecordController.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package com.todaysgym.todaysgym.record;

import com.todaysgym.todaysgym.config.response.BaseResponse;
import com.todaysgym.todaysgym.record.dto.RecordGetRecentRes;
import com.todaysgym.todaysgym.record.dto.RecordGetReq;
import com.todaysgym.todaysgym.record.dto.RecordGetRes;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
Expand All @@ -24,4 +29,54 @@ public BaseResponse<String> createRecord(@RequestPart(value = "image", required
@RequestPart(value = "recordGetReq") @Valid RecordGetReq recordGetReq){
return new BaseResponse<>(recordService.saveRecord(multipartFiles, recordGetReq));
}

/**
* Record, 사진, 태그 조회 (달 기준)
*/
@GetMapping("/record/month")
public BaseResponse<List<RecordGetRes>> getRecordMonth(@Param("month") String month){
return new BaseResponse<>(recordService.findRecordByMonth(month));
}

/**
* Record, 사진, 태그 조회 (날짜 기준)
*/
@GetMapping("/record/day")
public BaseResponse<RecordGetRes> getRecordDay(@Param("date") String date){
return new BaseResponse<>(recordService.findRecordByDay(date));
}

/**
* 기록 수정하기
*/
@PostMapping("/record/update")
public BaseResponse<String> updateRecord(@Param("date") String date,
@RequestPart(value = "recordGetReq") @Valid RecordGetReq recordGetReq,
@RequestPart(value = "image", required = false) List<MultipartFile> multipartFiles){
return new BaseResponse<>(recordService.updateRecord(date, recordGetReq, multipartFiles));
}

/**
* 기록 삭제하기
*/
@PostMapping("/record/delete")
public BaseResponse<String> deleteRecord(@Param("date") String date){
return new BaseResponse<>(recordService.deleteRecord(date));
}

/**
* 최근 기록 조회하기
*/
@GetMapping("/record/recent")
public Page<RecordGetRecentRes> findRecentRecord(@Param("page") int page){
return recordService.findRecordRecent(page);
}

/**
* 기록 신고하기
*/
@GetMapping("/record/report")
public BaseResponse<String> reportRecord(@Param("date") String date){
return new BaseResponse<>(recordService.reportRecord(date));
}
}
21 changes: 19 additions & 2 deletions src/main/java/com/todaysgym/todaysgym/record/RecordRepository.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
package com.todaysgym.todaysgym.record;

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

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface RecordRepository extends JpaRepository<Record, Long> {
Optional<Record> getByRecordId(Long recordId);

@Query("select count(r) from Record r where FORMATDATETIME(r.createdAt, 'yyyy-MM-dd') = :date and r.member.memberId = :memberId")
Integer findByRecordDate(@Param("date") String date, @Param("memberId") Long memberId);
@Query("select count(r) from Record r where date_format(r.createdAt, '%Y-%m-%d') = :date and r.member.memberId = :memberId")
Integer findByRecordCount(@Param("date") String date, @Param("memberId") Long memberId);

@Query("select r from Record r where date_format(r.createdAt, '%Y-%m-%d') = :date and r.member.memberId = :memberId")
Record findByRecordDate(@Param("date") String date, @Param("memberId") Long memberId);

@Query("select r from Record r where date_format(r.createdAt, '%Y-%m') = :month and r.member.memberId = :memberId")
List<Record> findByRecordMonth(@Param("month") String month, @Param("memberId") Long memberId);

@Modifying
@Query("delete from Record r where r.recordId = :recordId")
Integer deleteAllByRecordId(@Param("recordId") Long recordId);

@Query("select r from Record r where r.member.memberId = :memberId")
Page<Record> findAllByUserId(@Param("memberId") Long memberId, PageRequest pageRequest);
}
136 changes: 133 additions & 3 deletions src/main/java/com/todaysgym/todaysgym/record/RecordService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,34 @@

import com.todaysgym.todaysgym.config.exception.BaseException;
import com.todaysgym.todaysgym.member.Member;
import com.todaysgym.todaysgym.post.Post;
import com.todaysgym.todaysgym.post.PostService;
import com.todaysgym.todaysgym.record.dto.RecordGetRecentRes;
import com.todaysgym.todaysgym.record.dto.RecordGetReq;
import com.todaysgym.todaysgym.record.dto.RecordGetRes;
import com.todaysgym.todaysgym.record.photo.RecordPhoto;
import com.todaysgym.todaysgym.record.photo.RecordPhotoService;
import com.todaysgym.todaysgym.tag.TagService;
import com.todaysgym.todaysgym.utils.S3Service;
import com.todaysgym.todaysgym.utils.UtilService;
import com.todaysgym.todaysgym.utils.dto.getS3Res;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

import static com.todaysgym.todaysgym.config.exception.errorCode.RecordErrorCode.EMPTY_RECORD;
import static com.todaysgym.todaysgym.config.exception.errorCode.RecordErrorCode.RECORD_DATE_EXISTS;

@Service
Expand All @@ -29,6 +41,7 @@ public class RecordService {
private final S3Service s3Service;
private final RecordPhotoService recordPhotoService;
private final TagService tagService;
private final PostService postService;
/**
* Record, photo, tag 저장
*/
Expand Down Expand Up @@ -60,9 +73,126 @@ public String saveRecord(List<MultipartFile> multipartFiles, RecordGetReq record
private void validateDuplicateRecord() throws BaseException {
Member member = utilService.findByMemberIdWithValidation(1L);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Integer count = recordRepository.findByRecordDate(ZonedDateTime.now(ZoneId.of("Asia/Seoul")).format(formatter).toString() , member.getMemberId());
if(count > 0){
throw new BaseException(RECORD_DATE_EXISTS);
Integer count = recordRepository.findByRecordCount(ZonedDateTime.now(ZoneId.of("Asia/Seoul")).format(formatter).toString() , member.getMemberId());
if(count > 0) throw new BaseException(RECORD_DATE_EXISTS);

}

/**
* y-m-d에 따라 기록 조회
*/
public RecordGetRes findRecordByDay(String date) throws BaseException {
Member member = utilService.findByMemberIdWithValidation(1L);
Record record = recordRepository.findByRecordDate(date, member.getMemberId());
if(record == null) throw new BaseException(EMPTY_RECORD);
record = utilService.findByRecordIdWithValidation(record.getRecordId());
RecordGetRes recordGetRes = new RecordGetRes(record, member);
return recordGetRes;
}

/**
* y-m에 따라 기록 조회
*/
public List<RecordGetRes> findRecordByMonth(String month) throws BaseException {
Member member = utilService.findByMemberIdWithValidation(1L);
List<Record> records = recordRepository.findByRecordMonth(month, member.getMemberId());
if(records.isEmpty()) throw new BaseException(EMPTY_RECORD);
List<RecordGetRes> recordGetRes = records.stream()
.map(record-> new RecordGetRes(record, member))
.collect(Collectors.toList());
return recordGetRes;
}

/**
* 기록 수정하기
*/
@Transactional
@Modifying
public String updateRecord(String date, RecordGetReq recordGetReq, List<MultipartFile> multipartFiles) throws BaseException {
//1. User, Record 조회 한 후 Record update
Member member = utilService.findByMemberIdWithValidation(1L);
Record record = recordRepository.findByRecordDate(date, member.getMemberId());
if(record == null) throw new BaseException(EMPTY_RECORD);
record = utilService.findByRecordIdWithValidation(record.getRecordId());
record.updateRecord(recordGetReq.getContent());

//2. RecordPhoto 삭제
List<RecordPhoto> recordPhotos = recordPhotoService.findByRecordId(record.getRecordId());
recordPhotoService.deleteAllRecordPhotos(recordPhotos);
List<Long> ids = recordPhotoService.findAllId(record.getRecordId());
recordPhotoService.deleteAllRecordPhotoByRecord(ids);
//3. RecordPhoto 추가
if(multipartFiles != null) {
List<getS3Res> imgUrls = s3Service.uploadFile(multipartFiles);
recordPhotoService.saveAllRecordPhotoByRecord(imgUrls, record);
}

//Tag 수정
List<Long> tIds = tagService.findAllId(record.getRecordId());
System.out.println(tIds.size());
tagService.deleteAllTagByRecord(tIds);
tagService.saveAllTagByRecord(recordGetReq,record);
return "기록을 수정했습니다.";
}

/**
* 기록 삭제하기 연관된 사진, 태그도 모두 삭제
* (태그를 삭제하면 최근 사용한 태그를 조회 불가)
*/
@Transactional
@Modifying
public String deleteRecord(String date) throws BaseException {
//1. 로그인 되어 있는 멤버와 관련된 기록 가져옴
Member member = utilService.findByMemberIdWithValidation(1L);
Record record = recordRepository.findByRecordDate(date, member.getMemberId());
if(record == null) throw new BaseException(EMPTY_RECORD);

//2. recordPhoto 삭제
List<RecordPhoto> recordPhotos = recordPhotoService.findByRecordId(record.getRecordId());
recordPhotoService.deleteAllRecordPhotos(recordPhotos);
List<Long> ids = recordPhotoService.findAllId(record.getRecordId());
recordPhotoService.deleteAllRecordPhotoByRecord(ids);

//3. 태그 삭제
List<Long> tIds = tagService.findAllId(record.getRecordId());
tagService.deleteAllTagByRecord(tIds);

//4. 기록과 관련된 게시글에 기록 삭제
List<Post> posts = postService.deleteRecord(record.getRecordId());

if(!posts.isEmpty()){
for(Post post : posts){
post.deleteRecord();
}
}
System.out.println(posts.size());
//Record 삭제
recordRepository.deleteAllByRecordId(record.getRecordId());
return "기록을 삭제했습니다.";
}


/**
* 최근 기록 조회
*/
public Page<RecordGetRecentRes> findRecordRecent(int page) throws BaseException {
Member member = utilService.findByMemberIdWithValidation(1L);
PageRequest pageRequest = PageRequest.of(page, 6, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Record> records = recordRepository.findAllByUserId(member.getMemberId(), pageRequest);
if (records.getTotalElements() == 0) throw new BaseException(EMPTY_RECORD);
Page<RecordGetRecentRes> results = records.map(r -> new RecordGetRecentRes(r.getRecordId(), r.getContent(), r.getCreatedAt(), r.getPhotoList()));
return results;
}

/**
* 기록 신고하기
*/
@Transactional
public String reportRecord(String date) throws BaseException {
Member member = utilService.findByMemberIdWithValidation(1L);
Record record = recordRepository.findByRecordDate(date, member.getMemberId());
record.addReport();
return "신고가 접수되었습니다";
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.todaysgym.todaysgym.record.dto;

import com.todaysgym.todaysgym.record.photo.RecordPhoto;
import com.todaysgym.todaysgym.utils.UtilService;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.List;

@Data
public class RecordGetRecentRes {
private Long recordId;
private String content;
private String createdTime;
private String imgUrl;
public RecordGetRecentRes(Long recordId, String content, LocalDateTime createdAt, List<RecordPhoto> recordPhotos) {
this.recordId = recordId;
this.content = content;
this.createdTime = UtilService.convertLocalDateTimeToLocalDate(createdAt);
if (recordPhotos.isEmpty()) {
this.imgUrl = "";
} else {
this.imgUrl = recordPhotos.get(0).getImgUrl();
}
}
}
Loading

0 comments on commit a771830

Please sign in to comment.