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 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -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<BookDistributionsResponse> 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"),
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package org.booklore.model.dto;
|
||||
|
||||
public interface ProgressPercentDto {
|
||||
Float getKoreaderProgressPercent();
|
||||
Float getKoboProgressPercent();
|
||||
Float getEpubProgressPercent();
|
||||
Float getPdfProgressPercent();
|
||||
Float getCbxProgressPercent();
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.booklore.model.dto;
|
||||
|
||||
public interface RatingDistributionDto {
|
||||
Integer getRating();
|
||||
Long getCount();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.booklore.model.dto;
|
||||
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
|
||||
public interface StatusDistributionDto {
|
||||
ReadStatus getStatus();
|
||||
Long getCount();
|
||||
}
|
||||
+48
@@ -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<RatingBucket> ratingDistribution;
|
||||
private List<ProgressBucket> progressDistribution;
|
||||
private List<StatusBucket> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<UserBookProgre
|
||||
@Param("userId") Long userId,
|
||||
@Param("startYear") int startYear,
|
||||
@Param("endYear") int endYear);
|
||||
|
||||
@Query("""
|
||||
SELECT ubp.personalRating as rating, COUNT(ubp) as count
|
||||
FROM UserBookProgressEntity ubp
|
||||
WHERE ubp.user.id = :userId
|
||||
AND ubp.personalRating IS NOT NULL
|
||||
GROUP BY ubp.personalRating
|
||||
ORDER BY ubp.personalRating
|
||||
""")
|
||||
List<RatingDistributionDto> 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<StatusDistributionDto> 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<ProgressPercentDto> findAllProgressPercentsByUser(@Param("userId") Long userId);
|
||||
}
|
||||
|
||||
@@ -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<BookDistributionsResponse.RatingBucket> ratingBuckets = userBookProgressRepository.findRatingDistributionByUser(userId)
|
||||
.stream()
|
||||
.map(dto -> BookDistributionsResponse.RatingBucket.builder()
|
||||
.rating(dto.getRating())
|
||||
.count(dto.getCount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Status distribution
|
||||
List<BookDistributionsResponse.StatusBucket> 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<ProgressPercentDto> 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<BookDistributionsResponse.ProgressBucket> 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<SessionScatterResponse> getSessionScatter(int year) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
|
||||
+10
-4
@@ -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<Long> 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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user