From 70234d2c06979ff6fe851e2edd7821cc3fe91270 Mon Sep 17 00:00:00 2001 From: James Ward Date: Wed, 14 Oct 2026 11:16:59 -0400 Subject: [PATCH] refactor(api): copy `AppBookSpecification` to browse helpers (#2888) --- .../service/book/BookQueryService.java | 3 +- .../service/browse/BookFacetRegistry.java | 63 +- .../browse/BookFilterSpecification.java | 919 ++++++++++++++++++ .../browse/BookFilterSpecifications.java | 3 +- 4 files changed, 953 insertions(+), 35 deletions(-) create mode 100644 backend/src/main/java/org/booklore/service/browse/BookFilterSpecification.java diff --git a/backend/src/main/java/org/booklore/service/book/BookQueryService.java b/backend/src/main/java/org/booklore/service/book/BookQueryService.java index fff9afafd..734e0241e 100644 --- a/backend/src/main/java/org/booklore/service/book/BookQueryService.java +++ b/backend/src/main/java/org/booklore/service/book/BookQueryService.java @@ -13,6 +13,7 @@ import org.booklore.model.entity.BookMetadataEntity; import org.booklore.repository.BookRepository; import org.booklore.repository.UserContentRestrictionRepository; import org.booklore.security.policy.ContentRestrictionSpecification; +import org.booklore.service.browse.BookFilterSpecification; import org.booklore.service.restriction.ContentRestrictionService; import org.booklore.util.BookUtils; import org.hibernate.Hibernate; @@ -94,7 +95,7 @@ public class BookQueryService { libraryIds == null || libraryIds.isEmpty() ? cb.disjunction() : root.get("library").get("id").in(libraryIds); - return AppBookSpecification.notDeleted() + return BookFilterSpecification.notDeleted() .and(inLibraries) .and(ContentRestrictionSpecification.from(restrictionRepository.findByUserId(userId))); } diff --git a/backend/src/main/java/org/booklore/service/browse/BookFacetRegistry.java b/backend/src/main/java/org/booklore/service/browse/BookFacetRegistry.java index 3efd95b48..5c36a35da 100644 --- a/backend/src/main/java/org/booklore/service/browse/BookFacetRegistry.java +++ b/backend/src/main/java/org/booklore/service/browse/BookFacetRegistry.java @@ -1,6 +1,5 @@ package org.booklore.service.browse; -import org.booklore.app.specification.AppBookSpecification; import org.booklore.browse.FacetLogic; import org.booklore.exception.ApiError; import org.booklore.model.entity.BookEntity; @@ -42,37 +41,37 @@ public class BookFacetRegistry { public Specification toSpecification(String facetName, List values, FacetLogic logic, Long userId) { String mode = mode(logic); return switch (facetName) { - case "author" -> AppBookSpecification.withAuthors(values, mode); - case "series" -> AppBookSpecification.inSeriesMulti(values, mode); - case "genre" -> AppBookSpecification.withCategories(values, mode); - case "tag" -> AppBookSpecification.withTags(values, mode); - case "mood" -> AppBookSpecification.withMoods(values, mode); - case "language" -> AppBookSpecification.withLanguages(values, mode); - case "publisher" -> AppBookSpecification.withPublishers(values, mode); - case "narrator" -> AppBookSpecification.withNarrators(values, mode); - case "library" -> AppBookSpecification.inLibraries(values, mode); + case "author" -> BookFilterSpecification.withAuthors(values, mode); + case "series" -> BookFilterSpecification.inSeriesMulti(values, mode); + case "genre" -> BookFilterSpecification.withCategories(values, mode); + case "tag" -> BookFilterSpecification.withTags(values, mode); + case "mood" -> BookFilterSpecification.withMoods(values, mode); + case "language" -> BookFilterSpecification.withLanguages(values, mode); + case "publisher" -> BookFilterSpecification.withPublishers(values, mode); + case "narrator" -> BookFilterSpecification.withNarrators(values, mode); + case "library" -> BookFilterSpecification.inLibraries(values, mode); case "shelf" -> shelves(values, logic, userId); - case "file_type" -> AppBookSpecification.withFileTypes(values, mode); - case "read_status" -> AppBookSpecification.withReadStatuses(values, userId, mode); - case "personal_rating" -> AppBookSpecification.withPersonalRatings(values, userId, mode); - case "amazon_rating" -> AppBookSpecification.withAmazonRatings(values, mode); - case "goodreads_rating" -> AppBookSpecification.withGoodreadsRatings(values, mode); - case "hardcover_rating" -> AppBookSpecification.withHardcoverRatings(values, mode); - case "ranobedb_rating" -> AppBookSpecification.withRanobedbRatings(values, mode); - case "lubimyczytac_rating" -> AppBookSpecification.withLubimyczytacRatings(values, mode); - case "audible_rating" -> AppBookSpecification.withAudibleRatings(values, mode); - case "applebooks_rating" -> AppBookSpecification.withApplebooksRatings(values, mode); - case "age_rating" -> AppBookSpecification.withAgeRatings(values, mode); - case "content_rating" -> AppBookSpecification.withContentRatings(values, mode); - case "match_score" -> AppBookSpecification.withMatchScores(values, mode); - case "published_year" -> AppBookSpecification.withPublishedYears(values, mode); - case "file_size" -> AppBookSpecification.withFileSizes(values, mode); - case "page_count" -> AppBookSpecification.withPageCounts(values, mode); - case "shelf_status" -> AppBookSpecification.withShelfStatus(values, mode); - case "comic_character" -> AppBookSpecification.withComicCharacters(values, mode); - case "comic_team" -> AppBookSpecification.withComicTeams(values, mode); - case "comic_location" -> AppBookSpecification.withComicLocations(values, mode); - case "comic_creator" -> AppBookSpecification.withComicCreators(values, mode); + case "file_type" -> BookFilterSpecification.withFileTypes(values, mode); + case "read_status" -> BookFilterSpecification.withReadStatuses(values, userId, mode); + case "personal_rating" -> BookFilterSpecification.withPersonalRatings(values, userId, mode); + case "amazon_rating" -> BookFilterSpecification.withAmazonRatings(values, mode); + case "goodreads_rating" -> BookFilterSpecification.withGoodreadsRatings(values, mode); + case "hardcover_rating" -> BookFilterSpecification.withHardcoverRatings(values, mode); + case "ranobedb_rating" -> BookFilterSpecification.withRanobedbRatings(values, mode); + case "lubimyczytac_rating" -> BookFilterSpecification.withLubimyczytacRatings(values, mode); + case "audible_rating" -> BookFilterSpecification.withAudibleRatings(values, mode); + case "applebooks_rating" -> BookFilterSpecification.withApplebooksRatings(values, mode); + case "age_rating" -> BookFilterSpecification.withAgeRatings(values, mode); + case "content_rating" -> BookFilterSpecification.withContentRatings(values, mode); + case "match_score" -> BookFilterSpecification.withMatchScores(values, mode); + case "published_year" -> BookFilterSpecification.withPublishedYears(values, mode); + case "file_size" -> BookFilterSpecification.withFileSizes(values, mode); + case "page_count" -> BookFilterSpecification.withPageCounts(values, mode); + case "shelf_status" -> BookFilterSpecification.withShelfStatus(values, mode); + case "comic_character" -> BookFilterSpecification.withComicCharacters(values, mode); + case "comic_team" -> BookFilterSpecification.withComicTeams(values, mode); + case "comic_location" -> BookFilterSpecification.withComicLocations(values, mode); + case "comic_creator" -> BookFilterSpecification.withComicCreators(values, mode); default -> throw ApiError.INVALID_FACET.createException("Unknown facet: " + facetName); }; } @@ -92,7 +91,7 @@ public class BookFacetRegistry { } if (!regularIds.isEmpty()) { String inMode = logic == FacetLogic.AND ? "and" : "or"; - specs.add(AppBookSpecification.inShelves(regularIds, inMode)); + specs.add(BookFilterSpecification.inShelves(regularIds, inMode)); } if (specs.isEmpty()) { return (root, query, cb) -> cb.conjunction(); diff --git a/backend/src/main/java/org/booklore/service/browse/BookFilterSpecification.java b/backend/src/main/java/org/booklore/service/browse/BookFilterSpecification.java new file mode 100644 index 000000000..931268bd3 --- /dev/null +++ b/backend/src/main/java/org/booklore/service/browse/BookFilterSpecification.java @@ -0,0 +1,919 @@ +package org.booklore.service.browse; + +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Expression; +import jakarta.persistence.criteria.From; +import jakarta.persistence.criteria.Join; +import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Subquery; +import org.booklore.exception.APIException; +import org.booklore.exception.ApiError; +import org.booklore.model.entity.AuthorEntity; +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; +import org.booklore.model.entity.BookMetadataEntity; +import org.booklore.model.entity.ComicCreatorMappingEntity; +import org.booklore.model.entity.ShelfEntity; +import org.booklore.model.entity.UserBookProgressEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.model.enums.ComicCreatorRole; +import org.booklore.model.enums.ReadStatus; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.http.HttpStatus; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; + +public class BookFilterSpecification { + + private static final String PHYSICAL_FILE_TYPE = "PHYSICAL"; + + private BookFilterSpecification() { + } + + private static List parseIntList(List values, String paramName) { + List invalid = new ArrayList<>(); + List 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 parseLongList(List values, String paramName) { + List invalid = new ArrayList<>(); + List 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; + } + + private record NumericRange(T min, T max) { + } + + private static > List> parseNumericRanges(List values, Function parser, String paramName) { + List invalid = new ArrayList<>(); + List> ranges = new ArrayList<>(); + for (String value : values) { + if (value == null || value.isBlank()) { + continue; + } + NumericRange range = parseNumericRange(value.trim(), parser); + if (range == null) { + invalid.add(value.trim()); + } else { + ranges.add(range); + } + } + if (!invalid.isEmpty()) { + throw new APIException("Invalid " + paramName + " values: " + invalid + + ". Expected a number, min..max, min..*, or *..max. Minimum must not exceed maximum.", HttpStatus.BAD_REQUEST); + } + return ranges; + } + + private static > NumericRange parseNumericRange(String value, Function parser) { + try { + int separator = value.indexOf(".."); + if (separator < 0) { + T exact = parser.apply(value); + return new NumericRange<>(exact, exact); + } + String minPart = value.substring(0, separator).trim(); + String maxPart = value.substring(separator + 2).trim(); + if (minPart.equals("*") && maxPart.equals("*")) { + return null; + } + T min = minPart.equals("*") ? null : parser.apply(minPart); + T max = maxPart.equals("*") ? null : parser.apply(maxPart); + if (min != null && max != null && min.compareTo(max) > 0) { + return null; + } + return new NumericRange<>(min, max); + } catch (NumberFormatException e) { + return null; + } + } + + private static > Predicate rangesPredicate( + CriteriaBuilder cb, Expression field, List> ranges) { + List predicates = new ArrayList<>(); + for (NumericRange range : ranges) { + if (range.min() != null && range.max() != null) { + predicates.add(cb.and( + cb.greaterThanOrEqualTo(field, range.min()), + cb.lessThanOrEqualTo(field, range.max()))); + } else if (range.min() != null) { + predicates.add(cb.greaterThanOrEqualTo(field, range.min())); + } else { + predicates.add(cb.lessThanOrEqualTo(field, range.max())); + } + } + return cb.or(predicates.toArray(Predicate[]::new)); + } + + @SuppressWarnings("unchecked") + private static Join getOrCreateJoin(From from, String attribute, JoinType joinType) { + for (Join join : from.getJoins()) { + if (join.getAttribute().getName().equals(attribute) && join.getJoinType() == joinType) { + return (Join) join; + } + } + return from.join(attribute, joinType); + } + + public static Specification inLibraries(Collection libraryIds) { + return (root, query, cb) -> { + if (libraryIds == null || libraryIds.isEmpty()) { + return cb.conjunction(); + } + return root.get("library").get("id").in(libraryIds); + }; + } + + public static Specification inLibrary(Long libraryId) { + return (root, query, cb) -> { + if (libraryId == null) { + return cb.conjunction(); + } + return cb.equal(root.get("library").get("id"), libraryId); + }; + } + + public static Specification inShelf(Long shelfId) { + return (root, query, cb) -> { + if (shelfId == null) { + return cb.conjunction(); + } + Join shelvesJoin = root.join("shelves", JoinType.INNER); + return cb.equal(shelvesJoin.get("id"), shelfId); + }; + } + + /** + * 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); + return cb.greaterThanOrEqualTo(root.get("addedOn"), cutoff); + }; + } + + public static Specification searchText(String searchQuery) { + return (root, query, cb) -> { + if (searchQuery == null || searchQuery.trim().isEmpty()) { + return cb.conjunction(); + } + String pattern = "%" + searchQuery.toLowerCase().trim() + "%"; + + Join metadataJoin = root.join("metadata", JoinType.LEFT); + + // Use EXISTS subquery for author search to avoid DISTINCT and cartesian products + Subquery authorSubquery = query.subquery(Long.class); + Root metaRoot = authorSubquery.from(BookMetadataEntity.class); + Join authorJoin = metaRoot.join("authors", JoinType.INNER); + authorSubquery.select(cb.literal(1L)) + .where( + cb.equal(metaRoot.get("id"), root.get("id")), + cb.like(cb.lower(authorJoin.get("name")), pattern) + ); + + return cb.or( + cb.like(cb.lower(metadataJoin.get("title")), pattern), + cb.like(cb.lower(metadataJoin.get("seriesName")), pattern), + cb.exists(authorSubquery) + ); + }; + } + + public static Specification notDeleted() { + return (root, query, cb) -> cb.or( + cb.isNull(root.get("deleted")), + cb.equal(root.get("deleted"), false) + ); + } + + public static Specification hasScannedOn() { + return (root, query, cb) -> cb.isNotNull(root.get("scannedOn")); + } + + public static Specification hasDigitalFileOrIsPhysical() { + return (root, query, cb) -> cb.or( + cb.isNotEmpty(root.get("bookFiles")), + cb.equal(root.get("isPhysical"), true) + ); + } + + /** + * Filter books by multiple file types with mode support. + * PHYSICAL matches the book's physical flag, alongside any digital file types. + * OR = books matching ANY listed format + * AND = books matching ALL listed formats + * NOT = books matching NONE of the listed formats + */ + public static Specification withFileTypes(List fileTypes, String mode) { + if (fileTypes.stream().anyMatch(s -> s != null && PHYSICAL_FILE_TYPE.equalsIgnoreCase(s.trim()))) { + List digitalTypes = fileTypes.stream() + .filter(s -> s != null && !s.isBlank() && !PHYSICAL_FILE_TYPE.equalsIgnoreCase(s.trim())) + .toList(); + Specification physical = (root, query, cb) -> + cb.isTrue(root.get("isPhysical")); + if ("not".equals(mode)) { + physical = Specification.not(physical); + } + if (digitalTypes.isEmpty()) { + return physical; + } + Specification digital = withFileTypes(digitalTypes, mode); + return "and".equals(mode) || "not".equals(mode) ? physical.and(digital) : physical.or(digital); + } + return (root, query, cb) -> { + List unknown = new ArrayList<>(); + List parsed = fileTypes.stream() + .filter(s -> s != null && !s.isBlank()) + .map(s -> { + String trimmed = s.trim().toUpperCase(); + try { + return BookFileType.valueOf(trimmed); + } catch (IllegalArgumentException e) { + unknown.add(s.trim()); + return null; + } + }) + .filter(Objects::nonNull) + .toList(); + if (!unknown.isEmpty()) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid fileType values: " + unknown + ". Valid values: " + List.of(BookFileType.values()) + ", " + PHYSICAL_FILE_TYPE); + } + if (parsed.isEmpty()) return cb.conjunction(); + + if ("and".equals(mode)) { + List predicates = new ArrayList<>(); + for (BookFileType ft : parsed) { + Subquery sub = query.subquery(Long.class); + Root bfRoot = sub.from(BookFileEntity.class); + sub.select(bfRoot.get("book").get("id")) + .where(cb.equal(bfRoot.get("bookType"), ft), + cb.isTrue(bfRoot.get("isBookFormat"))); + predicates.add(root.get("id").in(sub)); + } + return cb.and(predicates.toArray(Predicate[]::new)); + } + + Subquery sub = query.subquery(Long.class); + Root bfRoot = sub.from(BookFileEntity.class); + sub.select(bfRoot.get("book").get("id")) + .where(bfRoot.get("bookType").in(parsed), + cb.isTrue(bfRoot.get("isBookFormat"))); + + if ("not".equals(mode)) { + return cb.not(root.get("id").in(sub)); + } + return root.get("id").in(sub); + }; + } + + /** + * Filter books by multiple read statuses with mode support (per-user). + * OR = books with ANY of the listed read statuses + * AND = impossible for a single-value field, treated as OR + * NOT = books with NONE of the listed read statuses + */ + public static Specification withReadStatuses(List statuses, Long userId, String mode) { + return (root, query, cb) -> { + if (userId == null) return cb.conjunction(); + List unknown = new ArrayList<>(); + List parsed = statuses.stream() + .filter(s -> s != null && !s.isBlank()) + .map(s -> { + String trimmed = s.trim().toUpperCase(); + try { + return ReadStatus.valueOf(trimmed); + } catch (IllegalArgumentException e) { + unknown.add(s.trim()); + return null; + } + }) + .filter(Objects::nonNull) + .toList(); + if (!unknown.isEmpty()) { + throw new APIException("Invalid status values: " + unknown + ". Valid values: " + List.of(ReadStatus.values()), HttpStatus.BAD_REQUEST); + } + if (parsed.isEmpty()) return cb.conjunction(); + + boolean hasUnset = parsed.contains(ReadStatus.UNSET); + List realStatuses = parsed.stream().filter(s -> s != ReadStatus.UNSET).toList(); + + Subquery sub = query.subquery(Long.class); + Root progressRoot = sub.from(UserBookProgressEntity.class); + sub.select(progressRoot.get("book").get("id")) + .where( + cb.equal(progressRoot.get("user").get("id"), userId), + realStatuses.isEmpty() ? cb.disjunction() : progressRoot.get("readStatus").in(realStatuses) + ); + + Predicate isReal = root.get("id").in(sub); + + // UNSET means either no progress entry OR entry with UNSET status + Subquery anyEntrySub = query.subquery(Long.class); + Root 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 unsetEntrySub = query.subquery(Long.class); + Root 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 "not".equals(mode) ? cb.not(combined) : combined; + }; + } + + /** + * Filter books where the user's personal rating is >= minRating. + */ + public static Specification withMinRating(int minRating, Long userId) { + return (root, query, cb) -> { + Subquery subquery = query.subquery(Long.class); + Root progressRoot = subquery.from(UserBookProgressEntity.class); + subquery.select(progressRoot.get("book").get("id")) + .where( + cb.equal(progressRoot.get("user").get("id"), userId), + cb.greaterThanOrEqualTo(progressRoot.get("personalRating"), minRating) + ); + return root.get("id").in(subquery); + }; + } + + /** + * Filter books where the user's personal rating is <= maxRating. + * Use maxRating=0 to find unrated books. + */ + public static Specification withMaxRating(int maxRating, Long userId) { + return (root, query, cb) -> { + Subquery subquery = query.subquery(Long.class); + Root progressRoot = subquery.from(UserBookProgressEntity.class); + + if (maxRating == 0) { + // Unrated: books with no progress entry or null personalRating + Subquery ratedSubquery = query.subquery(Long.class); + Root ratedRoot = ratedSubquery.from(UserBookProgressEntity.class); + ratedSubquery.select(ratedRoot.get("book").get("id")) + .where( + cb.equal(ratedRoot.get("user").get("id"), userId), + cb.isNotNull(ratedRoot.get("personalRating")) + ); + return cb.not(root.get("id").in(ratedSubquery)); + } + + subquery.select(progressRoot.get("book").get("id")) + .where( + cb.equal(progressRoot.get("user").get("id"), userId), + cb.lessThanOrEqualTo(progressRoot.get("personalRating"), maxRating) + ); + return root.get("id").in(subquery); + }; + } + + /** + * Filter books by multiple author names with mode support. + * OR = books with ANY of the authors + * AND = books with ALL of the authors + * NOT = books with NONE of the authors + */ + public static Specification withAuthors(List authorNames, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(authorNames); + if (cleaned.isEmpty()) return cb.conjunction(); + + return buildManyToManySpec(root, query, cb, cleaned, mode, + "metadata", "authors", "name"); + }; + } + + /** + * Filter books by multiple language codes with mode support. + */ + public static Specification withLanguages(List languages, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(languages); + if (cleaned.isEmpty()) return cb.conjunction(); + + return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "language"); + }; + } + + public static Specification inSeries(String seriesName) { + return inSeriesMulti(seriesName == null ? List.of() : List.of(seriesName), "or"); + } + + /** + * Filter books by multiple series names with mode support. + */ + public static Specification inSeriesMulti(List seriesNames, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(seriesNames); + if (cleaned.isEmpty()) return cb.conjunction(); + + return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "seriesName"); + }; + } + + /** + * Filter books by multiple categories with mode support. + */ + public static Specification withCategories(List categoryNames, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(categoryNames); + if (cleaned.isEmpty()) return cb.conjunction(); + + return buildManyToManySpec(root, query, cb, cleaned, mode, + "metadata", "categories", "name"); + }; + } + + /** + * Filter books by multiple publishers with mode support. + */ + public static Specification withPublishers(List publishers, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(publishers); + if (cleaned.isEmpty()) return cb.conjunction(); + + return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "publisher"); + }; + } + + /** + * Filter books by multiple tags with mode support. + */ + public static Specification withTags(List tagNames, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(tagNames); + if (cleaned.isEmpty()) return cb.conjunction(); + + return buildManyToManySpec(root, query, cb, cleaned, mode, + "metadata", "tags", "name"); + }; + } + + /** + * Filter books by multiple moods with mode support. + */ + public static Specification withMoods(List moodNames, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(moodNames); + if (cleaned.isEmpty()) return cb.conjunction(); + + return buildManyToManySpec(root, query, cb, cleaned, mode, + "metadata", "moods", "name"); + }; + } + + /** + * Filter books by multiple narrators with mode support. + */ + public static Specification withNarrators(List narrators, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(narrators); + if (cleaned.isEmpty()) return cb.conjunction(); + + return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "narrator"); + }; + } + + public static Specification unshelved() { + return (root, query, cb) -> { + Subquery subquery = query.subquery(Long.class); + Root subRoot = subquery.correlate(root); + Join shelvesJoin = subRoot.join("shelves", JoinType.INNER); + subquery.select(cb.literal(1L)); + return cb.not(cb.exists(subquery)); + }; + } + + public static Specification withAgeRatings(List values, String mode) { + return (root, query, cb) -> { + List> ranges = parseNumericRanges(values, Integer::valueOf, "ageRating"); + if (ranges.isEmpty()) return cb.conjunction(); + Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); + Expression ageRating = metadataJoin.get("ageRating"); + Predicate combined = rangesPredicate(cb, ageRating, ranges); + return "not".equals(mode) ? cb.not(combined) : combined; + }; + } + + public static Specification withContentRatings(List values, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(values); + if (cleaned.isEmpty()) return cb.conjunction(); + return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "contentRating"); + }; + } + + public static Specification withMatchScores(List values, String mode) { + return (root, query, cb) -> { + List> ranges = parseNumericRanges(values, Float::valueOf, "matchScore"); + if (ranges.isEmpty()) return cb.conjunction(); + Expression score = root.get("metadataMatchScore"); + Predicate combined = rangesPredicate(cb, score, ranges); + return "not".equals(mode) ? cb.not(combined) : combined; + }; + } + + public static Specification withPublishedYears(List years, String mode) { + return (root, query, cb) -> { + List> ranges = parseNumericRanges(years, Integer::valueOf, "publishedDate"); + if (ranges.isEmpty()) return cb.conjunction(); + Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); + Expression yearExpr = cb.function("YEAR", Integer.class, metadataJoin.get("publishedDate")); + Predicate combined = rangesPredicate(cb, yearExpr, ranges); + return "not".equals(mode) ? cb.not(combined) : combined; + }; + } + + public static Specification withFileSizes(List values, String mode) { + return (root, query, cb) -> { + List> ranges = parseNumericRanges(values, Long::valueOf, "fileSize"); + if (ranges.isEmpty()) return cb.conjunction(); + + // Matches against the book's first book-format file. + Subquery sub = query.subquery(Long.class); + Root file = sub.from(BookFileEntity.class); + Subquery earlier = sub.subquery(Long.class); + Root earlierFile = earlier.from(BookFileEntity.class); + earlier.select(cb.literal(1L)).where( + cb.equal(earlierFile.get("book").get("id"), root.get("id")), + cb.equal(earlierFile.get("isBookFormat"), true), + cb.lessThan(earlierFile.get("id"), file.get("id"))); + sub.select(cb.literal(1L)).where( + cb.equal(file.get("book").get("id"), root.get("id")), + cb.equal(file.get("isBookFormat"), true), + cb.not(cb.exists(earlier)), + rangesPredicate(cb, file.get("fileSizeKb"), ranges)); + + return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub); + }; + } + + public static Specification withPersonalRatings(List values, Long userId, String mode) { + return (root, query, cb) -> { + if (userId == null || values.isEmpty()) return cb.conjunction(); + List parsed = parseIntList(values, "personalRating"); + if (parsed.isEmpty()) return cb.conjunction(); + Subquery sub = query.subquery(Long.class); + Root 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 withAmazonRatings(List rangeIds, String mode) { + return buildRatingRangeSpec(rangeIds, mode, "amazonRating"); + } + + public static Specification withGoodreadsRatings(List rangeIds, String mode) { + return buildRatingRangeSpec(rangeIds, mode, "goodreadsRating"); + } + + public static Specification withHardcoverRatings(List rangeIds, String mode) { + return buildRatingRangeSpec(rangeIds, mode, "hardcoverRating"); + } + + public static Specification withLubimyczytacRatings(List rangeIds, String mode) { + return buildRatingRangeSpec(rangeIds, mode, "lubimyczytacRating"); + } + + public static Specification withRanobedbRatings(List rangeIds, String mode) { + return buildRatingRangeSpec(rangeIds, mode, "ranobedbRating"); + } + + public static Specification withAudibleRatings(List rangeIds, String mode) { + return buildRatingRangeSpec(rangeIds, mode, "audibleRating"); + } + + public static Specification withApplebooksRatings(List rangeIds, String mode) { + return buildRatingRangeSpec(rangeIds, mode, "applebooksRating"); + } + + private static Specification buildRatingRangeSpec( + List values, String mode, String fieldName) { + return (root, query, cb) -> { + List> ranges = parseNumericRanges(values, Double::valueOf, fieldName); + if (ranges.isEmpty()) return cb.conjunction(); + Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); + Expression rating = metadataJoin.get(fieldName); + Predicate combined = rangesPredicate(cb, rating, ranges); + return "not".equals(mode) ? cb.not(combined) : combined; + }; + } + + public static Specification withPageCounts(List values, String mode) { + return (root, query, cb) -> { + List> ranges = parseNumericRanges(values, Integer::valueOf, "pageCount"); + if (ranges.isEmpty()) return cb.conjunction(); + Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); + Expression count = metadataJoin.get("pageCount"); + Predicate combined = rangesPredicate(cb, count, ranges); + return "not".equals(mode) ? cb.not(combined) : combined; + }; + } + + public static Specification withShelfStatus(List values, String mode) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(values); + if (cleaned.isEmpty()) return cb.conjunction(); + List 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 withComicCharacters(List values, String mode) { + return buildComicCollectionSpec(values, mode, "characters"); + } + + public static Specification withComicTeams(List values, String mode) { + return buildComicCollectionSpec(values, mode, "teams"); + } + + public static Specification withComicLocations(List values, String mode) { + return buildComicCollectionSpec(values, mode, "locations"); + } + + private static Specification buildComicCollectionSpec( + List values, String mode, String collectionAttr) { + return (root, query, cb) -> { + List cleaned = cleanLowerCase(values); + if (cleaned.isEmpty()) return cb.conjunction(); + + Subquery sub = query.subquery(Long.class); + Root 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 inShelves(List shelfIds, String mode) { + return (root, query, cb) -> { + if (shelfIds.isEmpty()) return cb.conjunction(); + List ids = parseLongList(shelfIds, "shelf"); + if (ids.isEmpty()) return cb.conjunction(); + + if ("and".equals(mode)) { + List predicates = new ArrayList<>(); + for (Long id : ids) { + Subquery sub = query.subquery(Long.class); + Root subRoot = sub.correlate(root); + Join 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(Predicate[]::new)); + } + + Subquery sub = query.subquery(Long.class); + Root subRoot = sub.correlate(root); + Join 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 inLibraries(List libraryIds, String mode) { + return (root, query, cb) -> { + if (libraryIds.isEmpty()) return cb.conjunction(); + List 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 withComicCreators(List values, String mode) { + return (root, query, cb) -> { + if (values == null || values.isEmpty()) return cb.conjunction(); + + // value is formatted as "name:role" from frontend + List 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 sub = query.subquery(Long.class); + Root mappingRoot = sub.from(ComicCreatorMappingEntity.class); + Join creatorJoin = mappingRoot.join("creator", JoinType.INNER); + Join comicJoin = mappingRoot.join("comicMetadata", JoinType.INNER); + + List 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(Predicate[]::new)); + predicates.add(cb.exists(sub)); + } + + Predicate combined = "and".equals(mode) + ? cb.and(predicates.toArray(Predicate[]::new)) + : cb.or(predicates.toArray(Predicate[]::new)); + 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 cleanLowerCase(List values) { + if (values == null) return List.of(); + return values.stream() + .filter(s -> s != null && !s.isBlank()) + .map(s -> s.trim().toLowerCase()) + .toList(); + } + + /** + * Builds a specification for a scalar field on BookMetadataEntity (language, seriesName, publisher, narrator). + * OR = metadata field IN (values) + * AND = impossible for scalar fields with multiple values (treated as OR since a scalar can only be one value) + * NOT = metadata field NOT IN (values) + */ + private static Predicate buildMetadataFieldSpec( + Root root, CriteriaQuery query, CriteriaBuilder cb, + List values, String mode, String fieldName) { + + Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); + Expression fieldExpr = cb.lower(metadataJoin.get(fieldName)); + + if ("not".equals(mode)) { + return fieldExpr.in(values).not(); + } + // Both "or" and "and" use IN for scalar fields (a single field can only match one value) + return fieldExpr.in(values); + } + + /** + * Builds a specification for a many-to-many collection (authors, categories, tags, moods). + * Uses EXISTS subqueries to avoid DISTINCT and cartesian product issues. + * + * OR = book has at least one related entity whose name is IN (values) + * AND = book has ALL of the named entities (one EXISTS per value) + * NOT = book has NONE of the named entities + */ + private static Predicate buildManyToManySpec( + Root root, CriteriaQuery query, CriteriaBuilder cb, + List values, String mode, + String metadataAttr, String collectionAttr, String nameAttr) { + + if ("and".equals(mode)) { + // AND: book must have ALL values one EXISTS subquery per value + List predicates = new ArrayList<>(); + for (String value : values) { + Subquery sub = query.subquery(Long.class); + Root metaRoot = sub.from(BookMetadataEntity.class); + Join collJoin = metaRoot.join(collectionAttr, JoinType.INNER); + sub.select(cb.literal(1L)) + .where( + cb.equal(metaRoot.get("id"), root.get("id")), + cb.equal(cb.lower(collJoin.get(nameAttr)), value) + ); + predicates.add(cb.exists(sub)); + } + return cb.and(predicates.toArray(Predicate[]::new)); + } + + // OR or NOT: single EXISTS subquery with IN clause + Subquery sub = query.subquery(Long.class); + Root metaRoot = sub.from(BookMetadataEntity.class); + Join collJoin = metaRoot.join(collectionAttr, JoinType.INNER); + sub.select(cb.literal(1L)) + .where( + cb.equal(metaRoot.get("id"), root.get("id")), + cb.lower(collJoin.get(nameAttr)).in(values) + ); + + if ("not".equals(mode)) { + return cb.not(cb.exists(sub)); + } + return cb.exists(sub); + } + + @SafeVarargs + public static Specification combine(Specification... specs) { + Specification result = (root, query, cb) -> cb.conjunction(); + for (Specification spec : specs) { + if (spec != null) { + result = result.and(spec); + } + } + return result; + } +} diff --git a/backend/src/main/java/org/booklore/service/browse/BookFilterSpecifications.java b/backend/src/main/java/org/booklore/service/browse/BookFilterSpecifications.java index 8c7c2cb1c..aacabe47a 100644 --- a/backend/src/main/java/org/booklore/service/browse/BookFilterSpecifications.java +++ b/backend/src/main/java/org/booklore/service/browse/BookFilterSpecifications.java @@ -1,7 +1,6 @@ package org.booklore.service.browse; import lombok.RequiredArgsConstructor; -import org.booklore.app.specification.AppBookSpecification; import org.booklore.browse.FacetLogic; import org.booklore.exception.ApiError; import org.booklore.model.entity.BookEntity; @@ -40,6 +39,6 @@ public class BookFilterSpecifications { } specs.add(facetRegistry.toSpecification(entry.getKey(), entry.getValue(), facetLogic, scope.userId())); } - return AppBookSpecification.combine(specs.toArray(Specification[]::new)); + return BookFilterSpecification.combine(specs.toArray(Specification[]::new)); } }