diff --git a/backend/src/main/java/org/booklore/app/service/AppBookService.java b/backend/src/main/java/org/booklore/app/service/AppBookService.java index 9e00c0867..215297150 100644 --- a/backend/src/main/java/org/booklore/app/service/AppBookService.java +++ b/backend/src/main/java/org/booklore/app/service/AppBookService.java @@ -1044,6 +1044,11 @@ public class AppBookService { } } + // For `lastReadTime` sorting we need to filter to only the current user's progress. + if ("lastreadtime".equalsIgnoreCase(req.sort())) { + specs.add(AppBookSpecification.withProgress(userId, true)); + } + return AppBookSpecification.combine(specs.toArray(new Specification[0])); } @@ -1061,7 +1066,7 @@ public class AppBookService { case "publisher" -> "metadata.publisher"; case "language" -> "metadata.language"; case "publisheddate" -> "metadata.publishedDate"; - case "lastreadtime" -> "lastReadTime"; + case "lastreadtime" -> "userBookProgress.lastReadTime"; case "pagecount" -> "metadata.pageCount"; default -> "addedOn"; }; diff --git a/backend/src/main/java/org/booklore/app/specification/AppBookSpecification.java b/backend/src/main/java/org/booklore/app/specification/AppBookSpecification.java index 5c308846f..2d680fc5a 100644 --- a/backend/src/main/java/org/booklore/app/specification/AppBookSpecification.java +++ b/backend/src/main/java/org/booklore/app/specification/AppBookSpecification.java @@ -131,6 +131,28 @@ public class AppBookSpecification { }; } + /** + * Filter books that have any progress for a specific user. + * If `optional` is true, allow books without user progress to be included + * but omit other user's progress. + */ + public static Specification withProgress(Long userId, boolean optional) { + return (root, query, cb) -> { + if (userId == null) { + return cb.conjunction(); + } + + Join progressJoin = root.join("userBookProgress", JoinType.LEFT); + progressJoin = progressJoin.on(cb.equal(progressJoin.get("user").get("id"), userId)); + + if (optional) { + return cb.conjunction(); + } + + return cb.equal(progressJoin.get("user").get("id"), userId); + }; + } + public static Specification addedWithinDays(int days) { return (root, query, cb) -> { Instant cutoff = Instant.now().minus(days, ChronoUnit.DAYS);