Add more user-specific charts (#1991)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+69
-7
@@ -1,20 +1,17 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.*;
|
||||
import com.adityachandel.booklore.service.ReadingSessionService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@@ -50,15 +47,80 @@ public class ReadingSessionController {
|
||||
@Operation(summary = "Get reading session timeline for a week", description = "Returns reading sessions grouped by book for calendar timeline view")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Timeline data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid week or year"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid week, month, or year"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/timeline/week/{year}/{week}")
|
||||
@GetMapping("/timeline/week/{year}/{month}/{week}")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<ReadingSessionTimelineResponse>> getTimelineForWeek(
|
||||
@PathVariable int year,
|
||||
@PathVariable int month,
|
||||
@PathVariable int week) {
|
||||
List<ReadingSessionTimelineResponse> timelineData = readingSessionService.getSessionTimelineForWeek(year, week);
|
||||
List<ReadingSessionTimelineResponse> timelineData = readingSessionService.getSessionTimelineForWeek(year, month, week);
|
||||
return ResponseEntity.ok(timelineData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get reading speed analysis", description = "Returns average reading speed (progress per minute) over time for a specific year")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Reading speed data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/speed/year/{year}")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<ReadingSpeedResponse>> getReadingSpeedForYear(@PathVariable int year) {
|
||||
List<ReadingSpeedResponse> speedData = readingSessionService.getReadingSpeedForYear(year);
|
||||
return ResponseEntity.ok(speedData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get peak reading hours", description = "Returns reading activity distribution by hour of day. Can be filtered by year and/or month.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Peak reading hours retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/peak-hours")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<PeakReadingHoursResponse>> getPeakReadingHours(
|
||||
@RequestParam(required = false) Integer year,
|
||||
@RequestParam(required = false) Integer month) {
|
||||
List<PeakReadingHoursResponse> peakHours = readingSessionService.getPeakReadingHours(year, month);
|
||||
return ResponseEntity.ok(peakHours);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get favorite reading days", description = "Returns reading activity distribution by day of week. Can be filtered by year and/or month.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Favorite reading days retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/favorite-days")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<FavoriteReadingDaysResponse>> getFavoriteReadingDays(
|
||||
@RequestParam(required = false) Integer year,
|
||||
@RequestParam(required = false) Integer month) {
|
||||
List<FavoriteReadingDaysResponse> favoriteDays = readingSessionService.getFavoriteReadingDays(year, month);
|
||||
return ResponseEntity.ok(favoriteDays);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get genre statistics", description = "Returns reading statistics grouped by book genres/categories")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Genre statistics retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/genres")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<GenreStatisticsResponse>> getGenreStatistics() {
|
||||
List<GenreStatisticsResponse> genreStats = readingSessionService.getGenreStatistics();
|
||||
return ResponseEntity.ok(genreStats);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get completion timeline", description = "Returns reading completion statistics over time with status breakdown for a specific year")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Completion timeline retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/completion-timeline/year/{year}")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<CompletionTimelineResponse>> getCompletionTimeline(@PathVariable int year) {
|
||||
List<CompletionTimelineResponse> timeline = readingSessionService.getCompletionTimeline(year);
|
||||
return ResponseEntity.ok(timeline);
|
||||
}
|
||||
}
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
|
||||
public interface CompletionTimelineDto {
|
||||
Integer getYear();
|
||||
Integer getMonth();
|
||||
ReadStatus getReadStatus();
|
||||
Long getBookCount();
|
||||
}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
public interface FavoriteReadingDayDto {
|
||||
Integer getDayOfWeek();
|
||||
Long getSessionCount();
|
||||
Long getTotalDurationSeconds();
|
||||
}
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
public interface GenreStatisticsDto {
|
||||
String getGenre();
|
||||
Long getBookCount();
|
||||
Long getTotalSessions();
|
||||
Long getTotalDurationSeconds();
|
||||
}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
public interface PeakReadingHourDto {
|
||||
Integer getHourOfDay();
|
||||
Long getSessionCount();
|
||||
Long getTotalDurationSeconds();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
|
||||
public interface ReadingSpeedDto {
|
||||
Integer getTotalSessions();
|
||||
Double getAvgProgressPerMinute();
|
||||
LocalDate getDate();
|
||||
}
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CompletionTimelineResponse {
|
||||
private Integer year;
|
||||
private Integer month;
|
||||
private Long totalBooks;
|
||||
private Map<ReadStatus, Long> statusBreakdown;
|
||||
private Long finishedBooks;
|
||||
private Double completionRate;
|
||||
}
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class FavoriteReadingDaysResponse {
|
||||
private Integer dayOfWeek; // 1=Monday, 7=Sunday
|
||||
private String dayName;
|
||||
private Long sessionCount;
|
||||
private Long totalDurationSeconds;
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class GenreStatisticsResponse {
|
||||
private String genre;
|
||||
private Long bookCount;
|
||||
private Long totalSessions;
|
||||
private Long totalDurationSeconds;
|
||||
private Double averageSessionsPerBook;
|
||||
}
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PeakReadingHoursResponse {
|
||||
private Integer hourOfDay;
|
||||
private Long sessionCount;
|
||||
private Long totalDurationSeconds;
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ReadingSpeedResponse {
|
||||
private LocalDate date;
|
||||
private Double avgProgressPerMinute;
|
||||
private Integer totalSessions;
|
||||
}
|
||||
|
||||
+69
-4
@@ -1,7 +1,6 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.ReadingSessionCountDto;
|
||||
import com.adityachandel.booklore.model.dto.ReadingSessionTimelineDto;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
@@ -36,12 +35,78 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
||||
JOIN rs.book b
|
||||
WHERE rs.user.id = :userId
|
||||
AND YEAR(rs.startTime) = :year
|
||||
AND WEEK(rs.startTime) = :weekOfYear
|
||||
AND MONTH(rs.startTime) = :month
|
||||
AND WEEK(rs.startTime) = :week
|
||||
GROUP BY b.id, b.metadata.title, rs.bookType
|
||||
ORDER BY MIN(rs.startTime)
|
||||
""")
|
||||
List<ReadingSessionTimelineDto> findSessionTimelineByUserAndWeek(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") int year,
|
||||
@Param("weekOfYear") int weekOfYear);
|
||||
@Param("month") int month,
|
||||
@Param("week") int week);
|
||||
|
||||
@Query("""
|
||||
SELECT
|
||||
CAST(rs.createdAt AS LocalDate) as date,
|
||||
AVG(rs.progressDelta / (rs.durationSeconds / 60.0)) as avgProgressPerMinute,
|
||||
COUNT(rs) as totalSessions
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.durationSeconds > 0
|
||||
AND rs.progressDelta > 0
|
||||
AND YEAR(rs.createdAt) = :year
|
||||
GROUP BY CAST(rs.createdAt AS LocalDate)
|
||||
ORDER BY date
|
||||
""")
|
||||
List<ReadingSpeedDto> findReadingSpeedByUserAndYear(@Param("userId") Long userId, @Param("year") int year);
|
||||
|
||||
@Query("""
|
||||
SELECT
|
||||
HOUR(rs.startTime) as hourOfDay,
|
||||
COUNT(rs) as sessionCount,
|
||||
SUM(rs.durationSeconds) as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND (:year IS NULL OR YEAR(rs.startTime) = :year)
|
||||
AND (:month IS NULL OR MONTH(rs.startTime) = :month)
|
||||
GROUP BY HOUR(rs.startTime)
|
||||
ORDER BY hourOfDay
|
||||
""")
|
||||
List<PeakReadingHourDto> findPeakReadingHoursByUser(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") Integer year,
|
||||
@Param("month") Integer month);
|
||||
|
||||
@Query("""
|
||||
SELECT
|
||||
DAYOFWEEK(rs.startTime) as dayOfWeek,
|
||||
COUNT(rs) as sessionCount,
|
||||
SUM(rs.durationSeconds) as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND (:year IS NULL OR YEAR(rs.startTime) = :year)
|
||||
AND (:month IS NULL OR MONTH(rs.startTime) = :month)
|
||||
GROUP BY DAYOFWEEK(rs.startTime)
|
||||
ORDER BY dayOfWeek
|
||||
""")
|
||||
List<FavoriteReadingDayDto> findFavoriteReadingDaysByUser(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") Integer year,
|
||||
@Param("month") Integer month);
|
||||
|
||||
@Query("""
|
||||
SELECT
|
||||
c.name as genre,
|
||||
COUNT(DISTINCT b.id) as bookCount,
|
||||
COUNT(rs) as totalSessions,
|
||||
SUM(rs.durationSeconds) as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
JOIN b.metadata.categories c
|
||||
WHERE rs.user.id = :userId
|
||||
GROUP BY c.name
|
||||
ORDER BY totalSessions DESC
|
||||
""")
|
||||
List<GenreStatisticsDto> findGenreStatisticsByUser(@Param("userId") Long userId);
|
||||
}
|
||||
|
||||
+20
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.CompletionTimelineDto;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
@@ -40,4 +41,23 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
|
||||
@Param("userId") Long userId,
|
||||
@Param("snapshotId") String snapshotId
|
||||
);
|
||||
|
||||
@Query("""
|
||||
SELECT
|
||||
YEAR(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)) as year,
|
||||
MONTH(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)) as month,
|
||||
ubp.readStatus as readStatus,
|
||||
COUNT(ubp) as bookCount
|
||||
FROM UserBookProgressEntity ubp
|
||||
WHERE ubp.user.id = :userId
|
||||
AND ubp.readStatus IS NOT NULL
|
||||
AND ubp.readStatus NOT IN (com.adityachandel.booklore.model.enums.ReadStatus.UNSET, com.adityachandel.booklore.model.enums.ReadStatus.UNREAD)
|
||||
AND COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime) IS NOT NULL
|
||||
AND YEAR(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)) = :year
|
||||
GROUP BY YEAR(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)),
|
||||
MONTH(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)),
|
||||
ubp.readStatus
|
||||
ORDER BY year DESC, month DESC
|
||||
""")
|
||||
List<CompletionTimelineDto> findCompletionTimelineByUser(@Param("userId") Long userId, @Param("year") int year);
|
||||
}
|
||||
|
||||
+122
-2
@@ -4,13 +4,20 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.CompletionTimelineResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.FavoriteReadingDaysResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.GenreStatisticsResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.PeakReadingHoursResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSpeedResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.ReadingSessionRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -18,7 +25,9 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -30,6 +39,7 @@ public class ReadingSessionService {
|
||||
private final ReadingSessionRepository readingSessionRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
|
||||
@Transactional
|
||||
public void recordSession(ReadingSessionRequest request) {
|
||||
@@ -73,11 +83,11 @@ public class ReadingSessionService {
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
|
||||
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int month, int week) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
return readingSessionRepository.findSessionTimelineByUserAndWeek(userId, year, week)
|
||||
return readingSessionRepository.findSessionTimelineByUserAndWeek(userId, year, month, week)
|
||||
.stream()
|
||||
.map(dto -> ReadingSessionTimelineResponse.builder()
|
||||
.bookId(dto.getBookId())
|
||||
@@ -90,4 +100,114 @@ public class ReadingSessionService {
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ReadingSpeedResponse> getReadingSpeedForYear(int year) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
return readingSessionRepository.findReadingSpeedByUserAndYear(userId, year)
|
||||
.stream()
|
||||
.map(dto -> ReadingSpeedResponse.builder()
|
||||
.date(dto.getDate())
|
||||
.avgProgressPerMinute(dto.getAvgProgressPerMinute())
|
||||
.totalSessions(dto.getTotalSessions())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<PeakReadingHoursResponse> getPeakReadingHours(Integer year, Integer month) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
return readingSessionRepository.findPeakReadingHoursByUser(userId, year, month)
|
||||
.stream()
|
||||
.map(dto -> PeakReadingHoursResponse.builder()
|
||||
.hourOfDay(dto.getHourOfDay())
|
||||
.sessionCount(dto.getSessionCount())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
String[] dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
|
||||
|
||||
return readingSessionRepository.findFavoriteReadingDaysByUser(userId, year, month)
|
||||
.stream()
|
||||
.map(dto -> FavoriteReadingDaysResponse.builder()
|
||||
.dayOfWeek(dto.getDayOfWeek())
|
||||
.dayName(dayNames[dto.getDayOfWeek() - 1])
|
||||
.sessionCount(dto.getSessionCount())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<GenreStatisticsResponse> getGenreStatistics() {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
return readingSessionRepository.findGenreStatisticsByUser(userId)
|
||||
.stream()
|
||||
.map(dto -> {
|
||||
double avgSessionsPerBook = dto.getBookCount() > 0
|
||||
? (double) dto.getTotalSessions() / dto.getBookCount()
|
||||
: 0.0;
|
||||
|
||||
return GenreStatisticsResponse.builder()
|
||||
.genre(dto.getGenre())
|
||||
.bookCount(dto.getBookCount())
|
||||
.totalSessions(dto.getTotalSessions())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
.averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0)
|
||||
.build();
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<CompletionTimelineResponse> getCompletionTimeline(int year) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
Map<String, Map<ReadStatus, Long>> timelineMap = new HashMap<>();
|
||||
|
||||
userBookProgressRepository.findCompletionTimelineByUser(userId, year).forEach(dto -> {
|
||||
String key = dto.getYear() + "-" + dto.getMonth();
|
||||
timelineMap.computeIfAbsent(key, k -> new HashMap<>())
|
||||
.put(dto.getReadStatus(), dto.getBookCount());
|
||||
});
|
||||
|
||||
return timelineMap.entrySet().stream()
|
||||
.map(entry -> {
|
||||
String[] parts = entry.getKey().split("-");
|
||||
int yearPart = Integer.parseInt(parts[0]);
|
||||
int month = Integer.parseInt(parts[1]);
|
||||
Map<ReadStatus, Long> statusBreakdown = entry.getValue();
|
||||
|
||||
long totalBooks = statusBreakdown.values().stream().mapToLong(Long::longValue).sum();
|
||||
long finishedBooks = statusBreakdown.getOrDefault(ReadStatus.READ, 0L);
|
||||
double completionRate = totalBooks > 0 ? (finishedBooks * 100.0 / totalBooks) : 0.0;
|
||||
|
||||
return CompletionTimelineResponse.builder()
|
||||
.year(yearPart)
|
||||
.month(month)
|
||||
.totalBooks(totalBooks)
|
||||
.statusBreakdown(statusBreakdown)
|
||||
.finishedBooks(finishedBooks)
|
||||
.completionRate(Math.round(completionRate * 100.0) / 100.0)
|
||||
.build();
|
||||
})
|
||||
.sorted((a, b) -> {
|
||||
int cmp = b.getYear().compareTo(a.getYear());
|
||||
return cmp != 0 ? cmp : b.getMonth().compareTo(a.getMonth());
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user