8000 [Feature] 유저 연속 참여 및 주간 활동 조회 기능 구현 by wngktjd13 · Pull Request #47 · If-u-Lab/If-u-server · GitHub
[go: up one dir, main page]

Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

import com.ifu.ifu_server.domain.comment.entity.Comment;
import com.ifu.ifu_server.domain.question.entity.Question;
import java.time.LocalDateTime;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

Expand All @@ -21,4 +24,10 @@ public interface CommentRepository extends JpaRepository<Comment, Long> {

// 특정 사용자의 총 댓글 수 조회 (삭제된 댓글 포함)
long countByUserId(Long userId);

/**
* 특정 사용자의 활동 일시 조회 (기간 내)
*/
@Query("SELECT c.createdAt FROM Comment c WHERE c.user.id = :userId AND c.createdAt >= :startDateTime")
List<LocalDateTime> findActivityDateTimesByUserIdAndCreatedAtAfter(@Param("userId") Long userId, @Param("startDateTime") LocalDateTime startDateTime);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.ifu.ifu_server.domain.question.repository.QuestionRepository;
import com.ifu.ifu_server.domain.user.entity.User;
import com.ifu.ifu_server.domain.user.repository.UserRepository;
import com.ifu.ifu_server.domain.user.service.UserService;
import com.ifu.ifu_server.global.exception.BusinessException;
import com.ifu.ifu_server.global.exception.ErrorCode;
import lombok.RequiredArgsConstructor;
Expand All @@ -39,11 +40,11 @@ public class CommentService {
private final CommentBlockRepository commentBlockRepository;
private final QuestionRepository questionRepository;
private final UserRepository userRepository;
private final UserService userService;

@Transactional
public CommentResponse createComment(Long userId, CommentCreateRequest request) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND));
User user = userService.findValidUser(userId);

Question question = questionRepository.findById(request.questionId())
.orElseThrow(() -> new BusinessException(ErrorCode.QUESTION_NOT_FOUND));
Expand Down Expand Up @@ -73,6 +74,9 @@ public CommentResponse createComment(Long userId, CommentCreateRequest request)

Comment savedComment = commentRepository.save(comment);

// streak 업데이트
userService.updateUserStreak(user);

return CommentMapper.toCommentResponse(savedComment, List.of(), List.of());
}

Expand Down
16 changes: 13 additions & 3 deletions src/main/java/com/ifu/ifu_server/domain/user/dto/UserResponse.java
8000
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import com.ifu.ifu_server.domain.user.entity.Role;
import com.ifu.ifu_server.domain.user.entity.User;

import java.util.List;

@JsonInclude(JsonInclude.Include.NON_NULL)
public record UserResponse(
Long id,
Expand All @@ -17,7 +19,7 @@ public record UserResponse(
) {

public static UserResponse of(User user, long totalVotes, long totalComments,
double participationRate) {
double participationRate, List<Boolean> weeklyActivity) {
boolean isDeleted = user.isDeleted();
return new UserResponse(
user.getId(),
Expand All @@ -27,14 +29,22 @@ public static UserResponse of(User user, long totalVotes, long totalComments,
isDeleted ? null : user.getRole(),
isDeleted,
isDeleted ? null : user.isNotificationEnabled(),
isDeleted ? null : new UserStats(totalVotes, totalComments, participationRate)
isDeleted ? null : new UserStats(
totalVotes,
totalComments,
participationRate,
user.getCurrentStreak(),
weeklyActivity
)
);
}

public record UserStats(
long totalVotes,
long totalComments,
double participationRate
double participationRate,
int currentStreak,
List<Boolean> weeklyActivity
) {

}
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/com/ifu/ifu_server/domain/user/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import jakarta.persistence.*;
import lombok.*;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Entity
Expand Down Expand Up @@ -37,6 +38,13 @@ public class User extends BaseEntity {
@Column(name = "notification_enabled", nullable = false)
private boolean notificationEnabled = false;

@Builder.Default
@Column(name = "current_streak", nullable = false)
private int currentStreak = 0;

@Column(name = "last_activity_date")
private LocalDate lastActivityDate;

public void delete() {
this.deletedAt = LocalDateTime.now();
}
Expand Down Expand Up @@ -75,4 +83,12 @@ public void updateRefreshToken(String refreshToken) {
public void updateNotificationEnabled(boolean notificationEnabled) {
this.notificationEnabled = notificationEnabled;
}

public void updateStreak(int streak, LocalDate date) {
if (streak < 0) {
throw new IllegalArgumentException("Streak cannot be negative");
}
this.currentStreak = streak;
this.lastActivityDate = date;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
@Service
Expand All @@ -32,6 +38,7 @@ public class UserService {
private final VoteRepository voteRepository;
private final CommentRepository commentRepository;
private final QuestionRepository questionRepository;
private final Clock clock;

/**
* 유효한 사용자 조회 - 삭제되지 않은 사용자만 조회
Expand Down Expand Up @@ -79,7 +86,71 @@ public UserResponse getUserInfoWithStats(Long userId) {
? Math.round((double) votedQuestions / totalQuestions * 1000.0) / 10.0
: 0.0;

return UserResponse.of(user, totalVotes, totalComments, participationRate);
// 최근 7일 활동 조회
List<Boolean> weeklyActivity = getWeeklyActivity(userId);

return UserResponse.of(user, totalVotes, totalComments, participationRate, weeklyActivity);
}

/**
* 사용자 streak 업데이트
* - 첫 활동: streak = 1
* - 같은 날 중복: 변화 없음
* - 연속 활동: streak + 1
* - 하루 이상 빠짐: streak = 1 (초기화)
*
* @param user 사용자 엔티티
*/
@Transactional
public void updateUserStreak(User user) {
LocalDate today = LocalDate.now(clock);
LocalDate lastActivityDate = user.getLastActivityDate();

if (lastActivityDate == null) {
// 첫 활동
user.updateStreak(1, today);
} else if (lastActivityDate.equals(today)) {
// 같은 날 중복 활동 - 변화 없음
return;
} else if (lastActivityDate.equals(today.minusDays(1))) {
// 어제 활동했음 - 연속
user.updateStreak(user.getCurrentStreak() + 1, today);
} else {
// 하루 이상 빠짐 - 초기화
user.updateStreak(1, today);
}

log.info("Streak updated: userId={}, streak={}", user.getId(), user.getCurrentStreak());
}

/**
* 최근 7일간 활동 여부 조회 (실시간 계산)
*
* @param userId 사용자 ID
* @return 최근 7일간 활동 여부 리스트 (index 0: 오늘, index 6: 6일 전)
*/
public List<Boolean> getWeeklyActivity(Long userId) {
LocalDate today = LocalDate.now(clock);
LocalDateTime startDateTime = today.minusDays(6).atStartOfDay();

// 투표와 댓글 활동 일시를 조회하여 날짜로 변환 후 Set으로 합침
Set<LocalDate> activityDates = voteRepository
.findActivityDateTimesByUserIdAndCreatedAtAfter(userId, startDateTime)
.stream()
.map(LocalDateTime::toLocalDate)
.collect(Collectors.toSet());

commentRepository
.findActivityDateTimesByUserIdAndCreatedAtAfter(userId, startDateTime)
.stream()
.map(LocalDateTime::toLocalDate)
.forEach(activityDates::add);

// 최근 7일 활동 여부 계산 (index 0: 오늘, index 6: 6일 전)
return IntStream.range(0, 7)
.mapToObj(i -> today.minusDays(i))
.map(activityDates::contains)
.collect(Collectors.toList());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.ifu.ifu_server.domain.question.entity.Question;
import com.ifu.ifu_server.domain.user.entity.User;
import com.ifu.ifu_server.domain.vote.entity.Vote;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
Expand Down Expand Up @@ -40,4 +41,10 @@ public interface VoteRepository extends JpaRepository<Vote, Long> {
*/
@Query("SELECT COUNT(DISTINCT v.question.id) FROM Vote v WHERE v.user.id = :userId")
long countDistinctQuestionsByUserId(@Param("userId") Long userId);

/**
* 특정 사용자의 활동 일시 조회 (기간 내)
*/
@Query("SELECT v.createdAt FROM Vote v WHERE v.user.id = :userId AND v.createdAt >= :startDateTime")
List<LocalDateTime> findActivityDateTimesByUserIdAndCreatedAtAfter(@Param("userId") Long userId, @Param("startDateTime") LocalDateTime startDateTime);
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ public VoteResponse vote(Long userId, Long questionId, VoteRequest request) {

incrementVoteStats(voteStats, choice);
isChanged = false;

// streak 업데이트 (새 투표만)
userService.updateUserStreak(user);

log.info("새 투표 - userId: {}, questionId: {}, choice: {}", userId, questionId, choice);
}

Expand Down
15 changes: 15 additions & 0 deletions src/main/java/com/ifu/ifu_server/global/config/ClockConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.ifu.ifu_server.global.config;

import java.time.Clock;
import java.time.ZoneId;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ClockConfig {

@Bean
public Clock clock() {
return Clock.system(ZoneId.of("Asia/Seoul"));
}
}
0