Skip to content

Commit

Permalink
Merge pull request #37 from Team-UniVoice/feat/#36-fix-like-save-erro…
Browse files Browse the repository at this point in the history
…erFormat

Feat/#36 fix like save erroer format
  • Loading branch information
softmoca authored Jul 14, 2024
2 parents b6a375c + 9880c69 commit 8f6a5c8
Show file tree
Hide file tree
Showing 14 changed files with 83 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

public record UserLoginResponse(
String accessToken

) {

public static UserLoginResponse of(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@ private void setResponse(HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.getWriter()
.write(objectMapper.writeValueAsString(
ErrorResponse.of(ErrorMessage.JWT_UNAUTHORIZED_EXCEPTION.getStatus(),
ErrorMessage.JWT_UNAUTHORIZED_EXCEPTION.getMessage())));
response.getWriter().write(objectMapper.writeValueAsString(
ErrorResponse.of(
ErrorMessage.JWT_UNAUTHORIZED_EXCEPTION.getStatus(),
ErrorMessage.JWT_UNAUTHORIZED_EXCEPTION.getMessage(),
null // 추가된 필드
)
));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,10 @@ public UserLoginResponse logineMember(
MemberSignInRequest memberSignInRequest
) {
Member member = authRepository.findByEmail(memberSignInRequest.getEmail())
.orElseThrow(() -> new UnauthorizedException(ErrorMessage.JWT_UNAUTHORIZED_EXCEPTION));
.orElseThrow(() -> new UnauthorizedException(ErrorMessage.JWT_LOGIN_PASSWORD_EXCEPTION));

if (!passwordEncoder.matches(memberSignInRequest.getPassword(), member.getPassword())) {
throw new UnauthorizedException(ErrorMessage.JWT_LOGIN_EXCEPTION);
throw new UnauthorizedException(ErrorMessage.JWT_LOGIN_PASSWORD_EXCEPTION);
}

Long memberId = member.getId();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public ResponseEntity<SuccessStatusResponse<Object>> getDepartmentNoticeByUserUn

@PostMapping("/quick")
public ResponseEntity<SuccessStatusResponse<List<QuickQueryNoticeDTO>>> getQuickNoticeByUserUniversity(@RequestBody AffiliationRequestDTO request) {
System.out.println("Received Affiliation Request: " + request.getAffiliation());

List<QuickQueryNoticeDTO> response = noticeService.getQuickNoticeByUserUniversity(request.getAffiliation());
return ResponseEntity.status(HttpStatus.OK)
.body(SuccessStatusResponse.of(SuccessMessage.GET_QUICK_NOTICE_SUCCESS, response));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,8 @@ public class NoticeDetailResponseDTO {
private List<String> noticeImages;
private LocalDateTime createdAt; // 추가된 부분
private LocalDateTime updatedAt; // 추가된 부분
private Boolean likeCheck;
private Boolean saveCheck;
private String dayOfWeek;

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class QuickQueryNoticeDTO {
private LocalDateTime endTime;
private String title;
private Long likeCount;
private Long saveCount;
private Long viewCount;
private String category;
private LocalDateTime createdAt; // 추가된 부분
private LocalDateTime updatedAt; // 추가된 부분
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/sopt/univoice/domain/notice/entity/Notice.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public class Notice extends BaseTimeEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;


private String title;

@Column(length = 1000)
Expand All @@ -40,7 +39,6 @@ public class Notice extends BaseTimeEntity {
@Column(length = 1000)
private String contentSummary;


@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
import java.util.Optional;

public interface NoticeLikeRepository extends JpaRepository<NoticeLike, Long> {
boolean existsByMemberIdAndNoticeId(Long memberId, Long noticeId);
Optional<NoticeLike> findByNoticeAndMember(Notice notice, Member member);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import java.util.Optional;

public interface SaveNoticeRepository extends JpaRepository<SaveNotice, Long>{
boolean existsByMemberIdAndNoticeId(Long memberId, Long noticeId);

Optional<SaveNotice> findByNoticeAndMember(Notice notice, Member member);
List<SaveNotice> findByMember(Member member);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import java.util.stream.Collectors;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.DayOfWeek;
import java.time.format.TextStyle;
import java.util.Locale;

@Service
@RequiredArgsConstructor
Expand All @@ -51,13 +54,18 @@ public void createPost(NoticeCreateRequest noticeCreateRequest) {
.orElseThrow(() -> new RuntimeException("회원이 존재하지 않습니다."));
System.out.println("Member Role: " + member.getAffiliation().getRole());

String content = noticeCreateRequest.getContent();
String summarizedContent = null;
try {
summarizedContent = openAiService.summarizeText(noticeCreateRequest.getContent());
System.out.println("Summarized Content: " + summarizedContent);
} catch (IOException e) {
System.err.println("Error summarizing content: " + e.getMessage());
e.printStackTrace();
if (content.length() <= 150) {
summarizedContent = "150자 이내인 내용 입니다\n" + content;
} else {
try {
summarizedContent = openAiService.summarizeText(content);
System.out.println("Summarized Content: " + summarizedContent);
} catch (IOException e) {
System.err.println("Error summarizing content: " + e.getMessage());
e.printStackTrace();
}
}

// 사용자 권한 확인
Expand Down Expand Up @@ -275,7 +283,7 @@ public List<QuickQueryNoticeDTO> getQuickNoticeByUserUniversity(String affiliati
notice.getCreatedAt(),
notice.getUpdatedAt()
))
.sorted(Comparator.comparing(QuickQueryNoticeDTO::getCreatedAt)) // 오름차순 정렬
.sorted(Comparator.comparing(QuickQueryNoticeDTO::getCreatedAt).reversed()) //내림차순
.collect(Collectors.toList());
}

Expand Down Expand Up @@ -411,7 +419,6 @@ public List<NoticeDTO> getAllNoticeByUserUniversity() {
noticeDTOs.add(noticeDTO);
}

// Sort the list based on createdAt in descending order
noticeDTOs.sort(Comparator.comparing(NoticeDTO::getCreatedAt));

return noticeDTOs;
Expand Down Expand Up @@ -513,6 +520,8 @@ public List<NoticeResponseDTO> getDepartmentNoticeByUserUniversity() {

@Transactional(readOnly = true)
public NoticeDetailResponseDTO getNoticeById(Long noticeId) {
Long memberId = principalHandler.getUserIdFromPrincipal();

Notice notice = noticeRepository.findById(noticeId)
.orElseThrow(() -> new RuntimeException("공지사항이 존재하지 않습니다."));

Expand All @@ -525,6 +534,16 @@ public NoticeDetailResponseDTO getNoticeById(Long noticeId) {
// Affiliation의 affiliation 값을 가져옵니다.
String writeAffiliation = affiliation.getAffiliation();

// likeCheck 로직 추가
boolean likeCheck = noticeLikeRepository.existsByMemberIdAndNoticeId(memberId, noticeId);

// saveCheck 로직 추가
boolean saveCheck = saveNoticeRepository.existsByMemberIdAndNoticeId(memberId, noticeId);

// 요일 계산
DayOfWeek dayOfWeekEnum = notice.getCreatedAt().getDayOfWeek();
String dayOfWeek = convertDayOfWeekToKorean(dayOfWeekEnum);

return new NoticeDetailResponseDTO(
notice.getId(),
notice.getTitle(),
Expand All @@ -540,8 +559,32 @@ public NoticeDetailResponseDTO getNoticeById(Long noticeId) {
writeAffiliation, // 추가된 부분
notice.getNoticeImages().stream().map(NoticeImage::getNoticeImage).collect(Collectors.toList()),
notice.getCreatedAt(),
notice.getUpdatedAt()
notice.getUpdatedAt(),
likeCheck,
saveCheck, // saveCheck 로직 추가
dayOfWeek // dayOfWeek 추가
);
}

private String convertDayOfWeekToKorean(DayOfWeek dayOfWeek) {
switch (dayOfWeek) {
case MONDAY:
return "월";
case TUESDAY:
return "화";
case WEDNESDAY:
return "수";
case THURSDAY:
return "목";
case FRIDAY:
return "금";
case SATURDAY:
return "토";
case SUNDAY:
return "일";
default:
return "";
}
}

}
11 changes: 6 additions & 5 deletions src/main/java/sopt/univoice/infra/common/dto/ErrorResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

public record ErrorResponse(
int status,
String message
String message,
Object data // 추가된 필드
) {
public static ErrorResponse of(int status, String message) {
return new ErrorResponse(status, message);
public static ErrorResponse of(int status, String message, Object data) {
return new ErrorResponse(status, message, data);
}
public static ErrorResponse of(ErrorMessage errorMessage) {
return new ErrorResponse(errorMessage.getStatus(), errorMessage.getMessage());
return new ErrorResponse(errorMessage.getStatus(), errorMessage.getMessage(), null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public enum SuccessMessage {
EMAIL_AVAILABLE(HttpStatus.OK.value(),"사용가능한 아이디입니다."),
SIGNUP_SUCCESS(HttpStatus.CREATED.value(),"회원가입에 성공하였습니다."),
SIGNIN_SUCCESS(HttpStatus.OK.value(),"로그인에 성공하였습니다."),

JWT_LOGIN_SUCCESS(HttpStatus.UNAUTHORIZED.value(), "가입된 계정이 없습니다 아이디와 비밀번호를 다시 확인해주세요."),
CREATE_NOTICE_SUCCESS(HttpStatus.CREATED.value(),"공지작성에 성공하였습니다."),
LIKE_NOTICE_SUCCESS(HttpStatus.CREATED.value(),"공지 좋아요에 성공하였습니다."),
LIKE_CANCLE_NOTICE_SUCCESS(HttpStatus.CREATED.value(),"공지 좋아요 취소에 성공하였습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,18 @@ public class GlobalExceptionHandler {

@ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<ErrorResponse> handleEntityNotFoundException(EntityNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ErrorResponse.of(HttpStatus.NOT_FOUND.value(), e.getMessage()));
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ErrorResponse.of(HttpStatus.NOT_FOUND.value(), e.getMessage(), null));
}

@ExceptionHandler(BusinessException.class)
protected ResponseEntity<ErrorResponse> handleBusinessException(BusinessException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(ErrorResponse.of(e.getErrorMessage()));
return ResponseEntity.status(HttpStatus.CONFLICT).body(ErrorResponse.of(e.getErrorMessage().getStatus(), e.getErrorMessage().getMessage(), null));
}



@ExceptionHandler(UnauthorizedException.class)
protected ResponseEntity<ErrorResponse> handlerUnauthorizedException(UnauthorizedException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(ErrorResponse.of(e.getErrorMessage().getStatus(), e.getErrorMessage().getMessage()));
.body(ErrorResponse.of(e.getErrorMessage().getStatus(), e.getErrorMessage().getMessage(), null));
}


}

Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
@Getter
public enum ErrorMessage {
EMAIL_DUPLICATE(HttpStatus.CONFLICT.value(), "이미 사용중인 아이디 입니다."),
JWT_LOGIN_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "가입된 계정이 없습니다 아이디와 비밀번호를 다시 확인해주세요."),
JWT_LOGIN_PASSWORD_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "가입된 계정이 없습니다 아이디와 비밀번호를 다시 확인해주세요."),
JWT_UNAUTHORIZED_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "사용자의 로그인 검증을 실패했습니다."),
APPROVEADMIN_UNAUTHORIZED_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "승인된 관리자의 로그인 검증을 실패했습니다."),
;
Expand Down

0 comments on commit 8f6a5c8

Please sign in to comment.