Skip to content

Commit

Permalink
Merge pull request #218 from softeerbootcamp4th/feature/#203-rush-eve…
Browse files Browse the repository at this point in the history
…nt-apply-stress-test

Feature/#203 rush event apply stress test
  • Loading branch information
k000927 authored Aug 22, 2024
2 parents 8e621fe + c1d2eda commit 883932a
Show file tree
Hide file tree
Showing 19 changed files with 54 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public ResponseEntity<Boolean> checkUserParticipationInRushEvent(HttpServletRequ
BaseUser user = (BaseUser) httpServletRequest.getAttribute("user");
return ResponseEntity
.status(HttpStatus.OK)
.body(rushEventService.isExists(user.getId()));
.body(rushEventService.isExists(user.getPhoneNumber()));
}

@Operation(summary = "선착순 이벤트 응모", description = "해당 유저가 오늘의 이벤트에 응모합니다. optionId 값이 필요합니다. optionId 값이 1이면 왼쪽 선택지, 2이면 오른쪽 선택지에 응모합니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public record LotteryEventParticipantsResponseDto(
public static LotteryEventParticipantsResponseDto of(LotteryParticipants participant) {
return new LotteryEventParticipantsResponseDto(
participant.getId(),
participant.getBaseUser().getId(),
participant.getBaseUser().getPhoneNumber(),
participant.getLinkClickedCount(),
participant.getExpectations(),
participant.getAppliedCount(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public record RushEventParticipantResponseDto(Long id, String phoneNumber,
public static RushEventParticipantResponseDto of(RushParticipants rushParticipants, Long rank){
return new RushEventParticipantResponseDto(
rushParticipants.getId(),
rushParticipants.getBaseUser().getId(),
rushParticipants.getBaseUser().getPhoneNumber(),
rushParticipants.getOptionId(),
rushParticipants.getCreatedAt().toLocalDate(),
rushParticipants.getCreatedAt().toLocalTime(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ public class RushEvent extends BaseEvent {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long rushEventId;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "rushEvent", cascade = CascadeType.ALL, orphanRemoval = true)
@OneToMany(mappedBy = "rushEvent", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private final Set<RushOption> options = new HashSet<>();

@OneToMany(fetch = FetchType.EAGER, mappedBy = "rushEvent", cascade = CascadeType.ALL, orphanRemoval = true)
@OneToMany(mappedBy = "rushEvent", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<RushParticipants> rushParticipants;

public RushEvent() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class LotteryParticipants extends BaseEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToOne(fetch = FetchType.LAZY) // mappedBy 이용하면 둘 다 저장 안해도 됨
@ManyToOne(fetch = FetchType.LAZY) // mappedBy 이용하면 둘 다 저장 안해도 됨
@JoinColumn(name = "base_user_id")
@JsonBackReference
@JsonIgnore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class LotteryWinners {

public LotteryWinners(LotteryParticipants lotteryParticipants) {
this.id = lotteryParticipants.getId();
this.phoneNumber = lotteryParticipants.getBaseUser().getId();
this.phoneNumber = lotteryParticipants.getBaseUser().getPhoneNumber();
this.linkClickedCount = lotteryParticipants.getLinkClickedCount();
this.expectation = lotteryParticipants.getExpectations();
this.appliedCount = lotteryParticipants.getAppliedCount();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ public class RushParticipants extends BaseEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int optionId;
@OneToOne

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "base_user_id")
@JsonBackReference
private BaseUser baseUser;

@ManyToOne
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "rush_event_id")
private RushEvent rushEvent;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@

@Repository
public interface AdminRepository extends JpaRepository<Admin, String> {
Optional<Admin> findByIdAndPassword(String id, String password);
Optional<Admin> findByPhoneNumberAndPassword(String id, String password);
Optional<Admin> findByPhoneNumber(String id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
public interface LotteryParticipantsRepository extends JpaRepository<LotteryParticipants, Long> {
Optional<LotteryParticipants> findByBaseUser(BaseUser baseUser);

@Query("SELECT p FROM LotteryParticipants p WHERE p.baseUser.id LIKE :id%")
@Query("SELECT p FROM LotteryParticipants p WHERE p.baseUser.phoneNumber LIKE :id%")
Page<LotteryParticipants> findByBaseUser_Id(@Param("id") String id, Pageable pageable);

@Query("SELECT COUNT(p) FROM LotteryParticipants p WHERE p.baseUser.id LIKE :id%")
@Query("SELECT COUNT(p) FROM LotteryParticipants p WHERE p.baseUser.phoneNumber LIKE :id%")
long countByBaseUser_Id(@Param("id") String id);

@Query("SELECT lp.id, lp.appliedCount From LotteryParticipants lp")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

@Repository
public interface RushParticipantsRepository extends JpaRepository<RushParticipants, Long> {
boolean existsByRushEvent_RushEventIdAndBaseUser_Id(Long eventId, String userId);
boolean existsByRushEvent_RushEventIdAndBaseUser_PhoneNumber(Long eventId, String userId);

long countByRushEvent_RushEventIdAndOptionId(Long eventId, int optionId);

Expand Down Expand Up @@ -41,12 +41,12 @@ long findUserRankByEventIdAndUserId(@Param("eventId") Long eventId,

Page<RushParticipants> findByRushEvent_RushEventId(Long rushEventId, Pageable pageable);

@Query("SELECT p FROM RushParticipants p WHERE p.rushEvent.rushEventId = :rushEventId AND p.baseUser.id LIKE :baseUserId%")
@Query("SELECT p FROM RushParticipants p WHERE p.rushEvent.rushEventId = :rushEventId AND p.baseUser.phoneNumber LIKE :baseUserId%")
Page<RushParticipants> findByRushEvent_RushEventIdAndBaseUser_Id(@Param("rushEventId") Long rushEventId, @Param("baseUserId") String baseUserId, Pageable pageable);

Page<RushParticipants> findByRushEvent_RushEventIdAndOptionId(Long rushEventId, int optionId, Pageable pageable);

@Query("SELECT p FROM RushParticipants p WHERE p.rushEvent.rushEventId = :rushEventId AND p.optionId = :optionId AND p.baseUser.id LIKE :baseUserId%")
@Query("SELECT p FROM RushParticipants p WHERE p.rushEvent.rushEventId = :rushEventId AND p.optionId = :optionId AND p.baseUser.phoneNumber LIKE :baseUserId%")
Page<RushParticipants> findByRushEvent_RushEventIdAndOptionIdAndBaseUser_Id(@Param("rushEventId") Long rushEventId, @Param("optionId") int optionId, @Param("baseUserId") String baseUserId, Pageable pageable);


Expand All @@ -60,7 +60,7 @@ Page<RushParticipants> findWinnerByEventIdAndOptionId(
@Query("SELECT rp FROM RushParticipants rp " +
"WHERE rp.rushEvent.rushEventId = :eventId " +
"AND rp.optionId = :optionId " +
"AND rp.baseUser.id LIKE :phoneNumber% " +
"AND rp.baseUser.phoneNumber LIKE :phoneNumber% " +
"ORDER BY rp.id ASC ")
Page<RushParticipants> findWinnerByEventIdAndOptionIdAndPhoneNumber(
@Param("eventId") Long eventId, @Param("optionId") int optionId, @Param("phoneNumber") String phoneNumber, Pageable pageable
Expand All @@ -74,15 +74,15 @@ Page<RushParticipants> findWinnerByEventIdAndOptionIdAndPhoneNumber(

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

@Query("SELECT COUNT(p) FROM RushParticipants p WHERE p.rushEvent.rushEventId = :rushEventId AND p.optionId = :optionId AND p.baseUser.id LIKE :baseUserId%")
@Query("SELECT COUNT(p) FROM RushParticipants p WHERE p.rushEvent.rushEventId = :rushEventId AND p.optionId = :optionId AND p.baseUser.phoneNumber LIKE :baseUserId%")
long countByRushEvent_RushEventIdAndOptionIdAndBaseUser_Id(@Param("rushEventId") Long rushEventId, @Param("optionId") int optionId, @Param("baseUserId") String baseUserId);

long countByRushEvent_RushEventId(long rushEventId);

@Query("SELECT COUNT(p) FROM RushParticipants p WHERE p.rushEvent.rushEventId = :rushEventId AND p.baseUser.id LIKE :baseUserId%")
@Query("SELECT COUNT(p) FROM RushParticipants p WHERE p.rushEvent.rushEventId = :rushEventId AND p.baseUser.phoneNumber LIKE :baseUserId%")
long countByRushEvent_RushEventIdAndBaseUser_Id(@Param("rushEventId") Long rushEventId, @Param("baseUserId") String baseUserId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,15 @@ public class AdminService {

// 어드민 인증
public Admin verifyAdmin(AdminRequestDto adminRequestDto) {
return adminRepository.findByIdAndPassword(adminRequestDto.getAdminId(), adminRequestDto.getPassword()).orElseThrow(NoSuchElementException::new);
return adminRepository.findByPhoneNumberAndPassword(adminRequestDto.getAdminId(), adminRequestDto.getPassword()).orElseThrow(NoSuchElementException::new);
}

// 어드민 생성
public ResponseDto postAdmin(AdminRequestDto adminRequestDto) {
String adminId = adminRequestDto.getAdminId();
String password = adminRequestDto.getPassword();

Admin admin = adminRepository.findById(adminId).orElse(null);
Admin admin = adminRepository.findByPhoneNumber(adminId).orElse(null);

if (admin != null) throw new CustomException("이미 등록된 ID입니다.", CustomErrorCode.CONFLICT);
adminRepository.save(new Admin(adminId, password, Role.ADMIN));
Expand Down Expand Up @@ -213,7 +213,7 @@ public RushEventParticipantsListResponseDto getRushEventParticipants(long rushEv

List<RushEventParticipantResponseDto> rushEventParticipantResponseDtoList = new ArrayList<>();
for (RushParticipants rushParticipant : rushParticipantsPage) {
String userId = rushParticipant.getBaseUser().getId();
String userId = rushParticipant.getBaseUser().getPhoneNumber();
int userChoice = rushParticipant.getOptionId();
long rank = rushParticipantsRepository.findUserRankByEventIdAndUserIdAndOptionId(rushEventId, userId, userChoice);
rushEventParticipantResponseDtoList.add(
Expand Down Expand Up @@ -263,7 +263,7 @@ public RushEventParticipantsListResponseDto getRushEventWinners(long rushEventId

List<RushEventParticipantResponseDto> rushEventParticipantResponseDtoList = new ArrayList<>();
for (RushParticipants rushParticipant : rushParticipantsPage) {
String userId = rushParticipant.getBaseUser().getId();
String userId = rushParticipant.getBaseUser().getPhoneNumber();
int userChoice = rushParticipant.getOptionId();
long rank = rushParticipantsRepository.findUserRankByEventIdAndUserIdAndOptionId(rushEventId, userId, userChoice);
rushEventParticipantResponseDtoList.add(
Expand Down Expand Up @@ -531,7 +531,7 @@ public LotteryEventExpectationsResponseDto getLotteryEventExpectations(int page,


Pageable pageable = PageRequest.of(page, size);
Page<CasperBot> casperBotPage = casperBotRepository.findByPhoneNumberAndActiveExpectations(lotteryParticipant.getBaseUser().getId(), pageable);
Page<CasperBot> casperBotPage = casperBotRepository.findByPhoneNumberAndActiveExpectations(lotteryParticipant.getBaseUser().getPhoneNumber(), pageable);

// DTO로 변환합니다.
List<LotteryEventExpectationResponseDto> lotteryEventExpectationResponseDtoList = casperBotPage.getContent().stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import JGS.CasperEvent.domain.event.entity.event.LotteryEvent;
import JGS.CasperEvent.domain.event.entity.participants.LotteryParticipants;
import JGS.CasperEvent.domain.event.repository.CasperBotRepository;
import JGS.CasperEvent.domain.event.repository.eventRepository.LotteryEventRepository;
import JGS.CasperEvent.domain.event.repository.participantsRepository.LotteryParticipantsRepository;
import JGS.CasperEvent.domain.event.service.redisService.RedisService;
import JGS.CasperEvent.global.entity.BaseUser;
Expand Down Expand Up @@ -47,7 +46,7 @@ public CasperBotResponseDto postCasperBot(BaseUser user, CasperBotRequestDto cas

LotteryEvent lotteryEvent = eventCacheService.getLotteryEvent();

CasperBot casperBot = casperBotRepository.save(new CasperBot(casperBotRequestDto, user.getId()));
CasperBot casperBot = casperBotRepository.save(new CasperBot(casperBotRequestDto, user.getPhoneNumber()));
lotteryEvent.addAppliedCount();

participants.updateCasperId(casperBot.getCasperId());
Expand Down Expand Up @@ -85,7 +84,6 @@ public LotteryParticipants registerUserIfNeed(BaseUser user, CasperBotRequestDto

addReferralAppliedCount(casperBotRequestDto);

user.updateLotteryParticipants(participant);
userRepository.save(user);
}

Expand All @@ -99,7 +97,7 @@ private void addReferralAppliedCount(CasperBotRequestDto casperBotRequestDto) th
String referralId = AESUtils.decrypt(casperBotRequestDto.getReferralId(), secretKey);
Optional<LotteryParticipants> referralParticipant =
lotteryParticipantsRepository.findByBaseUser(
userRepository.findById(referralId).orElse(null)
userRepository.findByPhoneNumber(referralId).orElse(null)
);
referralParticipant.ifPresent(LotteryParticipants::linkClickedCountAdded);
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public RushEventListResponseDto getAllRushEvents() {
public boolean isExists(String userId) {
LocalDate today = LocalDate.now();
Long todayEventId = eventCacheService.getTodayEvent(today).rushEventId();
return rushParticipantsRepository.existsByRushEvent_RushEventIdAndBaseUser_Id(todayEventId, userId);
return rushParticipantsRepository.existsByRushEvent_RushEventIdAndBaseUser_PhoneNumber(todayEventId, userId);
}

@Transactional
Expand All @@ -79,7 +79,7 @@ public void apply(BaseUser user, int optionId) {
Long todayEventId = eventCacheService.getTodayEvent(today).rushEventId();

// 이미 응모한 회원인지 검증
if (rushParticipantsRepository.existsByRushEvent_RushEventIdAndBaseUser_Id(todayEventId, user.getId())) {
if (rushParticipantsRepository.existsByRushEvent_RushEventIdAndBaseUser_PhoneNumber(todayEventId, user.getPhoneNumber())) {
throw new CustomException("이미 응모한 회원입니다.", CustomErrorCode.CONFLICT);
}

Expand All @@ -95,7 +95,7 @@ public void apply(BaseUser user, int optionId) {
public RushEventRateResponseDto getRushEventRate(BaseUser user) {
LocalDate today = LocalDate.now();
Long todayEventId = eventCacheService.getTodayEvent(today).rushEventId();
Optional<Integer> optionId = rushParticipantsRepository.getOptionIdByUserId(user.getId());
Optional<Integer> optionId = rushParticipantsRepository.getOptionIdByUserId(user.getPhoneNumber());
long leftOptionCount = rushParticipantsRepository.countByRushEvent_RushEventIdAndOptionId(todayEventId, 1);
long rightOptionCount = rushParticipantsRepository.countByRushEvent_RushEventIdAndOptionId(todayEventId, 2);

Expand All @@ -117,7 +117,7 @@ public RushEventResultResponseDto getRushEventResult(BaseUser user) {
long leftOption = rushParticipantsRepository.countByRushEvent_RushEventIdAndOptionId(todayEventId, 1);
long rightOption = rushParticipantsRepository.countByRushEvent_RushEventIdAndOptionId(todayEventId, 2);

Optional<Integer> optionIdOptional = rushParticipantsRepository.getOptionIdByUserId(user.getId());
Optional<Integer> optionIdOptional = rushParticipantsRepository.getOptionIdByUserId(user.getPhoneNumber());
if (optionIdOptional.isEmpty()) {
return new RushEventResultResponseDto(
null,
Expand All @@ -135,7 +135,7 @@ public RushEventResultResponseDto getRushEventResult(BaseUser user) {
// 동점인 경우
if (leftOption == rightOption) {
// 전체 참여자에서 등수 계산하기
long rank = rushParticipantsRepository.findUserRankByEventIdAndUserId(todayRushEvent.rushEventId(), user.getId());
long rank = rushParticipantsRepository.findUserRankByEventIdAndUserId(todayRushEvent.rushEventId(), user.getPhoneNumber());

// 각 옵션 선택지를 더하여 전체 참여자 수 구하기
long totalParticipants = leftOption + rightOption;
Expand All @@ -149,7 +149,7 @@ public RushEventResultResponseDto getRushEventResult(BaseUser user) {
long totalParticipants = (optionId == 1 ? leftOption : rightOption);

// eventId, userId, optionId 를 이용하여 해당 유저가 응모한 선택지에서 등수를 가져옴
long rank = rushParticipantsRepository.findUserRankByEventIdAndUserIdAndOptionId(todayRushEvent.rushEventId(), user.getId(), optionId);
long rank = rushParticipantsRepository.findUserRankByEventIdAndUserIdAndOptionId(todayRushEvent.rushEventId(), user.getPhoneNumber(), optionId);

// 해당 유저가 선택한 옵션이 패배한 경우
if ((optionId == 1 && leftOption < rightOption) || (optionId == 2 && leftOption > rightOption)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class UrlService {
//todo: 테스트 끝나면 수정필요
// 단축 url 생성
public ShortenUrlResponseDto generateShortUrl(BaseUser user) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
String encryptedUserId = AESUtils.encrypt(user.getId(), secretKey);
String encryptedUserId = AESUtils.encrypt(user.getPhoneNumber(), secretKey);

String originalUrl = clientUrl + "?" + "referralId=" + encryptedUserId;
String originalLocalUrl = localClientUrl + "?" + "referralId=" + encryptedUserId;
Expand Down
25 changes: 14 additions & 11 deletions Server/src/main/java/JGS/CasperEvent/global/entity/BaseUser.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,31 +9,34 @@
import lombok.EqualsAndHashCode;
import lombok.Getter;

import java.util.List;

@Getter
@Entity
@EqualsAndHashCode(callSuper = false)
@Inheritance(strategy = InheritanceType.JOINED)
public class BaseUser extends BaseEntity {


@Id
String id;
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

String phoneNumber;
Role role;

@JsonManagedReference
@OneToOne(mappedBy = "baseUser", cascade = CascadeType.ALL)
@OneToMany(mappedBy = "baseUser", cascade = CascadeType.ALL)
@JsonIgnore
private LotteryParticipants lotteryParticipants;
private List<LotteryParticipants> lotteryParticipants;

@JsonManagedReference
@OneToOne(mappedBy = "baseUser", cascade = CascadeType.ALL)
@OneToMany(mappedBy = "baseUser", cascade = CascadeType.ALL)
@JsonIgnore
private RushParticipants rushParticipants;

public void updateLotteryParticipants(LotteryParticipants lotteryParticipant) {
this.lotteryParticipants = lotteryParticipant;
}
private List<RushParticipants> rushParticipants;

public BaseUser(String id, Role role) {
this.id = id;
public BaseUser(String phoneNumber, Role role) {
this.phoneNumber = phoneNumber;
this.role = role;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
String token = getToken(httpServletRequest);
BaseUser user = getAuthenticateUser(token);
verifyAuthorization(requestUri, user);
log.info("값 : {}", user.getId());
log.info("값 : {}", user.getPhoneNumber());
httpServletRequest.setAttribute("user", user);
chain.doFilter(request, response);
} catch (JsonParseException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import JGS.CasperEvent.global.entity.BaseUser;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

public interface UserRepository extends JpaRepository<BaseUser, String> {
public interface UserRepository extends JpaRepository<BaseUser, Long> {
Optional<BaseUser> findByPhoneNumber(String phoneNumber);
}
Loading

0 comments on commit 883932a

Please sign in to comment.