Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] 솝트 로그 API 개발 - #437 #459

Open
wants to merge 7 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.sopt.app.common.exception.BadRequestException;
import org.sopt.app.common.exception.UnauthorizedException;
import org.sopt.app.common.response.ErrorCode;
import org.sopt.app.domain.entity.User;
import org.sopt.app.domain.enums.UserStatus;
import org.sopt.app.presentation.auth.AppAuthRequest.AccessTokenRequest;
import org.sopt.app.presentation.auth.AppAuthRequest.CodeRequest;
Expand Down Expand Up @@ -239,4 +240,15 @@ private <T extends PostWithMemberInfo> List<T> getPostsWithMemberInfo(String pla
}
return mutablePosts;
}

public int getUserSoptLevel(User user) {
final Map<String, String> accessToken = createAuthorizationHeaderByUserPlaygroundToken(user.getPlaygroundToken());
return playgroundClient.getPlayGroundUserSoptLevel(accessToken,user.getPlaygroundId()).soptProjectCount();
}

public PlaygroundProfile getPlayGroundProfile(String accessToken) {
Map<String, String> requestHeader = createAuthorizationHeaderByUserPlaygroundToken(accessToken);
return playgroundClient.getPlayGroundProfile(requestHeader);

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.sopt.app.application.auth.dto.PlaygroundAuthTokenInfo.RefreshedToken;
import org.sopt.app.application.playground.dto.PlayGroundEmploymentResponse;
import org.sopt.app.application.playground.dto.PlayGroundPostDetailResponse;
import org.sopt.app.application.playground.dto.PlayGroundUserSoptLevelResponse;
import org.sopt.app.application.playground.dto.PlaygroundPostInfo.PlaygroundPostResponse;
import org.sopt.app.application.playground.dto.PlaygroundProfileInfo.ActiveUserIds;
import org.sopt.app.application.playground.dto.PlaygroundProfileInfo.OwnPlaygroundProfile;
Expand Down Expand Up @@ -66,4 +67,10 @@ PlayGroundEmploymentResponse getPlaygroundEmploymentPost(@HeaderMap Map<String,
@RequestLine("GET /api/v1/community/posts/{postId}")
PlayGroundPostDetailResponse getPlayGroundPostDetail(@HeaderMap Map<String, String> headers,
@Param Long postId);

@RequestLine("GET /internal/api/v1/members/{memberId}/project")
PlayGroundUserSoptLevelResponse getPlayGroundUserSoptLevel(@HeaderMap Map<String, String> headers, @Param Long memberId);

@RequestLine("GET /api/v1/members/profile/me")
PlaygroundProfile getPlayGroundProfile(@HeaderMap Map<String, String> headers);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.sopt.app.application.playground.dto;

public record PlayGroundUserSoptLevelResponse(
Long id,
String profileImage,
int soptProjectCount
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public static class PlaygroundProfile {
private Long memberId;
private String name;
private String profileImage;
private String introduction;
private List<ActivityCardinalInfo> activities;

public ActivityCardinalInfo getLatestActivity() {
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/org/sopt/app/application/poke/PokeService.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,8 @@ private PokeHistory createPokeByApplyingReply(
.isAnonymous(isAnonymous)
.build());
}

public Long getUserPokeCount(Long userId) {
return historyRepository.countByPokerIdOrPokedId(userId, userId);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.sopt.app.application.rank;

import java.util.AbstractMap;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
Expand All @@ -20,4 +21,16 @@ public List<Main> calculateRank() {
.map(user -> Main.of(rankPoint.getAndIncrement(), user))
.toList();
}

public Long getUserRank(Long userId) {
AtomicInteger rankPoint = new AtomicInteger(1);

return Long.valueOf(soptampUserInfos.stream()
.sorted(Comparator.comparing(SoptampUserInfo::getTotalPoints).reversed())
.map(user -> new AbstractMap.SimpleEntry<>(rankPoint.getAndIncrement(), user))
.filter(entry -> entry.getValue().getId().equals(userId))
.map(AbstractMap.SimpleEntry::getKey)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("User not found")));
Comment on lines +30 to +34
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2. 전부를 map으로 변환하고 찾는 것이 아닌 totalPoint를 이용해 sort된 유저를 1등부터 확인하며 userId와 일치하는 유저를 찾아 반환하는 것이 더 빠르게 순위를 반환하는 방법일 것 같아요

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 좋은 방법이네요 감사합니다!

}
}
23 changes: 23 additions & 0 deletions src/main/java/org/sopt/app/application/user/UserService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.sopt.app.application.user;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
Expand All @@ -8,7 +9,10 @@
import org.sopt.app.common.exception.NotFoundException;
import org.sopt.app.common.exception.UnauthorizedException;
import org.sopt.app.common.response.ErrorCode;
import org.sopt.app.domain.entity.Icons;
import org.sopt.app.domain.entity.User;
import org.sopt.app.domain.enums.IconType;
import org.sopt.app.interfaces.postgres.IconRepository;
import org.sopt.app.interfaces.postgres.UserRepository;
import org.sopt.app.presentation.auth.AppAuthRequest.AccessTokenRequest;
import org.springframework.stereotype.Service;
Expand All @@ -21,6 +25,7 @@
public class UserService {

private final UserRepository userRepository;
private final IconRepository iconRepository;

@Transactional
public Long upsertUser(LoginInfo loginInfo) {
Expand Down Expand Up @@ -82,4 +87,22 @@ public List<Long> getAllPlaygroundIds() {
public boolean isUserExist(Long userId) {
return userRepository.existsById(userId);
}

public Long getDuration(Long myGeneration, Long currentGeneration) {
long monthsBetweenGenerations = (currentGeneration - myGeneration) * 6;
LocalDate now = LocalDate.now();
int currentMonth = now.getMonthValue();
int startMonth = (currentGeneration % 2 == 0) ? 3 : 9;
int monthsSinceStart = currentMonth - startMonth;
if (monthsSinceStart < 0) {
monthsSinceStart += 12;
}
return monthsBetweenGenerations + monthsSinceStart;
}
Comment on lines +91 to +101
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2. 현재 홈화면에서 사용되는 ActivityDurationCalculator 사용하면 될 것 같습니다!


public List<String> getIcons(IconType iconType) {
return iconRepository.findAllByIconType(iconType).stream()
.map(Icons::getIconUrl)
.toList();
}
}
27 changes: 27 additions & 0 deletions src/main/java/org/sopt/app/domain/entity/Icons.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.sopt.app.domain.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.sopt.app.domain.enums.IconType;

@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Icons {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String iconUrl;

@Enumerated(EnumType.STRING)
private IconType iconType;
}
5 changes: 5 additions & 0 deletions src/main/java/org/sopt/app/domain/enums/IconType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package org.sopt.app.domain.enums;

public enum IconType {
ACTIVE, INACTIVE
}
29 changes: 26 additions & 3 deletions src/main/java/org/sopt/app/facade/AuthFacade.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
package org.sopt.app.facade;

import java.util.List;
import lombok.RequiredArgsConstructor;
import org.sopt.app.application.auth.JwtTokenService;
import org.sopt.app.application.auth.dto.PlaygroundAuthTokenInfo.*;
import org.sopt.app.application.auth.dto.PlaygroundAuthTokenInfo.AppToken;
import org.sopt.app.application.playground.PlaygroundAuthService;
import org.sopt.app.application.playground.dto.PlaygroundProfileInfo.*;
import org.sopt.app.application.playground.dto.PlaygroundProfileInfo.LoginInfo;
import org.sopt.app.application.playground.dto.PlaygroundProfileInfo.PlaygroundMain;
import org.sopt.app.application.playground.dto.PlaygroundProfileInfo.PlaygroundProfile;
import org.sopt.app.application.poke.PokeService;
import org.sopt.app.application.soptamp.SoptampUserService;
import org.sopt.app.application.user.UserService;
import org.sopt.app.presentation.auth.AppAuthRequest.*;
import org.sopt.app.domain.entity.User;
import org.sopt.app.domain.enums.IconType;
import org.sopt.app.presentation.auth.AppAuthRequest.AccessTokenRequest;
import org.sopt.app.presentation.auth.AppAuthRequest.CodeRequest;
import org.sopt.app.presentation.auth.AppAuthResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -20,6 +27,7 @@ public class AuthFacade {
private final UserService userService;
private final PlaygroundAuthService playgroundAuthService;
private final SoptampUserService soptampUserService;
private final PokeService pokeService;

@Transactional
public AppAuthResponse loginWithPlayground(CodeRequest codeRequest) {
Expand Down Expand Up @@ -66,4 +74,19 @@ public AppAuthResponse getRefreshToken(String refreshToken) {
.build();
}

public int getUserSoptLevel(User user) {
return playgroundAuthService.getUserSoptLevel(user);
}

public PlaygroundProfile getUserDetails(User user) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P4. user를 매개변수로 전달하는 것이 아닌 필요한 playgroundToken만 전달하는 것이 좋을 것 같아요

return playgroundAuthService.getPlayGroundProfile(user.getPlaygroundToken());
}

public Long getDuration(Long Mygeneration, Long generation) {
return userService.getDuration(Mygeneration, generation);
}

public List<String> getIcons(IconType iconType) {
return userService.getIcons(iconType);
}
}
4 changes: 4 additions & 0 deletions src/main/java/org/sopt/app/facade/PokeFacade.java
Original file line number Diff line number Diff line change
Expand Up @@ -259,4 +259,8 @@ public RecommendedFriendsRequest getRecommendedFriendsByTypeList(
public boolean getIsNewUser(Long userId) {
return friendService.getIsNewUser(userId);
}

public Long getUserPokeCount(Long userId) {
return pokeService.getUserPokeCount(userId);
}
}
7 changes: 7 additions & 0 deletions src/main/java/org/sopt/app/facade/RankFacade.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,11 @@ public PartRank findPartRank(Part part) {
.filter(partRank -> partRank.getPart().equals(part.getPartName()))
.findFirst().orElseThrow();
}

@Transactional(readOnly = true)
public Long findUserRank(Long userId) {
List<SoptampUserInfo> soptampUserInfos = soptampUserFinder.findAllOfCurrentGeneration();
SoptampUserRankCalculator soptampUserRankCalculator = new SoptampUserRankCalculator(soptampUserInfos);
return soptampUserRankCalculator.getUserRank(userId);
}
}
10 changes: 10 additions & 0 deletions src/main/java/org/sopt/app/interfaces/postgres/IconRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.sopt.app.interfaces.postgres;

import java.util.List;
import org.sopt.app.domain.entity.Icons;
import org.sopt.app.domain.enums.IconType;
import org.springframework.data.jpa.repository.JpaRepository;

public interface IconRepository extends JpaRepository<Icons,Long> {
List<Icons> findAllByIconType(IconType iconType);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.sopt.app.interfaces.postgres;

import jakarta.validation.constraints.NotNull;
import java.util.List;
import org.sopt.app.domain.entity.poke.PokeHistory;
import org.springframework.data.domain.Page;
Expand Down Expand Up @@ -36,4 +37,6 @@ List<PokeHistory> findAllWithFriendOrderByCreatedAtDescIsReplyFalse(@Param("user
List<PokeHistory> findAllPokeHistoryByUsers(@Param("userId") Long userId, @Param("friendId") Long friendId);

Long countByPokedIdAndIsReplyIsFalse(Long pokedId);

Long countByPokerIdOrPokedId(@NotNull Long pokerId, @NotNull Long pokedId);
}
37 changes: 36 additions & 1 deletion src/main/java/org/sopt/app/presentation/user/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,29 @@
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.sopt.app.application.playground.dto.PlaygroundProfileInfo.PlaygroundProfile;
import org.sopt.app.application.soptamp.SoptampUserService;
import org.sopt.app.domain.entity.User;
import org.sopt.app.domain.enums.IconType;
import org.sopt.app.facade.AuthFacade;
import org.sopt.app.facade.PokeFacade;
import org.sopt.app.facade.RankFacade;
import org.sopt.app.facade.SoptampFacade;
import org.sopt.app.presentation.user.UserResponse.SoptLog;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v2/user")
Expand All @@ -28,6 +37,11 @@ public class UserController {

private final SoptampUserService soptampUserService;
private final SoptampFacade soptampFacade;
private final AuthFacade authFacade;
private final PokeFacade pokeFacade;
private final RankFacade rankFacade;
@Value("${sopt.current.generation}")
private Long generation;

@Operation(summary = "솝탬프 정보 조회")
@ApiResponses({
Expand Down Expand Up @@ -62,4 +76,25 @@ public ResponseEntity<UserResponse.ProfileMessage> editProfileMessage(
return ResponseEntity.ok(response);
}

@Operation(summary = "유저 솝트로그 조회")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "success"),
@ApiResponse(responseCode = "500", description = "server error", content = @Content)
})
@GetMapping(value = "/sopt-log")
public ResponseEntity<UserResponse.SoptLog> getUserSoptLog(@AuthenticationPrincipal User user) {
int soptLevel = authFacade.getUserSoptLevel(user);
Long pokeCount = pokeFacade.getUserPokeCount(user.getId());
PlaygroundProfile playgroundProfile = authFacade.getUserDetails(user);
Long soptampRank = null;
Long soptDuring = null;
Comment on lines +89 to +90
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2. Long 값을 null로 전달하는 것보다 isActive 값에 따라서 ResponseEntity를 return하는 것이 좋아보여요.
팩토리 메서드 패턴을 이용해서 클라에 전달할 때만 null로 전달하는 것이 좋을 것 같아요!

Boolean isActive = playgroundProfile.getLatestActivity().getGeneration() == generation;
if (isActive) {
soptampRank = rankFacade.findUserRank(user.getId());
} else {
soptDuring = authFacade.getDuration(playgroundProfile.getLatestActivity().getGeneration(), generation);
}
List<String> icons = authFacade.getIcons(isActive ? IconType.ACTIVE : IconType.INACTIVE);
return ResponseEntity.ok(SoptLog.of(soptLevel, pokeCount, soptampRank, soptDuring,isActive,icons, playgroundProfile));
}
}
Loading