From 88622a66dd90097e2b41c2b64eeec19a3b71afe4 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Sun, 22 Feb 2026 19:29:21 -0700 Subject: [PATCH] feat: add book distributions endpoint for mobile stats (#2855) * feat: add book distributions endpoint for mobile stats Add GET /api/v1/user-stats/book-distributions returning rating, reading progress, and read status distributions. Progress percentages are coalesced across all sync sources and bucketed into 6 ranges. * fix(test): use stable date for thisPeriod_week test to avoid Monday boundary flake The test used Instant.now().minus(1 day) which falls in the previous ISO week when CI runs on Monday (UTC). Use a date guaranteed to be within the current week instead. --------- Co-authored-by: acx10 --- .../controller/UserStatsController.java | 12 +++ .../model/dto/ProgressPercentDto.java | 9 +++ .../model/dto/RatingDistributionDto.java | 6 ++ .../model/dto/StatusDistributionDto.java | 8 ++ .../response/BookDistributionsResponse.java | 48 ++++++++++++ .../UserBookProgressRepository.java | 34 +++++++++ .../service/ReadingSessionService.java | 75 +++++++++++++++++++ ...okRuleEvaluatorServiceIntegrationTest.java | 14 +++- 8 files changed, 202 insertions(+), 4 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/ProgressPercentDto.java create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/RatingDistributionDto.java create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/StatusDistributionDto.java create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/response/BookDistributionsResponse.java diff --git a/booklore-api/src/main/java/org/booklore/controller/UserStatsController.java b/booklore-api/src/main/java/org/booklore/controller/UserStatsController.java index 30dd3496b..65040bb68 100644 --- a/booklore-api/src/main/java/org/booklore/controller/UserStatsController.java +++ b/booklore-api/src/main/java/org/booklore/controller/UserStatsController.java @@ -160,6 +160,18 @@ public class UserStatsController { return ResponseEntity.ok(data); } + @Operation(summary = "Get book distribution statistics", description = "Returns rating, progress, and read status distributions for the authenticated user's library") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Book distributions retrieved successfully"), + @ApiResponse(responseCode = "401", description = "Unauthorized") + }) + @GetMapping("/book-distributions") + @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") + public ResponseEntity getBookDistributions() { + BookDistributionsResponse data = readingSessionService.getBookDistributions(); + return ResponseEntity.ok(data); + } + @Operation(summary = "Get all reading dates", description = "Returns daily reading session counts across all time for the authenticated user") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Reading dates retrieved successfully"), diff --git a/booklore-api/src/main/java/org/booklore/model/dto/ProgressPercentDto.java b/booklore-api/src/main/java/org/booklore/model/dto/ProgressPercentDto.java new file mode 100644 index 000000000..a46dfc743 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/ProgressPercentDto.java @@ -0,0 +1,9 @@ +package org.booklore.model.dto; + +public interface ProgressPercentDto { + Float getKoreaderProgressPercent(); + Float getKoboProgressPercent(); + Float getEpubProgressPercent(); + Float getPdfProgressPercent(); + Float getCbxProgressPercent(); +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/RatingDistributionDto.java b/booklore-api/src/main/java/org/booklore/model/dto/RatingDistributionDto.java new file mode 100644 index 000000000..e10b6cf6d --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/RatingDistributionDto.java @@ -0,0 +1,6 @@ +package org.booklore.model.dto; + +public interface RatingDistributionDto { + Integer getRating(); + Long getCount(); +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/StatusDistributionDto.java b/booklore-api/src/main/java/org/booklore/model/dto/StatusDistributionDto.java new file mode 100644 index 000000000..461db95b3 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/StatusDistributionDto.java @@ -0,0 +1,8 @@ +package org.booklore.model.dto; + +import org.booklore.model.enums.ReadStatus; + +public interface StatusDistributionDto { + ReadStatus getStatus(); + Long getCount(); +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/response/BookDistributionsResponse.java b/booklore-api/src/main/java/org/booklore/model/dto/response/BookDistributionsResponse.java new file mode 100644 index 000000000..fec5c884e --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/response/BookDistributionsResponse.java @@ -0,0 +1,48 @@ +package org.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class BookDistributionsResponse { + + private List ratingDistribution; + private List progressDistribution; + private List statusDistribution; + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class RatingBucket { + private int rating; + private long count; + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class ProgressBucket { + private String range; + private int min; + private int max; + private long count; + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class StatusBucket { + private String status; + private long count; + } +} diff --git a/booklore-api/src/main/java/org/booklore/repository/UserBookProgressRepository.java b/booklore-api/src/main/java/org/booklore/repository/UserBookProgressRepository.java index a4c28c2ae..04e545157 100644 --- a/booklore-api/src/main/java/org/booklore/repository/UserBookProgressRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/UserBookProgressRepository.java @@ -2,6 +2,9 @@ package org.booklore.repository; import org.booklore.model.dto.BookCompletionHeatmapDto; import org.booklore.model.dto.CompletionTimelineDto; +import org.booklore.model.dto.ProgressPercentDto; +import org.booklore.model.dto.RatingDistributionDto; +import org.booklore.model.dto.StatusDistributionDto; import org.booklore.model.entity.UserBookProgressEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; @@ -162,4 +165,35 @@ public interface UserBookProgressRepository extends JpaRepository findRatingDistributionByUser(@Param("userId") Long userId); + + @Query(""" + SELECT ubp.readStatus as status, COUNT(ubp) as count + FROM UserBookProgressEntity ubp + WHERE ubp.user.id = :userId + AND ubp.readStatus IS NOT NULL + AND ubp.readStatus <> org.booklore.model.enums.ReadStatus.UNSET + GROUP BY ubp.readStatus + """) + List findStatusDistributionByUser(@Param("userId") Long userId); + + @Query(""" + SELECT ubp.koreaderProgressPercent as koreaderProgressPercent, + ubp.koboProgressPercent as koboProgressPercent, + ubp.epubProgressPercent as epubProgressPercent, + ubp.pdfProgressPercent as pdfProgressPercent, + ubp.cbxProgressPercent as cbxProgressPercent + FROM UserBookProgressEntity ubp + WHERE ubp.user.id = :userId + """) + List findAllProgressPercentsByUser(@Param("userId") Long userId); } diff --git a/booklore-api/src/main/java/org/booklore/service/ReadingSessionService.java b/booklore-api/src/main/java/org/booklore/service/ReadingSessionService.java index 7da92d86d..83592826d 100644 --- a/booklore-api/src/main/java/org/booklore/service/ReadingSessionService.java +++ b/booklore-api/src/main/java/org/booklore/service/ReadingSessionService.java @@ -6,6 +6,7 @@ import org.booklore.model.dto.BookLoreUser; import org.booklore.model.dto.CompletionRaceSessionDto; import org.booklore.model.dto.request.ReadingSessionRequest; import org.booklore.model.dto.PageTurnerSessionDto; +import org.booklore.model.dto.ProgressPercentDto; import org.booklore.model.dto.response.*; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookLoreUserEntity; @@ -418,6 +419,80 @@ public class ReadingSessionService { .collect(Collectors.toList()); } + @Transactional(readOnly = true) + public BookDistributionsResponse getBookDistributions() { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + Long userId = authenticatedUser.getId(); + + // Rating distribution + List ratingBuckets = userBookProgressRepository.findRatingDistributionByUser(userId) + .stream() + .map(dto -> BookDistributionsResponse.RatingBucket.builder() + .rating(dto.getRating()) + .count(dto.getCount()) + .build()) + .collect(Collectors.toList()); + + // Status distribution + List statusBuckets = userBookProgressRepository.findStatusDistributionByUser(userId) + .stream() + .map(dto -> BookDistributionsResponse.StatusBucket.builder() + .status(dto.getStatus().name()) + .count(dto.getCount()) + .build()) + .collect(Collectors.toList()); + + // Progress distribution — coalesce to max across sources, then bucket + List progressRows = userBookProgressRepository.findAllProgressPercentsByUser(userId); + long[] bucketCounts = new long[6]; // Not Started, Just Started, Getting Into It, Halfway Through, Almost Done, Completed + + for (ProgressPercentDto row : progressRows) { + float maxPercent = maxProgress(row); + int pct = Math.round(maxPercent * 100); + if (pct <= 0) bucketCounts[0]++; + else if (pct <= 25) bucketCounts[1]++; + else if (pct <= 50) bucketCounts[2]++; + else if (pct <= 75) bucketCounts[3]++; + else if (pct < 100) bucketCounts[4]++; + else bucketCounts[5]++; + } + + String[][] bucketDefs = { + {"Not Started", "0", "0"}, + {"Just Started", "1", "25"}, + {"Getting Into It", "26", "50"}, + {"Halfway Through", "51", "75"}, + {"Almost Done", "76", "99"}, + {"Completed", "100", "100"} + }; + + List progressBuckets = new ArrayList<>(); + for (int i = 0; i < 6; i++) { + progressBuckets.add(BookDistributionsResponse.ProgressBucket.builder() + .range(bucketDefs[i][0]) + .min(Integer.parseInt(bucketDefs[i][1])) + .max(Integer.parseInt(bucketDefs[i][2])) + .count(bucketCounts[i]) + .build()); + } + + return BookDistributionsResponse.builder() + .ratingDistribution(ratingBuckets) + .progressDistribution(progressBuckets) + .statusDistribution(statusBuckets) + .build(); + } + + private float maxProgress(ProgressPercentDto row) { + float max = 0f; + if (row.getKoreaderProgressPercent() != null) max = Math.max(max, row.getKoreaderProgressPercent()); + if (row.getKoboProgressPercent() != null) max = Math.max(max, row.getKoboProgressPercent()); + if (row.getEpubProgressPercent() != null) max = Math.max(max, row.getEpubProgressPercent()); + if (row.getPdfProgressPercent() != null) max = Math.max(max, row.getPdfProgressPercent()); + if (row.getCbxProgressPercent() != null) max = Math.max(max, row.getCbxProgressPercent()); + return max; + } + @Transactional(readOnly = true) public List getSessionScatter(int year) { BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); diff --git a/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorServiceIntegrationTest.java b/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorServiceIntegrationTest.java index 7f7101185..24d9a5688 100644 --- a/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorServiceIntegrationTest.java +++ b/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorServiceIntegrationTest.java @@ -1481,9 +1481,15 @@ class BookRuleEvaluatorServiceIntegrationTest { @Test void thisPeriod_week_matchesThisWeekBook() { - BookEntity yesterday = createBook("Yesterday Book"); - yesterday.setAddedOn(Instant.now().minus(1, ChronoUnit.DAYS)); - em.merge(yesterday); + // Use midweek (Wednesday) of the current week to avoid boundary issues on Monday + LocalDate thisWeekWednesday = LocalDate.now().with(java.time.temporal.TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY)).plusDays(2); + // If Wednesday is in the future (we're Mon/Tue), just use today + LocalDate safeDate = thisWeekWednesday.isAfter(LocalDate.now()) ? LocalDate.now() : thisWeekWednesday; + Instant thisWeekInstant = safeDate.atStartOfDay(java.time.ZoneId.systemDefault()).toInstant().plus(12, ChronoUnit.HOURS); + + BookEntity thisWeekBook = createBook("This Week Book"); + thisWeekBook.setAddedOn(thisWeekInstant); + em.merge(thisWeekBook); BookEntity twoWeeksAgo = createBook("Two Weeks Ago Book"); twoWeeksAgo.setAddedOn(Instant.now().minus(14, ChronoUnit.DAYS)); @@ -1492,7 +1498,7 @@ class BookRuleEvaluatorServiceIntegrationTest { em.clear(); List ids = findMatchingIds(singleRule(RuleField.ADDED_ON, RuleOperator.THIS_PERIOD, "week")); - assertThat(ids).contains(yesterday.getId()); + assertThat(ids).contains(thisWeekBook.getId()); assertThat(ids).doesNotContain(twoWeeksAgo.getId()); } }