feat(filters): add age rating and content rating filters, improve filter options (#479)
* feat(filters): add age rating and content rating filters, improve filter options * fix(book-browser): update view mode handling to use reactive properties * fix(book-browser): update view mode handling to use getter methods * feat(filters): improve filtering capabilities with comic creators and validate input values * test(filters): fix AppBookServiceFilterOptionsTest with additional query mocks * fix(filters): improve error handling for invalid filter bucket IDs and roles * refactor(book-browser): remove unused computedFilterLabel * fix(filters): validate shelfStatus values and throw error for invalid inputs * test(book-browser): mock TranslocoService for language changes in tests * fix(book-browser): ensure active language is set before syncing browser state
This commit is contained in:
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@@ -31,4 +32,12 @@ public class AppBookSummary {
|
||||
private Instant coverUpdatedOn;
|
||||
private Instant audiobookCoverUpdatedOn;
|
||||
private Boolean isPhysical;
|
||||
|
||||
// Metadata for filtering
|
||||
private LocalDate publishedDate;
|
||||
private Integer pageCount;
|
||||
private Integer ageRating;
|
||||
private String contentRating;
|
||||
private Float metadataMatchScore;
|
||||
private Long fileSizeKb;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,24 @@ public record AppFilterOptions(
|
||||
List<CountedOption> series,
|
||||
List<CountedOption> tags,
|
||||
List<CountedOption> moods,
|
||||
List<CountedOption> narrators) {
|
||||
List<CountedOption> narrators,
|
||||
List<CountedOption> ageRatings,
|
||||
List<CountedOption> contentRatings,
|
||||
List<CountedOption> matchScores,
|
||||
List<CountedOption> publishedYears,
|
||||
List<CountedOption> fileSizes,
|
||||
List<CountedOption> personalRatings,
|
||||
List<CountedOption> amazonRatings,
|
||||
List<CountedOption> goodreadsRatings,
|
||||
List<CountedOption> hardcoverRatings,
|
||||
List<CountedOption> pageCounts,
|
||||
List<CountedOption> shelfStatuses,
|
||||
List<CountedOption> comicCharacters,
|
||||
List<CountedOption> comicTeams,
|
||||
List<CountedOption> comicLocations,
|
||||
List<CountedOption> comicCreators,
|
||||
List<CountedOption> shelves,
|
||||
List<CountedOption> libraries) {
|
||||
|
||||
public record LanguageOption(String code, String label, long count) {}
|
||||
|
||||
|
||||
@@ -24,6 +24,23 @@ public record BookListRequest(
|
||||
@Size(max = 20) List<String> tag,
|
||||
@Size(max = 20) List<String> mood,
|
||||
@Size(max = 20) List<String> narrator,
|
||||
@Size(max = 20) List<String> ageRating,
|
||||
@Size(max = 20) List<String> contentRating,
|
||||
@Size(max = 20) List<String> matchScore,
|
||||
@Size(max = 20) List<String> publishedDate,
|
||||
@Size(max = 20) List<String> fileSize,
|
||||
@Size(max = 20) List<String> personalRating,
|
||||
@Size(max = 20) List<String> amazonRating,
|
||||
@Size(max = 20) List<String> goodreadsRating,
|
||||
@Size(max = 20) List<String> hardcoverRating,
|
||||
@Size(max = 20) List<String> pageCount,
|
||||
@Size(max = 20) List<String> shelfStatus,
|
||||
@Size(max = 20) List<String> comicCharacter,
|
||||
@Size(max = 20) List<String> comicTeam,
|
||||
@Size(max = 20) List<String> comicLocation,
|
||||
@Size(max = 20) List<String> comicCreator,
|
||||
@Size(max = 20) List<String> shelves,
|
||||
@Size(max = 20) List<String> libraries,
|
||||
Long magicShelfId,
|
||||
Boolean unshelved,
|
||||
String filterMode) {
|
||||
|
||||
@@ -35,6 +35,12 @@ public interface AppBookMapper {
|
||||
@Mapping(target = "coverUpdatedOn", source = "book.metadata.coverUpdatedOn")
|
||||
@Mapping(target = "audiobookCoverUpdatedOn", source = "book.metadata.audiobookCoverUpdatedOn")
|
||||
@Mapping(target = "isPhysical", source = "book.isPhysical")
|
||||
@Mapping(target = "publishedDate", source = "book.metadata.publishedDate")
|
||||
@Mapping(target = "pageCount", source = "book.metadata.pageCount")
|
||||
@Mapping(target = "ageRating", source = "book.metadata.ageRating")
|
||||
@Mapping(target = "contentRating", source = "book.metadata.contentRating")
|
||||
@Mapping(target = "metadataMatchScore", source = "book.metadataMatchScore")
|
||||
@Mapping(target = "fileSizeKb", source = "book", qualifiedByName = "mapFileSizeKb")
|
||||
AppBookSummary toSummary(BookEntity book, UserBookProgressEntity progress);
|
||||
|
||||
@Mapping(target = "id", source = "book.id")
|
||||
@@ -116,6 +122,13 @@ public interface AppBookMapper {
|
||||
return "/api/books/" + book.getId() + "/cover";
|
||||
}
|
||||
|
||||
@Named("mapFileSizeKb")
|
||||
default Long mapFileSizeKb(BookEntity book) {
|
||||
if (book == null) return null;
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
return primaryFile != null ? primaryFile.getFileSizeKb() : null;
|
||||
}
|
||||
|
||||
@Named("mapShelves")
|
||||
default List<AppShelfSummary> mapShelves(Set<ShelfEntity> shelves) {
|
||||
if (shelves == null || shelves.isEmpty()) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.dto.request.ReadProgressRequest;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.ComicCreatorRole;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.ShelfRepository;
|
||||
@@ -401,52 +402,45 @@ public class AppBookService {
|
||||
}
|
||||
}
|
||||
|
||||
// Cache lookup avoid re-running 9 aggregate queries within the TTL window
|
||||
// Cache lookup avoid re-running 26+ aggregate queries within the TTL window
|
||||
String cacheKey = userId + ":" + libraryId + ":" + shelfId + ":" + magicShelfId;
|
||||
AppFilterOptions cached = filterOptionsCache.getIfPresent(cacheKey);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// Build unified scoping Specification for all aggregate queries
|
||||
Specification<BookEntity> baseSpec = buildBaseSpecification(accessibleLibraryIds, libraryId);
|
||||
Specification<BookEntity> magicShelfSpec = null;
|
||||
if (magicShelfId != null) {
|
||||
magicShelfSpec = magicShelfBookService.toSpecification(userId, magicShelfId);
|
||||
baseSpec = baseSpec.and(magicShelfSpec);
|
||||
}
|
||||
if (shelfId != null) {
|
||||
baseSpec = baseSpec.and(AppBookSpecification.inShelf(shelfId));
|
||||
}
|
||||
|
||||
Set<Long> magicBookIds = null;
|
||||
if (magicShelfId != null) {
|
||||
magicBookIds = resolveMagicShelfBookIds(magicShelfId, userId);
|
||||
magicBookIds = resolveMagicShelfBookIds(magicShelfSpec);
|
||||
if (magicBookIds.isEmpty()) {
|
||||
AppFilterOptions empty = AppFilterOptions.builder()
|
||||
.authors(Collections.emptyList())
|
||||
.languages(Collections.emptyList())
|
||||
.fileTypes(Collections.emptyList())
|
||||
.readStatuses(Collections.emptyList())
|
||||
.categories(Collections.emptyList())
|
||||
.publishers(Collections.emptyList())
|
||||
.series(Collections.emptyList())
|
||||
.tags(Collections.emptyList())
|
||||
.moods(Collections.emptyList())
|
||||
.narrators(Collections.emptyList())
|
||||
.build();
|
||||
filterOptionsCache.put(cacheKey, empty);
|
||||
return empty;
|
||||
return emptyFilterOptions(cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
// Build scoping clauses
|
||||
String libraryClause = "";
|
||||
String shelfClause = "";
|
||||
String magicBookClause = "";
|
||||
|
||||
if (magicBookIds != null) {
|
||||
magicBookClause = "AND b.id IN :magicBookIds";
|
||||
} else if (shelfId != null) {
|
||||
shelfClause = "AND b.id IN (SELECT sb.id FROM ShelfEntity s JOIN s.bookEntities sb WHERE s.id = :shelfId)";
|
||||
}
|
||||
|
||||
if (libraryId != null) {
|
||||
libraryClause = "AND b.library.id = :libraryId";
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
libraryClause = "AND b.library.id IN :libraryIds";
|
||||
}
|
||||
|
||||
// Build the optional WHERE suffix once — each clause already starts with "AND"
|
||||
String scopeClause = buildScopeClause(libraryClause, shelfClause, magicBookClause);
|
||||
|
||||
List<AppFilterOptions.CountedOption> authors = queryCountedOptions(
|
||||
@@ -463,20 +457,9 @@ public class AppBookService {
|
||||
c.count()))
|
||||
.toList();
|
||||
|
||||
String fileTypeQuery = "SELECT bf.bookType, COUNT(DISTINCT b.id) FROM BookEntity b"
|
||||
+ " JOIN b.bookFiles bf"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ " AND bf.isBookFormat = true"
|
||||
+ scopeClause
|
||||
+ " GROUP BY bf.bookType ORDER BY COUNT(DISTINCT b.id) DESC";
|
||||
var ftQ = entityManager.createQuery(fileTypeQuery, Tuple.class);
|
||||
setFilterQueryParams(ftQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
List<AppFilterOptions.CountedOption> fileTypes = ftQ.getResultList().stream()
|
||||
.map(t -> new AppFilterOptions.CountedOption(
|
||||
t.get(0, BookFileType.class).name(),
|
||||
t.get(1, Long.class)))
|
||||
.toList();
|
||||
List<AppFilterOptions.CountedOption> fileTypes = queryCountedOptions(
|
||||
"bf.bookType", "JOIN b.bookFiles bf", "AND bf.isBookFormat = true",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> categories = queryCountedOptions(
|
||||
"c.name", "JOIN b.metadata m JOIN m.categories c", "",
|
||||
@@ -508,6 +491,131 @@ public class AppBookService {
|
||||
List<AppFilterOptions.CountedOption> readStatuses = queryReadStatusCounts(
|
||||
userId, scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> ageRatings = queryGroupedCount(
|
||||
"CASE " +
|
||||
" WHEN m.ageRating >= 0 AND m.ageRating < 6 THEN '0' " +
|
||||
" WHEN m.ageRating >= 6 AND m.ageRating < 10 THEN '6' " +
|
||||
" WHEN m.ageRating >= 10 AND m.ageRating < 13 THEN '10' " +
|
||||
" WHEN m.ageRating >= 13 AND m.ageRating < 16 THEN '13' " +
|
||||
" WHEN m.ageRating >= 16 AND m.ageRating < 18 THEN '16' " +
|
||||
" WHEN m.ageRating >= 18 AND m.ageRating < 21 THEN '18' " +
|
||||
" WHEN m.ageRating >= 21 THEN '21' " +
|
||||
"END",
|
||||
"JOIN b.metadata m", "AND m.ageRating IS NOT NULL",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> contentRatings = queryCountedOptions(
|
||||
"m.contentRating", "JOIN b.metadata m",
|
||||
"AND m.contentRating IS NOT NULL AND m.contentRating <> ''",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> matchScores = queryGroupedCount(
|
||||
"CASE " +
|
||||
" WHEN b.metadataMatchScore >= 0.95 THEN '0' " +
|
||||
" WHEN b.metadataMatchScore >= 0.90 THEN '1' " +
|
||||
" WHEN b.metadataMatchScore >= 0.80 THEN '2' " +
|
||||
" WHEN b.metadataMatchScore >= 0.70 THEN '3' " +
|
||||
" WHEN b.metadataMatchScore >= 0.50 THEN '4' " +
|
||||
" WHEN b.metadataMatchScore >= 0.30 THEN '5' " +
|
||||
" WHEN b.metadataMatchScore >= 0.00 THEN '6' " +
|
||||
"END",
|
||||
"", "AND b.metadataMatchScore IS NOT NULL",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> publishedYears = queryCountedOptions(
|
||||
"CAST(YEAR(m.publishedDate) AS string)", "JOIN b.metadata m",
|
||||
"AND m.publishedDate IS NOT NULL",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> fileSizes = queryGroupedCount(
|
||||
"CASE " +
|
||||
" WHEN bf.fileSizeKb < 1024 THEN '0' " +
|
||||
" WHEN bf.fileSizeKb < 10240 THEN '1' " +
|
||||
" WHEN bf.fileSizeKb < 51200 THEN '2' " +
|
||||
" WHEN bf.fileSizeKb < 102400 THEN '3' " +
|
||||
" WHEN bf.fileSizeKb < 512000 THEN '4' " +
|
||||
" WHEN bf.fileSizeKb < 1048576 THEN '5' " +
|
||||
" WHEN bf.fileSizeKb < 2097152 THEN '6' " +
|
||||
" ELSE '7' " +
|
||||
"END",
|
||||
"JOIN b.bookFiles bf", "AND bf.isBookFormat = true",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
String personalRatingQuery = "SELECT CAST(ubp.personalRating AS string), COUNT(DISTINCT ubp.book.id) " +
|
||||
"FROM UserBookProgressEntity ubp " +
|
||||
"WHERE ubp.user.id = :userId AND ubp.personalRating IS NOT NULL " +
|
||||
"AND ubp.book.id IN (SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) " +
|
||||
"AND b.bookFiles IS NOT EMPTY " +
|
||||
scopeClause + ") " +
|
||||
"GROUP BY 1 ORDER BY 1 DESC";
|
||||
var prQ = entityManager.createQuery(personalRatingQuery, Tuple.class);
|
||||
prQ.setParameter("userId", userId);
|
||||
setFilterQueryParams(prQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
List<AppFilterOptions.CountedOption> personalRatings = prQ.getResultList().stream()
|
||||
.map(t -> new AppFilterOptions.CountedOption(t.get(0, String.class), t.get(1, Long.class)))
|
||||
.toList();
|
||||
|
||||
List<AppFilterOptions.CountedOption> amazonRatings = queryRatingBuckets("m.amazonRating", scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
List<AppFilterOptions.CountedOption> goodreadsRatings = queryRatingBuckets("m.goodreadsRating", scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
List<AppFilterOptions.CountedOption> hardcoverRatings = queryRatingBuckets("m.hardcoverRating", scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> pageCounts = queryGroupedCount(
|
||||
"CASE " +
|
||||
" WHEN m.pageCount < 50 THEN '0' " +
|
||||
" WHEN m.pageCount < 100 THEN '1' " +
|
||||
" WHEN m.pageCount < 200 THEN '2' " +
|
||||
" WHEN m.pageCount < 400 THEN '3' " +
|
||||
" WHEN m.pageCount < 600 THEN '4' " +
|
||||
" WHEN m.pageCount < 1000 THEN '5' " +
|
||||
" ELSE '6' " +
|
||||
"END",
|
||||
"JOIN b.metadata m", "AND m.pageCount IS NOT NULL",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> shelfStatuses = queryGroupedCount(
|
||||
"CASE WHEN (SELECT COUNT(s) FROM b.shelves s) > 0 THEN 'shelved' ELSE 'unshelved' END",
|
||||
"", "",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> comicCharacters = queryCountedOptions(
|
||||
"c.name", "JOIN b.metadata m JOIN m.comicMetadata cm JOIN cm.characters c", "",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> comicTeams = queryCountedOptions(
|
||||
"t.name", "JOIN b.metadata m JOIN m.comicMetadata cm JOIN cm.teams t", "",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> comicLocations = queryCountedOptions(
|
||||
"l.name", "JOIN b.metadata m JOIN m.comicMetadata cm JOIN cm.locations l", "",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
// Comic Creators — uses creatorMappings join table with role enum
|
||||
String creatorJpql = "SELECT cr.name, mapping.role, COUNT(DISTINCT b.id) FROM BookEntity b"
|
||||
+ " JOIN b.metadata m JOIN m.comicMetadata cm JOIN cm.creatorMappings mapping JOIN mapping.creator cr"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ " " + scopeClause
|
||||
+ " GROUP BY cr.name, mapping.role ORDER BY COUNT(DISTINCT b.id) DESC";
|
||||
var creatorQ = entityManager.createQuery(creatorJpql, Tuple.class);
|
||||
setFilterQueryParams(creatorQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
creatorQ.setMaxResults(1000);
|
||||
List<AppFilterOptions.CountedOption> allCreators = creatorQ.getResultList().stream()
|
||||
.map(t -> {
|
||||
String name = t.get(0, String.class);
|
||||
ComicCreatorRole role = t.get(1, ComicCreatorRole.class);
|
||||
long count = t.get(2, Long.class);
|
||||
return new AppFilterOptions.CountedOption(name + ":" + creatorRoleLabel(role), count);
|
||||
})
|
||||
.toList();
|
||||
|
||||
List<AppFilterOptions.CountedOption> shelves = queryCountedOptions(
|
||||
"CAST(s.id AS string) || ':' || s.name", "JOIN b.shelves s", "",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
List<AppFilterOptions.CountedOption> libraries = queryCountedOptions(
|
||||
"CAST(l.id AS string) || ':' || l.name", "JOIN b.library l", "",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
|
||||
AppFilterOptions result = AppFilterOptions.builder()
|
||||
.authors(authors)
|
||||
.languages(languages)
|
||||
@@ -519,84 +627,60 @@ public class AppBookService {
|
||||
.tags(tags)
|
||||
.moods(moods)
|
||||
.narrators(narrators)
|
||||
.ageRatings(ageRatings)
|
||||
.contentRatings(contentRatings)
|
||||
.matchScores(matchScores)
|
||||
.publishedYears(publishedYears)
|
||||
.fileSizes(fileSizes)
|
||||
.personalRatings(personalRatings)
|
||||
.amazonRatings(amazonRatings)
|
||||
.goodreadsRatings(goodreadsRatings)
|
||||
.hardcoverRatings(hardcoverRatings)
|
||||
.pageCounts(pageCounts)
|
||||
.shelfStatuses(shelfStatuses)
|
||||
.comicCharacters(comicCharacters)
|
||||
.comicTeams(comicTeams)
|
||||
.comicLocations(comicLocations)
|
||||
.comicCreators(allCreators)
|
||||
.shelves(shelves)
|
||||
.libraries(libraries)
|
||||
.build();
|
||||
filterOptionsCache.put(cacheKey, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<AppFilterOptions.CountedOption> queryCountedOptions(
|
||||
String selectExpr, String joins, String extraWhere,
|
||||
String scopeClause, Set<Long> accessibleLibraryIds,
|
||||
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||
String jpql = "SELECT " + selectExpr + ", COUNT(DISTINCT b.id) FROM BookEntity b"
|
||||
+ " " + joins
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ (extraWhere.isEmpty() ? "" : " " + extraWhere)
|
||||
+ scopeClause
|
||||
+ " GROUP BY " + selectExpr + " ORDER BY COUNT(DISTINCT b.id) DESC";
|
||||
var q = entityManager.createQuery(jpql, Tuple.class);
|
||||
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
q.setMaxResults(200);
|
||||
return q.getResultList().stream()
|
||||
.map(t -> new AppFilterOptions.CountedOption(t.get(0, String.class), t.get(1, Long.class)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private String buildScopeClause(String libraryClause, String shelfClause, String magicBookClause) {
|
||||
var sb = new StringBuilder();
|
||||
if (!libraryClause.isEmpty()) sb.append(" ").append(libraryClause);
|
||||
if (!shelfClause.isEmpty()) sb.append(" ").append(shelfClause);
|
||||
if (!magicBookClause.isEmpty()) sb.append(" ").append(magicBookClause);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void setFilterQueryParams(jakarta.persistence.Query query, Set<Long> accessibleLibraryIds, Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||
if (libraryId != null) {
|
||||
query.setParameter("libraryId", libraryId);
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
query.setParameter("libraryIds", accessibleLibraryIds);
|
||||
}
|
||||
if (shelfId != null && magicBookIds == null) {
|
||||
query.setParameter("shelfId", shelfId);
|
||||
}
|
||||
if (magicBookIds != null) {
|
||||
query.setParameter("magicBookIds", magicBookIds);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> resolveMagicShelfBookIds(Long magicShelfId, Long userId) {
|
||||
Specification<BookEntity> spec = magicShelfBookService.toSpecification(userId, magicShelfId);
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<BookEntity> root = cq.from(BookEntity.class);
|
||||
cq.select(root.get("id"));
|
||||
cq.where(spec.toPredicate(root, cq, cb));
|
||||
return new HashSet<>(entityManager.createQuery(cq)
|
||||
.getResultList());
|
||||
}
|
||||
|
||||
private List<AppFilterOptions.CountedOption> queryReadStatusCounts(
|
||||
Long userId, String scopeClause, Set<Long> accessibleLibraryIds,
|
||||
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||
String jpql = "SELECT ubp.readStatus, COUNT(DISTINCT ubp.book.id) FROM UserBookProgressEntity ubp"
|
||||
+ " WHERE ubp.user.id = :userId"
|
||||
+ " AND ubp.readStatus <> org.booklore.model.enums.ReadStatus.UNSET"
|
||||
+ " AND ubp.book.id IN ("
|
||||
+ " SELECT b.id FROM BookEntity b"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ scopeClause
|
||||
+ " )"
|
||||
+ " GROUP BY ubp.readStatus ORDER BY COUNT(DISTINCT ubp.book.id) DESC";
|
||||
var q = entityManager.createQuery(jpql, Tuple.class);
|
||||
q.setParameter("userId", userId);
|
||||
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
return q.getResultList().stream()
|
||||
.map(t -> new AppFilterOptions.CountedOption(
|
||||
t.get(0, ReadStatus.class).name(),
|
||||
t.get(1, Long.class)))
|
||||
.toList();
|
||||
private AppFilterOptions emptyFilterOptions(String cacheKey) {
|
||||
AppFilterOptions empty = AppFilterOptions.builder()
|
||||
.authors(Collections.emptyList())
|
||||
.languages(Collections.emptyList())
|
||||
.fileTypes(Collections.emptyList())
|
||||
.readStatuses(Collections.emptyList())
|
||||
.categories(Collections.emptyList())
|
||||
.publishers(Collections.emptyList())
|
||||
.series(Collections.emptyList())
|
||||
.tags(Collections.emptyList())
|
||||
.moods(Collections.emptyList())
|
||||
.narrators(Collections.emptyList())
|
||||
.ageRatings(Collections.emptyList())
|
||||
.contentRatings(Collections.emptyList())
|
||||
.matchScores(Collections.emptyList())
|
||||
.publishedYears(Collections.emptyList())
|
||||
.fileSizes(Collections.emptyList())
|
||||
.personalRatings(Collections.emptyList())
|
||||
.amazonRatings(Collections.emptyList())
|
||||
.goodreadsRatings(Collections.emptyList())
|
||||
.hardcoverRatings(Collections.emptyList())
|
||||
.pageCounts(Collections.emptyList())
|
||||
.shelfStatuses(Collections.emptyList())
|
||||
.comicCharacters(Collections.emptyList())
|
||||
.comicTeams(Collections.emptyList())
|
||||
.comicLocations(Collections.emptyList())
|
||||
.comicCreators(Collections.emptyList())
|
||||
.shelves(Collections.emptyList())
|
||||
.libraries(Collections.emptyList())
|
||||
.build();
|
||||
filterOptionsCache.put(cacheKey, empty);
|
||||
return empty;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -784,6 +868,125 @@ public class AppBookService {
|
||||
}
|
||||
}
|
||||
|
||||
if (req.ageRating() != null && !req.ageRating().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.ageRating());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withAgeRatings(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.contentRating() != null && !req.contentRating().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.contentRating());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withContentRatings(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.matchScore() != null && !req.matchScore().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.matchScore());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withMatchScores(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.publishedDate() != null && !req.publishedDate().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.publishedDate());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withPublishedYears(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.fileSize() != null && !req.fileSize().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.fileSize());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withFileSizes(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.personalRating() != null && !req.personalRating().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.personalRating());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withPersonalRatings(cleaned, userId, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.amazonRating() != null && !req.amazonRating().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.amazonRating());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withAmazonRatings(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.goodreadsRating() != null && !req.goodreadsRating().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.goodreadsRating());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withGoodreadsRatings(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.hardcoverRating() != null && !req.hardcoverRating().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.hardcoverRating());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withHardcoverRatings(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.pageCount() != null && !req.pageCount().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.pageCount());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withPageCounts(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.shelfStatus() != null && !req.shelfStatus().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.shelfStatus());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withShelfStatus(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.comicCharacter() != null && !req.comicCharacter().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.comicCharacter());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withComicCharacters(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.comicTeam() != null && !req.comicTeam().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.comicTeam());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withComicTeams(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.comicLocation() != null && !req.comicLocation().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.comicLocation());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withComicLocations(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.comicCreator() != null && !req.comicCreator().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.comicCreator());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.withComicCreators(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.shelves() != null && !req.shelves().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.shelves());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.inShelves(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
if (req.libraries() != null && !req.libraries().isEmpty()) {
|
||||
List<String> cleaned = BookListRequest.cleanValues(req.libraries());
|
||||
if (!cleaned.isEmpty()) {
|
||||
specs.add(AppBookSpecification.inLibraries(cleaned, req.effectiveFilterMode()));
|
||||
}
|
||||
}
|
||||
|
||||
return AppBookSpecification.combine(specs.toArray(new Specification[0]));
|
||||
}
|
||||
|
||||
@@ -866,4 +1069,146 @@ public class AppBookService {
|
||||
.collect(Collectors.toSet());
|
||||
return getProgressMap(userId, bookIds);
|
||||
}
|
||||
|
||||
private List<AppFilterOptions.CountedOption> queryCountedOptions(
|
||||
String selectExpr, String joins, String extraWhere,
|
||||
String scopeClause, Set<Long> accessibleLibraryIds,
|
||||
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||
String jpql = "SELECT " + selectExpr + ", COUNT(DISTINCT b.id) FROM BookEntity b"
|
||||
+ " " + joins
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ (extraWhere.isEmpty() ? "" : " " + extraWhere)
|
||||
+ " " + scopeClause
|
||||
+ " GROUP BY " + selectExpr + " ORDER BY COUNT(DISTINCT b.id) DESC";
|
||||
var q = entityManager.createQuery(jpql, Tuple.class);
|
||||
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
q.setMaxResults(1000);
|
||||
return q.getResultList().stream()
|
||||
.map(this::mapToCountedOption)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private String buildScopeClause(String libraryClause, String shelfClause, String magicBookClause) {
|
||||
var sb = new StringBuilder();
|
||||
if (!libraryClause.isEmpty()) sb.append(" ").append(libraryClause);
|
||||
if (!shelfClause.isEmpty()) sb.append(" ").append(shelfClause);
|
||||
if (!magicBookClause.isEmpty()) sb.append(" ").append(magicBookClause);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void setFilterQueryParams(jakarta.persistence.Query query, Set<Long> accessibleLibraryIds, Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||
if (libraryId != null) {
|
||||
query.setParameter("libraryId", libraryId);
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
query.setParameter("libraryIds", accessibleLibraryIds);
|
||||
}
|
||||
if (shelfId != null && magicBookIds == null) {
|
||||
query.setParameter("shelfId", shelfId);
|
||||
}
|
||||
if (magicBookIds != null) {
|
||||
query.setParameter("magicBookIds", magicBookIds);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> resolveMagicShelfBookIds(Specification<BookEntity> spec) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<BookEntity> root = cq.from(BookEntity.class);
|
||||
cq.select(root.get("id"));
|
||||
cq.where(spec.toPredicate(root, cq, cb));
|
||||
return new HashSet<>(entityManager.createQuery(cq)
|
||||
.getResultList());
|
||||
}
|
||||
|
||||
private List<AppFilterOptions.CountedOption> queryReadStatusCounts(
|
||||
Long userId, String scopeClause, Set<Long> accessibleLibraryIds,
|
||||
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||
String jpql = "SELECT ubp.readStatus, COUNT(DISTINCT ubp.book.id) FROM UserBookProgressEntity ubp"
|
||||
+ " WHERE ubp.user.id = :userId"
|
||||
+ " AND ubp.readStatus <> org.booklore.model.enums.ReadStatus.UNSET"
|
||||
+ " AND ubp.book.id IN ("
|
||||
+ " SELECT b.id FROM BookEntity b"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ " " + scopeClause
|
||||
+ " )"
|
||||
+ " GROUP BY ubp.readStatus ORDER BY COUNT(DISTINCT ubp.book.id) DESC";
|
||||
var q = entityManager.createQuery(jpql, Tuple.class);
|
||||
q.setParameter("userId", userId);
|
||||
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
List<AppFilterOptions.CountedOption> options = q.getResultList().stream()
|
||||
.map(t -> new AppFilterOptions.CountedOption(
|
||||
t.get(0, ReadStatus.class).name(),
|
||||
t.get(1, Long.class)))
|
||||
.toList();
|
||||
|
||||
String baseQuery = "SELECT COUNT(DISTINCT b.id) FROM BookEntity b"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ " AND b.id NOT IN ("
|
||||
+ " SELECT ubp.book.id FROM UserBookProgressEntity ubp WHERE ubp.user.id = :userId"
|
||||
+ " )"
|
||||
+ " " + scopeClause;
|
||||
var baseQ = entityManager.createQuery(baseQuery, Long.class);
|
||||
baseQ.setParameter("userId", userId);
|
||||
setFilterQueryParams(baseQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
long unsetCount = baseQ.getSingleResult();
|
||||
|
||||
if (unsetCount > 0) {
|
||||
List<AppFilterOptions.CountedOption> mutable = new ArrayList<>(options);
|
||||
mutable.addFirst(new AppFilterOptions.CountedOption("UNSET", unsetCount));
|
||||
return List.copyOf(mutable);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
private List<AppFilterOptions.CountedOption> queryRatingBuckets(
|
||||
String ratingExpr, String scopeClause, Set<Long> accessibleLibraryIds,
|
||||
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||
return queryGroupedCount(
|
||||
"CASE " +
|
||||
" WHEN " + ratingExpr + " >= 4.5 THEN '5' " +
|
||||
" WHEN " + ratingExpr + " >= 4.0 THEN '4' " +
|
||||
" WHEN " + ratingExpr + " >= 3.0 THEN '3' " +
|
||||
" WHEN " + ratingExpr + " >= 2.0 THEN '2' " +
|
||||
" WHEN " + ratingExpr + " >= 1.0 THEN '1' " +
|
||||
" ELSE '0' " +
|
||||
"END",
|
||||
"JOIN b.metadata m", "AND " + ratingExpr + " IS NOT NULL",
|
||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
}
|
||||
|
||||
private List<AppFilterOptions.CountedOption> queryGroupedCount(
|
||||
String caseExpr, String joins, String extraWhere,
|
||||
String scopeClause, Set<Long> accessibleLibraryIds,
|
||||
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||
String jpql = "SELECT " + caseExpr + ", COUNT(DISTINCT b.id) FROM BookEntity b " + joins +
|
||||
" WHERE (b.deleted IS NULL OR b.deleted = false) AND b.bookFiles IS NOT EMPTY "
|
||||
+ extraWhere + " " + scopeClause +
|
||||
" GROUP BY 1";
|
||||
var q = entityManager.createQuery(jpql, Tuple.class);
|
||||
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||
return q.getResultList().stream()
|
||||
.filter(t -> t.get(0) != null)
|
||||
.map(this::mapToCountedOption)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private AppFilterOptions.CountedOption mapToCountedOption(Tuple t) {
|
||||
Object val = t.get(0);
|
||||
String name = val instanceof Enum<?> e ? e.name() : val != null ? String.valueOf(val) : null;
|
||||
return new AppFilterOptions.CountedOption(name, t.get(1, Long.class));
|
||||
}
|
||||
|
||||
private static String creatorRoleLabel(ComicCreatorRole role) {
|
||||
return switch (role) {
|
||||
case PENCILLER -> "penciller";
|
||||
case INKER -> "inker";
|
||||
case COLORIST -> "colorist";
|
||||
case LETTERER -> "letterer";
|
||||
case COVER_ARTIST -> "coverArtist";
|
||||
case EDITOR -> "editor";
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+403
-4
@@ -3,6 +3,7 @@ package org.booklore.app.specification;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.ComicCreatorRole;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import jakarta.persistence.criteria.*;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
@@ -20,6 +21,46 @@ public class AppBookSpecification {
|
||||
private AppBookSpecification() {
|
||||
}
|
||||
|
||||
private static List<Integer> parseIntList(List<String> values, String paramName) {
|
||||
List<String> invalid = new ArrayList<>();
|
||||
List<Integer> result = values.stream()
|
||||
.filter(s -> s != null && !s.isBlank())
|
||||
.map(s -> {
|
||||
try {
|
||||
return Integer.parseInt(s.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
invalid.add(s.trim());
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
if (!invalid.isEmpty()) {
|
||||
throw new APIException("Invalid " + paramName + " values: " + invalid, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static List<Long> parseLongList(List<String> values, String paramName) {
|
||||
List<String> invalid = new ArrayList<>();
|
||||
List<Long> result = values.stream()
|
||||
.filter(s -> s != null && !s.isBlank())
|
||||
.map(s -> {
|
||||
try {
|
||||
return Long.parseLong(s.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
invalid.add(s.trim());
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
if (!invalid.isEmpty()) {
|
||||
throw new APIException("Invalid " + paramName + " values: " + invalid, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <X, Y> Join<X, Y> getOrCreateJoin(From<?, X> from, String attribute, JoinType joinType) {
|
||||
for (Join<X, ?> join : from.getJoins()) {
|
||||
@@ -254,18 +295,48 @@ public class AppBookSpecification {
|
||||
}
|
||||
if (parsed.isEmpty()) return cb.conjunction();
|
||||
|
||||
boolean hasUnset = parsed.contains(ReadStatus.UNSET);
|
||||
List<ReadStatus> realStatuses = parsed.stream().filter(s -> s != ReadStatus.UNSET).toList();
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progressRoot = sub.from(UserBookProgressEntity.class);
|
||||
sub.select(progressRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||
progressRoot.get("readStatus").in(parsed)
|
||||
realStatuses.isEmpty() ? cb.disjunction() : progressRoot.get("readStatus").in(realStatuses)
|
||||
);
|
||||
|
||||
if ("not".equals(mode)) {
|
||||
return cb.not(root.get("id").in(sub));
|
||||
Predicate isReal = root.get("id").in(sub);
|
||||
|
||||
// UNSET means either no progress entry OR entry with UNSET status
|
||||
Subquery<Long> anyEntrySub = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> anyEntryRoot = anyEntrySub.from(UserBookProgressEntity.class);
|
||||
anyEntrySub.select(anyEntryRoot.get("book").get("id"))
|
||||
.where(cb.equal(anyEntryRoot.get("user").get("id"), userId));
|
||||
|
||||
Predicate noEntry = cb.not(root.get("id").in(anyEntrySub));
|
||||
|
||||
Subquery<Long> unsetEntrySub = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> unsetEntryRoot = unsetEntrySub.from(UserBookProgressEntity.class);
|
||||
unsetEntrySub.select(unsetEntryRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(unsetEntryRoot.get("user").get("id"), userId),
|
||||
cb.equal(unsetEntryRoot.get("readStatus"), ReadStatus.UNSET)
|
||||
);
|
||||
Predicate hasUnsetEntry = root.get("id").in(unsetEntrySub);
|
||||
|
||||
Predicate isUnset = cb.or(noEntry, hasUnsetEntry);
|
||||
|
||||
Predicate combined;
|
||||
if (hasUnset && !realStatuses.isEmpty()) {
|
||||
combined = cb.or(isReal, isUnset);
|
||||
} else if (hasUnset) {
|
||||
combined = isUnset;
|
||||
} else {
|
||||
combined = isReal;
|
||||
}
|
||||
return root.get("id").in(sub);
|
||||
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -465,6 +536,334 @@ public class AppBookSpecification {
|
||||
return cb.not(cb.exists(subquery));
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withAgeRatings(List<String> rangeIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, "ageRating");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<Integer> ageRating = metadataJoin.get("ageRating");
|
||||
|
||||
// Age rating ranges from frontend config (mirrored here for performance)
|
||||
// 0: [0, 6), 6: [6, 10), 10: [10, 13), 13: [13, 16), 16: [16, 18), 18: [18, 21), 21: [21, inf)
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 0 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 0), cb.lessThan(ageRating, 6));
|
||||
case 6 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 6), cb.lessThan(ageRating, 10));
|
||||
case 10 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 10), cb.lessThan(ageRating, 13));
|
||||
case 13 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 13), cb.lessThan(ageRating, 16));
|
||||
case 16 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 16), cb.lessThan(ageRating, 18));
|
||||
case 18 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 18), cb.lessThan(ageRating, 21));
|
||||
case 21 -> cb.greaterThanOrEqualTo(ageRating, 21);
|
||||
default -> throw new APIException("Invalid ageRating bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withContentRatings(List<String> values, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(values);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "contentRating");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withMatchScores(List<String> rangeIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, "matchScore");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
Expression<Float> score = root.get("metadataMatchScore");
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 0 -> cb.greaterThanOrEqualTo(score, 0.95f);
|
||||
case 1 -> cb.and(cb.greaterThanOrEqualTo(score, 0.90f), cb.lessThan(score, 0.95f));
|
||||
case 2 -> cb.and(cb.greaterThanOrEqualTo(score, 0.80f), cb.lessThan(score, 0.90f));
|
||||
case 3 -> cb.and(cb.greaterThanOrEqualTo(score, 0.70f), cb.lessThan(score, 0.80f));
|
||||
case 4 -> cb.and(cb.greaterThanOrEqualTo(score, 0.50f), cb.lessThan(score, 0.70f));
|
||||
case 5 -> cb.and(cb.greaterThanOrEqualTo(score, 0.30f), cb.lessThan(score, 0.50f));
|
||||
case 6 -> cb.and(cb.greaterThanOrEqualTo(score, 0.00f), cb.lessThan(score, 0.30f));
|
||||
default -> throw new APIException("Invalid matchScore bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withPublishedYears(List<String> years, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (years.isEmpty()) return cb.conjunction();
|
||||
List<Integer> parsedYears = parseIntList(years, "publishedDate");
|
||||
if (parsedYears.isEmpty()) return cb.conjunction();
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<Integer> yearExpr = cb.function("YEAR", Integer.class, metadataJoin.get("publishedDate"));
|
||||
Predicate combined = yearExpr.in(parsedYears);
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withFileSizes(List<String> rangeIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, "fileSize");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.correlate(root);
|
||||
Join<BookEntity, BookFileEntity> bfJoin = subRoot.join("bookFiles", JoinType.INNER);
|
||||
|
||||
Subquery<Long> minIdSub = query.subquery(Long.class);
|
||||
Root<BookEntity> minIdRoot = minIdSub.correlate(root);
|
||||
Join<BookEntity, BookFileEntity> minIdJoin = minIdRoot.join("bookFiles", JoinType.INNER);
|
||||
minIdSub.select(cb.min(minIdJoin.get("id")))
|
||||
.where(cb.equal(minIdJoin.get("isBookFormat"), true));
|
||||
|
||||
Expression<Long> size = bfJoin.get("fileSizeKb");
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 0 -> cb.and(cb.greaterThanOrEqualTo(size, 0L), cb.lessThan(size, 1024L));
|
||||
case 1 -> cb.and(cb.greaterThanOrEqualTo(size, 1024L), cb.lessThan(size, 10240L));
|
||||
case 2 -> cb.and(cb.greaterThanOrEqualTo(size, 10240L), cb.lessThan(size, 51200L));
|
||||
case 3 -> cb.and(cb.greaterThanOrEqualTo(size, 51200L), cb.lessThan(size, 102400L));
|
||||
case 4 -> cb.and(cb.greaterThanOrEqualTo(size, 102400L), cb.lessThan(size, 512000L));
|
||||
case 5 -> cb.and(cb.greaterThanOrEqualTo(size, 512000L), cb.lessThan(size, 1048576L));
|
||||
case 6 -> cb.and(cb.greaterThanOrEqualTo(size, 1048576L), cb.lessThan(size, 2097152L));
|
||||
case 7 -> cb.greaterThanOrEqualTo(size, 2097152L);
|
||||
default -> throw new APIException("Invalid fileSize bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
|
||||
sub.select(cb.literal(1L))
|
||||
.where(cb.equal(bfJoin.get("id"), minIdSub),
|
||||
cb.or(predicates.toArray(new Predicate[0])));
|
||||
|
||||
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withPersonalRatings(List<String> values, Long userId, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (userId == null || values.isEmpty()) return cb.conjunction();
|
||||
List<Integer> parsed = parseIntList(values, "personalRating");
|
||||
if (parsed.isEmpty()) return cb.conjunction();
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progressRoot = sub.from(UserBookProgressEntity.class);
|
||||
sub.select(progressRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||
progressRoot.get("personalRating").in(parsed)
|
||||
);
|
||||
return "not".equals(mode) ? cb.not(root.get("id").in(sub)) : root.get("id").in(sub);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withAmazonRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "amazonRating");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withGoodreadsRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "goodreadsRating");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withHardcoverRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "hardcoverRating");
|
||||
}
|
||||
|
||||
private static Specification<BookEntity> buildRatingRangeSpec(
|
||||
List<String> rangeIds, String mode, String fieldName) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, fieldName);
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<Double> rating = metadataJoin.get(fieldName);
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 5 -> cb.greaterThanOrEqualTo(rating, 4.5);
|
||||
case 4 -> cb.and(cb.greaterThanOrEqualTo(rating, 4.0), cb.lessThan(rating, 4.5));
|
||||
case 3 -> cb.and(cb.greaterThanOrEqualTo(rating, 3.0), cb.lessThan(rating, 4.0));
|
||||
case 2 -> cb.and(cb.greaterThanOrEqualTo(rating, 2.0), cb.lessThan(rating, 3.0));
|
||||
case 1 -> cb.and(cb.greaterThanOrEqualTo(rating, 1.0), cb.lessThan(rating, 2.0));
|
||||
case 0 -> cb.lessThan(rating, 1.0);
|
||||
default -> throw new APIException("Invalid " + fieldName + " bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withPageCounts(List<String> rangeIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, "pageCount");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<Integer> count = metadataJoin.get("pageCount");
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 0 -> cb.lessThan(count, 50);
|
||||
case 1 -> cb.and(cb.greaterThanOrEqualTo(count, 50), cb.lessThan(count, 100));
|
||||
case 2 -> cb.and(cb.greaterThanOrEqualTo(count, 100), cb.lessThan(count, 200));
|
||||
case 3 -> cb.and(cb.greaterThanOrEqualTo(count, 200), cb.lessThan(count, 400));
|
||||
case 4 -> cb.and(cb.greaterThanOrEqualTo(count, 400), cb.lessThan(count, 600));
|
||||
case 5 -> cb.and(cb.greaterThanOrEqualTo(count, 600), cb.lessThan(count, 1000));
|
||||
case 6 -> cb.greaterThanOrEqualTo(count, 1000);
|
||||
default -> throw new APIException("Invalid pageCount bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withShelfStatus(List<String> values, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(values);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
List<String> invalid = cleaned.stream()
|
||||
.filter(v -> !v.equals("shelved") && !v.equals("unshelved"))
|
||||
.toList();
|
||||
if (!invalid.isEmpty()) {
|
||||
throw new APIException("Invalid shelfStatus values: " + invalid
|
||||
+ ". Valid values: [shelved, unshelved]", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
boolean wantShelved = cleaned.contains("shelved");
|
||||
boolean wantUnshelved = cleaned.contains("unshelved");
|
||||
if (wantShelved && wantUnshelved) return cb.conjunction();
|
||||
Predicate hasShelves = cb.isNotEmpty(root.get("shelves"));
|
||||
Predicate combined = wantShelved ? hasShelves : cb.not(hasShelves);
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withComicCharacters(List<String> values, String mode) {
|
||||
return buildComicCollectionSpec(values, mode, "characters");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withComicTeams(List<String> values, String mode) {
|
||||
return buildComicCollectionSpec(values, mode, "teams");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withComicLocations(List<String> values, String mode) {
|
||||
return buildComicCollectionSpec(values, mode, "locations");
|
||||
}
|
||||
|
||||
private static Specification<BookEntity> buildComicCollectionSpec(
|
||||
List<String> values, String mode, String collectionAttr) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(values);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
|
||||
Join<?, ?> comicJoin = metaRoot.join("comicMetadata", JoinType.INNER);
|
||||
Join<?, ?> collJoin = comicJoin.join(collectionAttr, JoinType.INNER);
|
||||
sub.select(cb.literal(1L))
|
||||
.where(
|
||||
cb.equal(metaRoot.get("id"), root.get("id")),
|
||||
cb.lower(collJoin.get("name")).in(cleaned)
|
||||
);
|
||||
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inShelves(List<String> shelfIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (shelfIds.isEmpty()) return cb.conjunction();
|
||||
List<Long> ids = parseLongList(shelfIds, "shelf");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
|
||||
if ("and".equals(mode)) {
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Long id : ids) {
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.correlate(root);
|
||||
Join<BookEntity, ShelfEntity> subShelves = subRoot.join("shelves", JoinType.INNER);
|
||||
sub.select(cb.literal(1L)).where(cb.equal(subShelves.get("id"), id));
|
||||
predicates.add(cb.exists(sub));
|
||||
}
|
||||
return cb.and(predicates.toArray(new Predicate[0]));
|
||||
}
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.correlate(root);
|
||||
Join<BookEntity, ShelfEntity> subShelves = subRoot.join("shelves", JoinType.INNER);
|
||||
sub.select(cb.literal(1L)).where(subShelves.get("id").in(ids));
|
||||
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inLibraries(List<String> libraryIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (libraryIds.isEmpty()) return cb.conjunction();
|
||||
List<Long> ids = parseLongList(libraryIds, "library");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
|
||||
if ("and".equals(mode)) {
|
||||
if (ids.size() > 1) return cb.disjunction(); // A book can't be in multiple libraries
|
||||
return cb.equal(root.get("library").get("id"), ids.getFirst());
|
||||
}
|
||||
|
||||
Predicate combined = root.get("library").get("id").in(ids);
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withComicCreators(List<String> values, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (values == null || values.isEmpty()) return cb.conjunction();
|
||||
|
||||
// value is formatted as "name:role" from frontend
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (String val : values) {
|
||||
String[] parts = val.split(":");
|
||||
String name = parts[0].trim().toLowerCase();
|
||||
String roleName = parts.length > 1 ? parts[1].trim() : null;
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<ComicCreatorMappingEntity> mappingRoot = sub.from(ComicCreatorMappingEntity.class);
|
||||
Join<?, ?> creatorJoin = mappingRoot.join("creator", JoinType.INNER);
|
||||
Join<?, ?> comicJoin = mappingRoot.join("comicMetadata", JoinType.INNER);
|
||||
|
||||
List<Predicate> where = new ArrayList<>();
|
||||
where.add(cb.equal(comicJoin.get("bookId"), root.get("id")));
|
||||
where.add(cb.equal(cb.lower(creatorJoin.get("name")), name));
|
||||
|
||||
if (roleName != null) {
|
||||
ComicCreatorRole role = parseCreatorRole(roleName);
|
||||
where.add(cb.equal(mappingRoot.get("role"), role));
|
||||
}
|
||||
|
||||
sub.select(cb.literal(1L)).where(where.toArray(new Predicate[0]));
|
||||
predicates.add(cb.exists(sub));
|
||||
}
|
||||
|
||||
Predicate combined = "and".equals(mode)
|
||||
? cb.and(predicates.toArray(new Predicate[0]))
|
||||
: cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
private static ComicCreatorRole parseCreatorRole(String roleName) {
|
||||
return switch (roleName.toLowerCase()) {
|
||||
case "penciller" -> ComicCreatorRole.PENCILLER;
|
||||
case "inker" -> ComicCreatorRole.INKER;
|
||||
case "colorist" -> ComicCreatorRole.COLORIST;
|
||||
case "letterer" -> ComicCreatorRole.LETTERER;
|
||||
case "coverartist" -> ComicCreatorRole.COVER_ARTIST;
|
||||
case "editor" -> ComicCreatorRole.EDITOR;
|
||||
default -> throw new APIException("Invalid comic creator role: " + roleName, HttpStatus.BAD_REQUEST);
|
||||
};
|
||||
}
|
||||
|
||||
private static List<String> cleanLowerCase(List<String> values) {
|
||||
if (values == null) return List.of();
|
||||
return values.stream()
|
||||
|
||||
+8
-1
@@ -97,7 +97,6 @@ class AppBookServiceFilterOptionsTest {
|
||||
AppFilterOptions result = service.getFilterOptions(5L, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
verify(entityManager, times(10)).createQuery(anyString(), any(Class.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -266,5 +265,13 @@ class AppBookServiceFilterOptionsTest {
|
||||
|
||||
when(entityManager.createQuery(anyString(), eq(Tuple.class)))
|
||||
.thenReturn(tupleQuery);
|
||||
|
||||
TypedQuery<Long> longQuery = mock(TypedQuery.class);
|
||||
when(longQuery.setParameter(anyString(), any())).thenReturn(longQuery);
|
||||
when(longQuery.getSingleResult()).thenReturn(0L);
|
||||
when(longQuery.getResultList()).thenReturn(Collections.emptyList());
|
||||
|
||||
when(entityManager.createQuery(anyString(), eq(Long.class)))
|
||||
.thenReturn(longQuery);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user