Skip to content

Commit

Permalink
Merge pull request #60 from kakao-tech-campus-2nd-step3/weekly/7
Browse files Browse the repository at this point in the history
merge: 7주차 작업 master에 반영
  • Loading branch information
peeerr authored Oct 22, 2024
2 parents 8dab3f2 + 926b59c commit 1f40cfe
Show file tree
Hide file tree
Showing 12 changed files with 78 additions and 58 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package com.potatocake.everymoment.controller;

import com.potatocake.everymoment.dto.SuccessResponse;
import com.potatocake.everymoment.dto.request.FileRequest;
import com.potatocake.everymoment.dto.response.FileResponse;
import com.potatocake.everymoment.security.MemberDetails;
import com.potatocake.everymoment.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
Expand Down Expand Up @@ -34,10 +34,12 @@ public class FileController {
private final FileService fileService;

@Operation(summary = "파일 목록 조회", description = "특정 일기의 파일 목록을 조회합니다.")
@ApiResponse(responseCode = "200", description = "파일 목록 조회 성공", content = @Content(schema = @Schema(implementation = FileResponse.class)))
@ApiResponse(responseCode = "200", description = "파일 목록 조회 성공", content = @Content(array = @ArraySchema(schema = @Schema(implementation = FileResponse.class))))
@GetMapping
public ResponseEntity<SuccessResponse<FileResponse>> getFiles(@Parameter(description = "조회할 일기 ID", required = true)
@PathVariable Long diaryId) {
public ResponseEntity<SuccessResponse<List<FileResponse>>> getFiles(
@Parameter(description = "조회할 일기 ID", required = true)
@PathVariable Long diaryId
) {
List<FileResponse> files = fileService.getFiles(diaryId);

return ResponseEntity.ok()
Expand All @@ -53,11 +55,9 @@ public ResponseEntity<SuccessResponse> uploadFiles(
@Parameter(description = "인증된 사용자 정보", hidden = true)
@AuthenticationPrincipal MemberDetails memberDetails,
@Parameter(description = "업로드할 파일 목록", required = true)
@RequestPart List<MultipartFile> files,
@Parameter(description = "일기에 보일 파일 이름과 순서", required = true)
@RequestPart List<FileRequest> info
@RequestPart List<MultipartFile> files
) {
fileService.uploadFiles(diaryId, memberDetails.getId(), files, info);
fileService.uploadFiles(diaryId, memberDetails.getId(), files);

return ResponseEntity.ok()
.body(SuccessResponse.ok());
Expand All @@ -72,11 +72,9 @@ public ResponseEntity<SuccessResponse> updateFiles(
@Parameter(description = "인증된 사용자 정보", hidden = true)
@AuthenticationPrincipal MemberDetails memberDetails,
@Parameter(description = "수정할 파일 목록", required = true)
@RequestPart List<MultipartFile> files,
@Parameter(description = "일기에 보일 파일 이름과 순서", required = true)
@RequestPart List<FileRequest> info
@RequestPart List<MultipartFile> files
) {
fileService.updateFiles(diaryId, memberDetails.getId(), files, info);
fileService.updateFiles(diaryId, memberDetails.getId(), files);

return ResponseEntity.ok()
.body(SuccessResponse.ok());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ public List<String> getEmojis() {
: Collections.emptyList();
}

public List<Long> getCategories() {
public List<String> getCategories() {
return (category != null && !category.isEmpty())
? Arrays.stream(category.split(","))
.map(Long::parseLong)
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList())
: Collections.emptyList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,5 @@ public class DiaryManualCreateRequest {
private boolean isBookmark;
private boolean isPublic;
private String emoji;
private List<FileRequest> file;
private String content;
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ public class FriendRequestResponse {

private Long id;
private Long senderId;
private String nickname;
private String profileImageUrl;

}
7 changes: 7 additions & 0 deletions src/main/java/com/potatocake/everymoment/entity/Diary.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.potatocake.everymoment.entity;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
Expand All @@ -9,6 +10,9 @@
import jakarta.persistence.JoinColumn;
import jakarta.persistence.Lob;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.util.HashSet;
import java.util.Set;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
Expand Down Expand Up @@ -53,6 +57,9 @@ public class Diary extends BaseTimeEntity {
@Builder.Default
private boolean isPublic = false;

@OneToMany(mappedBy = "diary", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<DiaryCategory> diaryCategories = new HashSet<>();

public void updateContent(String content) {
if (content != null) {
this.content = content;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,13 @@ public class DiaryCategory {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(name = "fk_category_id"), nullable = false)
private Category category;

public void setDiary(Diary diary) {
this.diary = diary;
}

public void setCategory(Category category) {
this.category = category;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ public void createDiaryManual(Long memberId, DiaryManualCreateRequest diaryManua
Member currentMember = memberRepository.findById(memberId)
.orElseThrow(() -> new GlobalException(ErrorCode.MEMBER_NOT_FOUND));


double longitude = diaryManualCreateRequest.getLocationPoint().getLongitude();
double latitude = diaryManualCreateRequest.getLocationPoint().getLatitude();

Expand Down Expand Up @@ -149,21 +148,21 @@ public MyDiariesResponse getMyDiaries(Long memberId, DiaryFilterRequest diaryFil

Page<Diary> diaryPage;

List<Long> categoryIds = diaryFilterRequest.getCategories();
List<String> categories = diaryFilterRequest.getCategories();
List<String> emojis = diaryFilterRequest.getEmojis();

Specification<Diary> spec = DiarySpecification.filterDiaries(
diaryFilterRequest.getKeyword(),
emojis,
categoryIds,
categories,
diaryFilterRequest.getDate(),
diaryFilterRequest.getFrom(),
diaryFilterRequest.getUntil(),
diaryFilterRequest.getIsBookmark())
.and((root, query, builder) -> builder.equal(root.get("member"), currentMember));

diaryPage = diaryRepository.findAll(spec, PageRequest.of(diaryFilterRequest.getKey(), diaryFilterRequest.getSize()));

diaryPage = diaryRepository.findAll(spec,
PageRequest.of(diaryFilterRequest.getKey(), diaryFilterRequest.getSize()));

List<MyDiarySimpleResponse> diaryDTOs = diaryPage.getContent().stream()
.map(this::convertToMyDiarySimpleResponseDto)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
package com.potatocake.everymoment.service;


import com.potatocake.everymoment.entity.Category;
import com.potatocake.everymoment.entity.Diary;
import com.potatocake.everymoment.entity.DiaryCategory;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.jpa.domain.Specification;

import java.time.LocalDate;

public class DiarySpecification {

public static Specification<Diary> filterDiaries(
String keyword, List<String> emojis, List<Long> categories,
String keyword, List<String> emojis, List<String> categories,
LocalDate date, LocalDate from, LocalDate until, Boolean isBookmark) {
return (Root<Diary> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> {
Predicate predicate = builder.conjunction();
Expand All @@ -29,15 +30,17 @@ public static Specification<Diary> filterDiaries(
}

if (categories != null && !categories.isEmpty()) {
Join<Diary, DiaryCategory> diaryCategoryJoin = root.join("diaryCategories");
predicate = builder.and(predicate, diaryCategoryJoin.get("category").get("id").in(categories));
Join<Diary, DiaryCategory> diaryCategoryJoin = root.join("diaryCategories", JoinType.LEFT);
Join<DiaryCategory, Category> categoryJoin = diaryCategoryJoin.join("category", JoinType.LEFT);
predicate = builder.and(predicate, categoryJoin.get("categoryName").in(categories));
}

LocalDate filterDate = (date != null) ? date : LocalDate.now();
predicate = builder.and(predicate, builder.equal(root.get("createAt").as(LocalDate.class), filterDate));

if (from != null && until != null) {
predicate = builder.and(predicate, builder.between(root.get("createAt"), from.atStartOfDay(), until.plusDays(1).atStartOfDay()));
predicate = builder.and(predicate,
builder.between(root.get("createAt"), from.atStartOfDay(), until.plusDays(1).atStartOfDay()));
}
if (isBookmark != null) {
predicate = builder.and(predicate, builder.equal(root.get("isBookmark"), isBookmark));
Expand Down
21 changes: 6 additions & 15 deletions src/main/java/com/potatocake/everymoment/service/FileService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.potatocake.everymoment.service;

import com.potatocake.everymoment.dto.request.FileRequest;
import com.potatocake.everymoment.dto.response.FileResponse;
import com.potatocake.everymoment.entity.Diary;
import com.potatocake.everymoment.entity.File;
Expand All @@ -11,8 +10,6 @@
import com.potatocake.everymoment.util.S3FileUploader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -34,29 +31,23 @@ public List<FileResponse> getFiles(Long diaryId) {
.toList();
}

public void uploadFiles(Long diaryId, Long memberId, List<MultipartFile> files, List<FileRequest> infos) {
public void uploadFiles(Long diaryId, Long memberId, List<MultipartFile> files) {
Diary diary = diaryRepository.findById(diaryId)
.orElseThrow(() -> new GlobalException(ErrorCode.DIARY_NOT_FOUND));

diary.checkOwner(memberId);

Map<String, MultipartFile> fileMap = files.stream()
.collect(Collectors.toMap(MultipartFile::getOriginalFilename, f -> f, (f1, f2) -> f1));

List<File> fileEntities = new ArrayList<>();

for (FileRequest info : infos) {
MultipartFile file = fileMap.get(info.getFilename());
if (file == null) {
throw new GlobalException(ErrorCode.FILE_NOT_FOUND);
}
for (int i = 0; i < files.size(); i++) {
MultipartFile file = files.get(i);

String url = uploader.uploadFile(file);

File fileEntity = File.builder()
.diary(diary)
.imageUrl(url)
.order(info.getOrder())
.order(i + 1)
.build();

fileEntities.add(fileEntity);
Expand All @@ -65,15 +56,15 @@ public void uploadFiles(Long diaryId, Long memberId, List<MultipartFile> files,
fileRepository.saveAll(fileEntities);
}

public void updateFiles(Long diaryId, Long memberId, List<MultipartFile> files, List<FileRequest> infos) {
public void updateFiles(Long diaryId, Long memberId, List<MultipartFile> files) {
Diary diary = diaryRepository.findById(diaryId)
.orElseThrow(() -> new GlobalException(ErrorCode.DIARY_NOT_FOUND));

diary.checkOwner(memberId);

fileRepository.deleteByDiary(diary);

uploadFiles(diaryId, memberId, files, infos);
uploadFiles(diaryId, memberId, files);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,21 @@ public FriendDiariesResponse getFriendDiaries(Long memberId, DiaryFilterRequest
Page<Diary> diaryPage;

// 카테고리와 이모지가 여러 개 전달될 수 있으므로 이를 리스트로 변환
List<Long> categoryIds = diaryFilterRequest.getCategories();
List<String> categories = diaryFilterRequest.getCategories();
List<String> emojis = diaryFilterRequest.getEmojis();

Specification<Diary> spec = DiarySpecification.filterDiaries(
diaryFilterRequest.getKeyword(),
emojis,
categoryIds,
categories,
diaryFilterRequest.getDate(),
diaryFilterRequest.getFrom(),
diaryFilterRequest.getUntil(),
diaryFilterRequest.getIsBookmark())
.and((root, query, builder) -> root.get("member").in(friendIdList));

diaryPage = diaryRepository.findAll(spec, PageRequest.of(diaryFilterRequest.getKey(), diaryFilterRequest.getSize()));
diaryPage = diaryRepository.findAll(spec,
PageRequest.of(diaryFilterRequest.getKey(), diaryFilterRequest.getSize()));

List<FriendDiarySimpleResponse> friendDiarySimpleResponseList = diaryPage.getContent().stream()
.map(this::convertToFriendDiariesResponseDTO)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.potatocake.everymoment.service;

import static java.util.function.Function.identity;
import static org.springframework.data.domain.Sort.Direction.DESC;

import com.potatocake.everymoment.dto.response.FriendRequestPageRequest;
Expand All @@ -14,6 +15,9 @@
import com.potatocake.everymoment.repository.MemberRepository;
import com.potatocake.everymoment.util.PagingUtil;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.ScrollPosition;
Expand Down Expand Up @@ -106,11 +110,27 @@ private Window<FriendRequest> fetchFriendRequestWindow(Long key, int size, Long
}

private List<FriendRequestResponse> convertToFriendRequestResponses(List<FriendRequest> requests) {
Set<Long> senderIds = requests.stream()
.map(request -> request.getSender().getId())
.collect(Collectors.toSet());

Map<Long, Member> senderMap = memberRepository.findAllById(senderIds)
.stream()
.collect(Collectors.toMap(Member::getId, identity()));

return requests.stream()
.map(request -> FriendRequestResponse.builder()
.id(request.getId())
.senderId(request.getSender().getId())
.build())
.map(request -> {
Member sender = senderMap.get(request.getSender().getId());
if (sender == null) {
throw new GlobalException(ErrorCode.MEMBER_NOT_FOUND);
}
return FriendRequestResponse.builder()
.id(request.getId())
.senderId(sender.getId())
.nickname(sender.getNickname())
.profileImageUrl(sender.getProfileImageUrl())
.build();
})
.toList();
}

Expand Down

0 comments on commit 1f40cfe

Please sign in to comment.