Skip to content

Commit

Permalink
Merge pull request #53 from softeerbootcamp4th/feature/52-fix-eventframe
Browse files Browse the repository at this point in the history
[chore] FE와 주고받는 EventFrame 식별자 PK가 아닌 별도 필드로 수정 (#52)
  • Loading branch information
win-luck authored Aug 13, 2024
2 parents 89dc043 + 04fcaf1 commit 2af9ec5
Show file tree
Hide file tree
Showing 29 changed files with 125 additions and 67 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import hyundai.softeer.orange.core.jwt.JWTManager;
import hyundai.softeer.orange.core.security.PasswordManager;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;
Expand All @@ -16,6 +18,7 @@
@Service
@RequiredArgsConstructor
public class AdminAuthService {
private static final Logger log = LoggerFactory.getLogger(AdminAuthService.class);
private final AdminRepository adminRepository;
private final PasswordManager pwManager;
private final JWTManager jwtManager;
Expand Down Expand Up @@ -56,7 +59,7 @@ public void signUp(String userName, String password, String nickname) {
.password(encryptedPassword)
.nickName(nickname)
.build();

log.info("admin signed up: {}", admin.getUserName());
adminRepository.save(admin);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class CommentController {
@ApiResponse(responseCode = "200", description = "기대평 조회 성공",
content = @Content(schema = @Schema(implementation = ResponseCommentsDto.class)))
})
public ResponseEntity<ResponseCommentsDto> getComments(@PathVariable Long eventFrameId) {
public ResponseEntity<ResponseCommentsDto> getComments(@PathVariable String eventFrameId) {
return ResponseEntity.ok(commentService.getComments(eventFrameId));
}

Expand All @@ -53,7 +53,7 @@ public ResponseEntity<ResponseCommentsDto> getComments(@PathVariable Long eventF
@ApiResponse(responseCode = "409", description = "하루에 여러 번의 기대평을 작성하려 할 때",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
})
public ResponseEntity<Boolean> createComment(@EventUserAnnotation EventUserInfo userInfo, @PathVariable Long eventFrameId, @RequestBody @Valid CreateCommentDto dto) {
public ResponseEntity<Boolean> createComment(@EventUserAnnotation EventUserInfo userInfo, @PathVariable String eventFrameId, @RequestBody @Valid CreateCommentDto dto) {
boolean isPositive = apiService.analyzeComment(dto.getContent());
return ResponseEntity.ok(commentService.createComment(userInfo.getUserId(), eventFrameId, dto, isPositive));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class CommentScheduler {
// 스케줄러에 의해 일정 시간마다 캐싱된 긍정 기대평 목록을 초기화한다.
@Scheduled(fixedRate = ConstantUtil.SCHEDULED_TIME) // 2시간마다 실행
private void clearCache() {
List<Long> eventFrameIds = eventFrameRepository.findAllIds();
eventFrameIds.forEach(commentService::getComments);
List<String> frameIds = eventFrameRepository.findAllFrameIds();
frameIds.forEach(commentService::getComments);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import hyundai.softeer.orange.common.util.ConstantUtil;
import hyundai.softeer.orange.config.NaverApiConfig;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
Expand All @@ -19,6 +21,7 @@
@Service
public class ApiService {

private static final Logger log = LoggerFactory.getLogger(ApiService.class);
private final NaverApiConfig naverApiConfig;

public boolean analyzeComment(String content) {
Expand Down Expand Up @@ -48,6 +51,7 @@ public boolean analyzeComment(String content) {
} catch (JsonProcessingException e) {
throw new CommentException(ErrorCode.INVALID_JSON);
}
log.info("comment <{}> sentiment analysis result: {}", content, isPositive);
return isPositive;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,39 +13,43 @@
import hyundai.softeer.orange.eventuser.entity.EventUser;
import hyundai.softeer.orange.eventuser.repository.EventUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class CommentService {
private static final Logger log = LoggerFactory.getLogger(CommentService.class);
private final CommentRepository commentRepository;
private final EventFrameRepository eventFrameRepository;
private final EventUserRepository eventUserRepository;

// 주기적으로 무작위 추출되는 긍정 기대평 목록을 조회한다.
@Transactional(readOnly = true)
@Cacheable(value = "comments", key = ConstantUtil.COMMENTS_KEY + " + #eventFrameId")
public ResponseCommentsDto getComments(Long eventFrameId) {
List<ResponseCommentDto> comments = commentRepository.findRandomPositiveComments(eventFrameId, ConstantUtil.COMMENTS_SIZE)
public ResponseCommentsDto getComments(String eventFrameId) {
EventFrame frame = eventFrameRepository.findByFrameId(eventFrameId)
.orElseThrow(() -> new CommentException(ErrorCode.EVENT_FRAME_NOT_FOUND));
List<ResponseCommentDto> comments = commentRepository.findRandomPositiveComments(frame.getId(), ConstantUtil.COMMENTS_SIZE)
.stream()
.map(ResponseCommentDto::from)
.toList();
log.info("comments of {} fetched from DB to Redis", eventFrameId);
return new ResponseCommentsDto(comments);
}

// 신규 기대평을 등록한다.
@Transactional
public Boolean createComment(String userId, Long eventFrameId, CreateCommentDto dto, Boolean isPositive) {
public Boolean createComment(String userId, String eventFrameId, CreateCommentDto dto, Boolean isPositive) {
EventUser eventUser = eventUserRepository.findByUserId(userId)
.orElseThrow(() -> new CommentException(ErrorCode.EVENT_USER_NOT_FOUND));
EventFrame eventFrame = eventFrameRepository.findById(eventFrameId)
EventFrame eventFrame = eventFrameRepository.findByFrameId(eventFrameId)
.orElseThrow(() -> new CommentException(ErrorCode.EVENT_FRAME_NOT_FOUND));

// 하루에 여러 번의 기대평을 작성하려 할 때 예외처리
Expand All @@ -56,6 +60,7 @@ public Boolean createComment(String userId, Long eventFrameId, CreateCommentDto
// TODO: 점수정책와 연계하여 기대평 등록 시 점수를 부여 추가해야함
Comment comment = Comment.of(dto.getContent(), eventFrame, eventUser, isPositive);
commentRepository.save(comment);
log.info("created comment: {}", comment.getId());
return true;
}

Expand All @@ -64,6 +69,7 @@ public Boolean createComment(String userId, Long eventFrameId, CreateCommentDto
public Boolean isCommentable(String userId) {
EventUser eventUser = eventUserRepository.findByUserId(userId)
.orElseThrow(() -> new CommentException(ErrorCode.EVENT_USER_NOT_FOUND));
log.info("checking commentable of user {}", eventUser.getUserId());
return !commentRepository.existsByCreatedDateAndEventUser(eventUser.getId());
}

Expand All @@ -75,19 +81,22 @@ public Long deleteComment(Long commentId) {
}

commentRepository.deleteById(commentId);
log.info("deleted comment: {}", commentId);
return commentId;
}

@Transactional
public void deleteComments(List<Long> commentIds) {
commentRepository.deleteAllById(commentIds);
log.info("deleted comments: {}", commentIds);
}

public ResponseCommentsDto searchComments(String eventId, Integer page, Integer size) {
PageRequest pageInfo = PageRequest.of(page, size);

var comments = commentRepository.findAllByEventId(eventId,pageInfo)
.getContent().stream().map(ResponseCommentDto::from).toList();
log.info("searched comments: {}", comments);
return new ResponseCommentsDto(comments);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import hyundai.softeer.orange.event.dto.EventFrameCreateRequest;
import hyundai.softeer.orange.event.dto.EventSearchHintDto;
import hyundai.softeer.orange.event.dto.group.EventEditGroup;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
Expand Down Expand Up @@ -115,7 +114,7 @@ public ResponseEntity<Void> editEvent(
@ApiResponse(responseCode = "4xx", description = "이벤트 프레임 생성 실패")
})
public ResponseEntity<Void> createEventFrame(@Valid @RequestBody EventFrameCreateRequest req) {
eventService.createEventFrame(req.getName());
eventService.createEventFrame(req.getFrameId(), req.getName());
return ResponseEntity.status(HttpStatus.CREATED).build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ public class EventFrame {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

// 클라이언트가 PathVariable로 넘겨줄 값 (ex: the-new-ioniq5)
@Column(unique = true, nullable = false)
private String frameId;

// 어드민에서 노출될 이름 (ex: 2024 하반기 신차 출시 이벤트)
@Column(unique = true, nullable = false)
private String name;

Expand All @@ -31,8 +36,9 @@ public class EventFrame {
@OneToMany(mappedBy="eventFrame")
private List<Comment> commentList = new ArrayList<>();

public static EventFrame of(String name) {
public static EventFrame of(String frame, String name) {
EventFrame eventFrame = new EventFrame();
eventFrame.frameId = frame;
eventFrame.name = name;
return eventFrame;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
public interface EventFrameRepository extends JpaRepository<EventFrame, Long> {
Optional<EventFrame> findByName(String name);

@Query("SELECT ef.id FROM EventFrame ef")
List<Long> findAllIds();
@Query("SELECT ef.frameId FROM EventFrame ef")
List<String> findAllFrameIds();

Optional<EventFrame> findByFrameId(String frameId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
import hyundai.softeer.orange.event.dto.EventDto;
import hyundai.softeer.orange.event.dto.EventSearchHintDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
Expand All @@ -35,10 +36,10 @@
/**
* 이벤트 전반에 대한 조회, 수정을 다루는 서비스. 구체적인 액션(추첨 등)은 구체적인 클래스에서 처리 요망
*/
@Slf4j
@RequiredArgsConstructor
@Service
public class EventService {
private static final Logger log = LoggerFactory.getLogger(EventService.class);
private final EventFrameRepository efRepository;
private final EventMetadataRepository emRepository;
private final EventFieldMapperMatcher mapperMatcher;
Expand Down Expand Up @@ -77,6 +78,7 @@ public void createEvent(EventDto eventDto) {
if(mapper == null) throw new EventException(ErrorCode.INVALID_EVENT_TYPE);

mapper.fetchToEventEntity(eventMetadata, eventDto);
log.info("Created Event: {}", eventKey);
emRepository.save(eventMetadata);
}

Expand All @@ -89,6 +91,7 @@ public void saveTempEvent(Long adminId, EventDto eventDto) {
String key = EventConst.TEMP_KEY(adminId);
// 24시간 동안 유지.
eventDtoRedisTemplate.opsForValue().set(key, eventDto, EventConst.TEMP_EVENT_DURATION_HOUR, TimeUnit.HOURS);
log.info("Saved temp event by {}", adminId);
}

/**
Expand All @@ -100,6 +103,7 @@ public EventDto getTempEvent(Long adminId) {
String key = EventConst.TEMP_KEY(adminId);
String dto = (String) eventDtoRedisTemplate.opsForValue().get(key);

log.info("Fetched temp event by {}", adminId);
return parseUtil.parse(dto, EventDto.class);
}

Expand All @@ -110,6 +114,7 @@ public EventDto getTempEvent(Long adminId) {
public void clearTempEvent(Long adminId) {
String key = EventConst.TEMP_KEY(adminId);
eventDtoRedisTemplate.delete(key);
log.info("Cleared temp event by {}", adminId);
}

/**
Expand All @@ -132,6 +137,7 @@ public void editEvent(EventDto eventDto) {
if(mapper == null) throw new EventException(ErrorCode.INVALID_EVENT_TYPE);

mapper.editEventField(eventMetadata, eventDto);
log.info("Edited event: {}", eventId);
emRepository.save(eventMetadata);
}

Expand Down Expand Up @@ -160,6 +166,7 @@ public EventDto getEventInfo(String eventId) {
.build();

mapper.fetchToDto(metadata, eventDto);
log.info("Fetched Event Info: {}", eventId);
return eventDto;
}

Expand Down Expand Up @@ -206,6 +213,7 @@ public List<BriefEventDto> searchEvents(String search, String sortQuery, Integer
.page(pageInfo)
);

log.info("Searched events for {}", search);
return eventPage.getContent();
}

Expand All @@ -219,6 +227,7 @@ public List<EventSearchHintDto> searchHints(String search) {
var isDrawEvent = EventSpecification.isEventTypeOf(EventType.draw);
// 내부적으로는 모든 데이터를 fetch하는 문제가 여전히 존재.

log.info("searching hints for {}", search);
return emRepository.findBy(
searchOnEventIdDefaultReject.and(isDrawEvent),
(q) -> q.as(EventSearchHintDto.class).all()
Expand All @@ -230,9 +239,10 @@ public List<EventSearchHintDto> searchHints(String search) {
* @param name 이벤트 프레임의 이름
*/
@Transactional
public void createEventFrame(String name) {
EventFrame eventFrame = EventFrame.of(name);
public void createEventFrame(String frameId, String name) {
EventFrame eventFrame = EventFrame.of(frameId, name);
efRepository.save(eventFrame);
log.info("Created Event Frame: {}", name);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import hyundai.softeer.orange.event.draw.component.picker.WinnerPicker;
import hyundai.softeer.orange.event.draw.repository.DrawEventWinningInfoRepository;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -26,6 +28,7 @@
@RequiredArgsConstructor
@Service
public class DrawEventService {
private static final Logger log = LoggerFactory.getLogger(DrawEventService.class);
private final DrawEventRepository deRepository;
private final DrawEventWinningInfoRepository deWinningInfoRepository;
private final WinnerPicker picker;
Expand Down Expand Up @@ -91,6 +94,7 @@ public void draw(Long drawEventId) {
remain--;
}

log.info("Draw Event: {}, Winners: {}", drawEventRawId, insertTargets.size());
deWinningInfoRepository.insertMany(insertTargets);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

@Getter
public class EventFrameCreateRequest {
@NotBlank
private String frameId;
@NotBlank
private String name;
}
Loading

0 comments on commit 2af9ec5

Please sign in to comment.