Skip to content

Commit

Permalink
Merge pull request #131 from softeerbootcamp4th/feat/#128-get-rush-wi…
Browse files Browse the repository at this point in the history
…nner

Feat/#128 get rush winner
  • Loading branch information
wjddn2165 authored Aug 14, 2024
2 parents 7839918 + 84a4aa7 commit faa6bd8
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.http.HttpStatusCode;

import java.util.List;

Expand All @@ -41,12 +40,10 @@ public ResponseEntity<ResponseDto> postAdmin(@RequestBody @Valid AdminRequestDto

// 이미지 업로드
@PostMapping("/image")
public ResponseEntity<ImageUrlResponseDto> postImage(
@RequestPart(value = "image") MultipartFile image){
public ResponseEntity<ImageUrlResponseDto> postImage(@RequestPart(value = "image") MultipartFile image) {
return ResponseEntity
.status(HttpStatus.CREATED)
.body(adminService.postImage(image));

}

// 추첨 이벤트 조회
Expand Down Expand Up @@ -110,18 +107,31 @@ public ResponseEntity<RushEventParticipantsListResponseDto> getRushEventParticip
.body(adminService.getRushEventParticipants(rushEventId, size, page, option, phoneNumber));
}

// 선착순 이벤트 당첨자 조회
@GetMapping("/event/rush/{rushEventId}/winner")
public ResponseEntity<RushEventParticipantsListResponseDto> getRushEventWinners(
@PathVariable("rushEventId") Long rushEventId,
@RequestParam(name = "size", required = false, defaultValue = "10") int size,
@RequestParam(name = "page", required = false, defaultValue = "0") int page,
@RequestParam(name = "number", required = false, defaultValue = "") String phoneNumber) {
return ResponseEntity
.status(HttpStatus.OK)
.body(adminService.getRushEventWinners(rushEventId, size, page, phoneNumber));
}

// 선착순 이벤트 수정
@PutMapping("/event/rush")
public ResponseEntity<List<AdminRushEventResponseDto>> updateRushEvent(
@RequestBody List<RushEventRequestDto> rushEventListRequestDto) {

return ResponseEntity
.status(HttpStatus.OK)
.body(adminService.updateRushEvents(rushEventListRequestDto));
}

// 선착순 이벤트 삭제
@DeleteMapping("/event/rush/{rushEventId}")
public ResponseEntity<ResponseDto> deleteRushEvent(@PathVariable Long rushEventId){
public ResponseEntity<ResponseDto> deleteRushEvent(@PathVariable Long rushEventId) {
return ResponseEntity
.status(HttpStatus.OK)
.body(adminService.deleteRushEvent(rushEventId));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.ToString;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

@Entity
@Getter
@ToString
public class RushEvent extends BaseEvent {
private String prizeImageUrl;
private String prizeDescription;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
@Repository
public interface RushParticipantsRepository extends JpaRepository<RushParticipants, Long> {
boolean existsByRushEvent_RushEventIdAndBaseUser_Id(Long eventId, String userId);

long countByRushEvent_RushEventIdAndOptionId(Long eventId, int optionId);

@Query("SELECT COUNT(rp) + 1 FROM RushParticipants rp " +
"WHERE rp.rushEvent.rushEventId = :eventId " +
"AND rp.optionId = :optionId " +
Expand All @@ -23,7 +25,9 @@ public interface RushParticipantsRepository extends JpaRepository<RushParticipan
long findUserRankByEventIdAndUserIdAndOptionId(@Param("eventId") Long eventId,
@Param("userId") String userId,
@Param("optionId") int optionId);

long countAllByOptionId(int optionId);

@Query("SELECT rp.optionId FROM RushParticipants rp WHERE rp.baseUser.id = :userId")
Optional<Integer> getOptionIdByUserId(@Param("userId") String userId);

Expand All @@ -35,4 +39,32 @@ long findUserRankByEventIdAndUserIdAndOptionId(@Param("eventId") Long eventId,

Page<RushParticipants> findByRushEvent_RushEventIdAndOptionIdAndBaseUser_Id(Long rushEventId, int optionId, String baseUser_id, Pageable pageable);


@Query("SELECT rp FROM RushParticipants rp " +
"WHERE rp.rushEvent.rushEventId = :eventId " +
"AND rp.optionId = :optionId " +
"ORDER BY rp.id ASC ")
Page<RushParticipants> findWinnerByEventIdAndOptionId(
@Param("eventId") Long eventId, @Param("optionId") int optionId, Pageable pageable);

@Query("SELECT rp FROM RushParticipants rp " +
"WHERE rp.rushEvent.rushEventId = :eventId " +
"AND rp.optionId = :optionId " +
"AND rp.baseUser.id = :phoneNumber " +
"ORDER BY rp.id ASC ")
Page<RushParticipants> findWinnerByEventIdAndOptionIdAndPhoneNumber(
@Param("eventId") Long eventId, @Param("optionId") int optionId, @Param("phoneNumber") String phoneNumber, Pageable pageable
);

@Query("SELECT rp FROM RushParticipants rp " +
"WHERE rp.rushEvent.rushEventId = :eventId " +
"ORDER BY rp.id ASC ")
Page<RushParticipants> findWinnerByEventId(@Param("eventId") Long eventId, @Param("winnerCount") Pageable pageable);


@Query("SELECT rp FROM RushParticipants rp " +
"WHERE rp.rushEvent.rushEventId = :eventId " +
"AND rp.baseUser.id = :phoneNumber " +
"ORDER BY rp.id ASC ")
Page<RushParticipants> findByWinnerByEventIdAndPhoneNumber(@Param("eventId") Long eventId, @Param("phoneNumber") String phoneNumber, Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import JGS.CasperEvent.global.service.S3Service;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
Expand All @@ -43,6 +44,8 @@
import java.time.LocalDateTime;
import java.util.*;

import static JGS.CasperEvent.global.util.RepositoryErrorHandler.findByIdOrElseThrow;

@RequiredArgsConstructor
@Service
public class AdminService {
Expand Down Expand Up @@ -100,7 +103,7 @@ public LotteryEventParticipantsListResponseDto getLotteryEventParticipants(int s

Page<LotteryParticipants> lotteryParticipantsPage = null;
if (phoneNumber.isEmpty()) lotteryParticipantsPage = lotteryParticipantsRepository.findAll(pageable);
else lotteryParticipantsRepository.findByBaseUser_Id(phoneNumber, pageable);
else lotteryParticipantsPage = lotteryParticipantsRepository.findByBaseUser_Id(phoneNumber, pageable);

List<LotteryEventParticipantsResponseDto> lotteryEventParticipantsResponseDtoList = new ArrayList<>();

Expand Down Expand Up @@ -200,9 +203,59 @@ public RushEventParticipantsListResponseDto getRushEventParticipants(long rushEv
}

Boolean isLastPage = !rushParticipantsPage.hasNext();
// todo 전체 참여자 아닌 옵션별 참여자로 수정하기
return new RushEventParticipantsListResponseDto(rushEventParticipantResponseDtoList, isLastPage, rushParticipantsRepository.count());
}

public RushEventParticipantsListResponseDto getRushEventWinners(long rushEventId, int size, int page, String phoneNumber) {
Page<RushParticipants> rushParticipantsPage = null;

RushEvent rushEvent = findByIdOrElseThrow(rushEventRepository, rushEventId, CustomErrorCode.NO_RUSH_EVENT);
int winnerCount = rushEvent.getWinnerCount();
Pageable winnerPage = PageRequest.of(0, winnerCount);

long leftSelect = rushParticipantsRepository.countByRushEvent_RushEventIdAndOptionId(rushEventId, 1);
long rightSelect = rushParticipantsRepository.countByRushEvent_RushEventIdAndOptionId(rushEventId, 2);

boolean isPhoneNumberEmpty = phoneNumber.isEmpty();

int winnerOptionId;
if (leftSelect > rightSelect) winnerOptionId = 1;
else if (leftSelect < rightSelect) winnerOptionId = 2;
else winnerOptionId = 0;

if (!isPhoneNumberEmpty && winnerOptionId != 0) {
// 전화번호와 유효한 옵션 ID가 있는 경우
rushParticipantsPage = rushParticipantsRepository.findWinnerByEventIdAndOptionIdAndPhoneNumber(rushEventId, winnerOptionId, phoneNumber, winnerPage);
} else if (isPhoneNumberEmpty && winnerOptionId == 0) {
// 전화번호가 비어있고 두 선택지가 동점인 경우
rushParticipantsPage = rushParticipantsRepository.findWinnerByEventId(rushEventId, winnerPage);
} else if (winnerOptionId != 0) {
// 유효한 옵션 ID가 있지만 전화번호는 비어있는 경우
rushParticipantsPage = rushParticipantsRepository.findWinnerByEventIdAndOptionId(rushEventId, winnerOptionId, winnerPage);
} else {
// 두 선택지가 동점이고 전화번호가 주어진 경우
rushParticipantsPage = rushParticipantsRepository.findByWinnerByEventIdAndPhoneNumber(rushEventId, phoneNumber, winnerPage);
}

List<RushParticipants> rushParticipantsList = rushParticipantsPage.getContent();
rushParticipantsPage = paginateList(rushParticipantsList, page, size);

List<RushEventParticipantResponseDto> rushEventParticipantResponseDtoList = new ArrayList<>();
for (RushParticipants rushParticipant : rushParticipantsPage) {
String userId = rushParticipant.getBaseUser().getId();
int userChoice = rushParticipant.getOptionId();
long rank = rushParticipantsRepository.findUserRankByEventIdAndUserIdAndOptionId(rushEventId, userId, userChoice);
rushEventParticipantResponseDtoList.add(
RushEventParticipantResponseDto.of(rushParticipant, rank)
);
}

Boolean isLastPage = !rushParticipantsPage.hasNext();
long totalParticipants = rushParticipantsList.size();
return new RushEventParticipantsListResponseDto(rushEventParticipantResponseDtoList, isLastPage, totalParticipants);
}

@Transactional
public void deleteLotteryEvent() {
LotteryEvent currentLotteryEvent = getCurrentLotteryEvent();
Expand Down Expand Up @@ -347,4 +400,13 @@ public void deleteLotteryEventExpectation(Long casperId) {

casperBot.deleteExpectation();
}

public static <T> Page<T> paginateList(List<T> list, int page, int size) {
int start = Math.min(page * size, list.size());
int end = Math.min(start + size, list.size());

List<T> paginatedList = list.subList(start, end);

return new PageImpl<>(paginatedList, PageRequest.of(page, size), list.size());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public void setTodayEventToRedis() {
RushEvent rushEvent = new RushEvent(
startDateTime.plusDays(i), // 이벤트 시작 날짜
endDateTime.plusDays(i), // 이벤트 종료 날짜
0, // 우승자 수 (winnerCount)
315, // 우승자 수 (winnerCount)
"http://example.com/prize" + (i + 1) + ".jpg", // 상 이미지 URL
"Prize Description " + (i + 1) // 상 설명
);
Expand Down

0 comments on commit faa6bd8

Please sign in to comment.