From f8375f03f30731803578fbd6197b9f44b75cd56b Mon Sep 17 00:00:00 2001 From: Pedro Nave Date: Wed, 4 Mar 2026 21:48:22 +0000 Subject: [PATCH] feat(hardcover): get Hardcover metadata from a specific edition when ISBN is provided (#2678) * fix: clean ISBN should allow ISBNs to have an X at the end * hardcover mood filter overload for just list of tags * When ISBN is given, fetch the book directly by the edition with that ISBN, and provide metadata from that edition * chore: improved formatting * PR improvements * replaced CachedTag with GraphQL specific class * moved hardcover cached tag to shared model --- .../metadata/parser/HardcoverParser.java | 135 ++++++- .../service/metadata/parser/ParserUtils.java | 9 +- .../parser/hardcover/GraphQLResponse.java | 133 +++++++ .../hardcover/HardcoverBookDetails.java | 24 +- .../hardcover/HardcoverBookSearchService.java | 71 +++- .../parser/hardcover/HardcoverCachedTag.java | 28 ++ .../parser/hardcover/HardcoverMoodFilter.java | 37 +- .../metadata/parser/HardcoverParserTest.java | 350 ++++++++++++++++-- .../hardcover/HardcoverMoodFilterTest.java | 78 ++-- 9 files changed, 741 insertions(+), 124 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverCachedTag.java diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/HardcoverParser.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/HardcoverParser.java index 931880e44..53544d46b 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/parser/HardcoverParser.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/HardcoverParser.java @@ -42,9 +42,9 @@ public class HardcoverParser implements BookParser { boolean searchByIsbn = isbnCleaned != null && !isbnCleaned.isBlank(); if (searchByIsbn) { - log.info("Hardcover: Fetching metadata using ISBN {}", fetchMetadataRequest.getIsbn()); - List hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getIsbn()); - return processHits(hits, fetchMetadataRequest, true); + log.info("Hardcover: Fetching metadata using ISBN {}", isbnCleaned); + List hits = hardcoverBookSearchService.searchBookByIsbn(isbnCleaned); + return processBooksWithEditions(hits); } String title = fetchMetadataRequest.getTitle(); @@ -79,6 +79,27 @@ public class HardcoverParser implements BookParser { return results; } + private List processBooksWithEditions(List books) { + if (books == null || books.isEmpty()) { + return Collections.emptyList(); + } + + List results = new ArrayList<>(); + for (GraphQLResponse.BookWithEditions book : books) { + if (book.getEditions() == null || book.getEditions().isEmpty()) { + continue; + } + for (GraphQLResponse.Edition edition : book.getEditions()) { + log.debug("Processing edition '{}' with id '{}' of book '{}'", edition.getTitle(), edition.getId(), book.getTitle()); + BookMetadata metadata = mapEditionToMetadata(edition, book); + if (metadata != null) { + results.add(metadata); + } + } + } + return results; + } + private List processHits(List hits, FetchMetadataRequest request, boolean searchByIsbn) { if (hits == null || hits.isEmpty()) { return Collections.emptyList(); @@ -110,7 +131,7 @@ public class HardcoverParser implements BookParser { return results; } - private boolean filterByAuthor(GraphQLResponse.Document doc, String searchAuthor, + private boolean filterByAuthor(GraphQLResponse.Document doc, String searchAuthor, boolean searchByIsbn, FuzzyScore fuzzyScore) { // Skip author filtering for ISBN searches or when no author provided if (searchByIsbn || searchAuthor.isBlank()) { @@ -131,7 +152,7 @@ public class HardcoverParser implements BookParser { for (String query : searchAuthorTokens) { int score = fuzzyScore.fuzzyScore(actual, query); int maxScore = Math.max( - fuzzyScore.fuzzyScore(query, query), + fuzzyScore.fuzzyScore(query, query), fuzzyScore.fuzzyScore(actual, actual) ); double similarity = maxScore > 0 ? (double) score / maxScore : 0; @@ -183,6 +204,104 @@ public class HardcoverParser implements BookParser { metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null); metadata.setProvider(MetadataProvider.Hardcover); + return metadata; + } + + private BookMetadata mapEditionToMetadata(GraphQLResponse.Edition edition, GraphQLResponse.BookWithEditions book) { + BookMetadata metadata = new BookMetadata(); + metadata.setHardcoverId(book.getSlug()); + + Integer bookId = book.getId(); + if (bookId != null) { + metadata.setHardcoverBookId(bookId.toString()); + } + + metadata.setTitle(edition.getTitle()); + metadata.setSubtitle(edition.getSubtitle()); + metadata.setDescription(book.getDescription()); + + if (edition.getCachedContributors() != null) { + metadata.setAuthors(edition.getCachedContributors().stream() + .map(GraphQLResponse.Contributor::getAuthor) + .filter(Objects::nonNull) + .map(GraphQLResponse.Author::getName) + .filter(Objects::nonNull) + .collect(Collectors.toSet())); + } + + if (book.getFeaturedBookSeries() != null && book.getFeaturedBookSeries().getSeries() != null) { + metadata.setSeriesName(book.getFeaturedBookSeries().getSeries().getName()); + metadata.setSeriesTotal(book.getFeaturedBookSeries().getSeries().getBooksCount()); + + if (book.getFeaturedBookSeries().getPosition() != null) { + try { + metadata.setSeriesNumber(Float.parseFloat(String.valueOf(book.getFeaturedBookSeries().getPosition()))); + } catch (NumberFormatException ignored) { + } + } + } + + if (book.getRating() != null) { + metadata.setHardcoverRating( + BigDecimal.valueOf(book.getRating()).setScale(2, RoundingMode.HALF_UP).doubleValue() + ); + } + metadata.setHardcoverReviewCount(book.getRatingsCount()); + metadata.setPageCount(edition.getPages()); + + if (edition.getReleaseDate() != null) { + try { + metadata.setPublishedDate(LocalDate.parse(edition.getReleaseDate())); + } catch (Exception e) { + log.debug("Could not parse release date: {}", edition.getReleaseDate()); + } + } + + // Set the language from the edition + if (edition.getLanguage() != null && edition.getLanguage().getCode2() != null) { + metadata.setLanguage(edition.getLanguage().getCode2()); + } + + // Set the Publisher from the edition + if (edition.getPublisher() != null && edition.getPublisher().getName() != null) { + metadata.setPublisher(edition.getPublisher().getName()); + } + + GraphQLResponse.CachedTags cachedTags = book.getCachedTags(); + + if (cachedTags != null && cachedTags.getMood() != null && !cachedTags.getMood().isEmpty()) { + Set basicFilteredMoods = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags.getMood()); + metadata.setMoods(basicFilteredMoods.stream() + .map(WordUtils::capitalizeFully) + .collect(Collectors.toCollection(LinkedHashSet::new))); + } + + if (cachedTags != null && cachedTags.getGenre() != null && !cachedTags.getGenre().isEmpty()) { + Set filteredGenres = HardcoverMoodFilter.filterGenresWithCounts(cachedTags.getGenre()); + metadata.setCategories(filteredGenres.stream() + .map(WordUtils::capitalizeFully) + .collect(Collectors.toSet())); + } + + if (cachedTags != null && cachedTags.getTag() != null && !cachedTags.getTag().isEmpty()) { + Set filteredTags = HardcoverMoodFilter.filterTagsWithCounts(cachedTags.getTag()); + metadata.setTags(filteredTags.stream() + .map(WordUtils::capitalizeFully) + .collect(Collectors.toSet())); + } + + metadata.setIsbn10(edition.getIsbn10()); + metadata.setIsbn13(edition.getIsbn13()); + + // If only one ISBN is provided, calculate the other + if (metadata.getIsbn10() != null && metadata.getIsbn13() == null) { + metadata.setIsbn13(BookUtils.isbn10To13(edition.getIsbn10())); + } else if (metadata.getIsbn13() != null && metadata.getIsbn10() == null) { + metadata.setIsbn10(BookUtils.isbn13to10(edition.getIsbn13())); + } + + metadata.setThumbnailUrl(edition.getImage() != null ? edition.getImage().getUrl() : null); + metadata.setProvider(MetadataProvider.Hardcover); return metadata; } @@ -282,9 +401,9 @@ public class HardcoverParser implements BookParser { if (StringUtils.isBlank(inputIsbn)) { // If we didn't search by ISBN, use first ISBN from results matchingIsbn = doc.getIsbns().stream() - .filter(isbn -> isbn.length() == 10 || isbn.length() == 13) - .findFirst() - .orElse(null); + .filter(isbn -> isbn.length() == 10 || isbn.length() == 13) + .findFirst() + .orElse(null); } else if (doc.getIsbns().contains(inputIsbn)) { // If we searched by ISBN and it matches a result perfectly, use that matchingIsbn = inputIsbn; diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/ParserUtils.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/ParserUtils.java index c6e6b37fd..f1596dba6 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/parser/ParserUtils.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/ParserUtils.java @@ -4,10 +4,15 @@ import java.util.regex.Pattern; public class ParserUtils { - private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]"); + private static final Pattern NON_ISBN_CHAR_PATTERN = Pattern.compile("[^0-9Xx]"); public static String cleanIsbn(String isbn) { if (isbn == null) return null; - return NON_DIGIT_PATTERN.matcher(isbn).replaceAll(""); + String cleaned = NON_ISBN_CHAR_PATTERN.matcher(isbn).replaceAll(""); + // Normalize 'x' to 'X' for ISBN-10 check digit + if (cleaned.length() == 10 && cleaned.endsWith("x")) { + cleaned = cleaned.substring(0, 9) + "X"; + } + return cleaned; } } diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/GraphQLResponse.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/GraphQLResponse.java index 6280bc684..40a98aac4 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/GraphQLResponse.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/GraphQLResponse.java @@ -23,6 +23,7 @@ public class GraphQLResponse { @JsonIgnoreProperties(ignoreUnknown = true) public static class Data { private Search search; + private List books; } @Getter @@ -160,6 +161,82 @@ public class GraphQLResponse { private Integer usersReadCount; } + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class BookWithEditions { + private Integer id; + private String slug; + private String title; + private String subtitle; + private String description; + + @JsonProperty("cached_contributors") + private List cachedContributors; + + @JsonProperty("featured_book_series") + private FeaturedSeries featuredBookSeries; + + private Double rating; + + @JsonProperty("ratings_count") + private Integer ratingsCount; + + @JsonProperty("reviews_count") + private Integer reviewsCount; + + private Integer pages; + + @JsonProperty("release_date") + private String releaseDate; + + @JsonProperty("release_year") + private Integer releaseYear; + + private Image image; + + @JsonProperty("cached_tags") + private CachedTags cachedTags; + + private List editions; + } + + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Edition { + private Integer id; + private String title; + private String subtitle; + + @JsonProperty("cached_contributors") + private List cachedContributors; + + private Integer pages; + + @JsonProperty("release_date") + private String releaseDate; + + @JsonProperty("release_year") + private Integer releaseYear; + + private Image image; + + private Publisher publisher; + + @JsonProperty("isbn_10") + private String isbn10; + + @JsonProperty("isbn_13") + private String isbn13; + + private Language language; + } + @Getter @Setter @NoArgsConstructor @@ -189,4 +266,60 @@ public class GraphQLResponse { @JsonProperty("books_count") private Integer booksCount; } + + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Contributor { + private Author author; + private String contribution; + } + + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Author { + private Integer id; + private String slug; + private String name; + private Image image; + } + + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class CachedTags { + @JsonProperty("Genre") + private List genre; + + @JsonProperty("Mood") + private List mood; + + @JsonProperty("Tag") + private List tag; + } + + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Publisher { + private String name; + } + + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Language { + private String code2; + } } diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverBookDetails.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverBookDetails.java index 4c015d6b2..3b68ccad3 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverBookDetails.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverBookDetails.java @@ -18,27 +18,5 @@ public class HardcoverBookDetails { private String title; @JsonProperty("cached_tags") - private Map> cachedTags; - - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - @JsonIgnoreProperties(ignoreUnknown = true) - public static class CachedTag { - private String tag; - - @JsonProperty("tagSlug") - private String tagSlug; - - private String category; - - @JsonProperty("categorySlug") - private String categorySlug; - - @JsonProperty("spoilerRatio") - private Double spoilerRatio; - - private Integer count; - } + private Map> cachedTags; } diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverBookSearchService.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverBookSearchService.java index 8157a86d8..b673614a7 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverBookSearchService.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverBookSearchService.java @@ -35,6 +35,75 @@ public class HardcoverBookSearchService { .build(); } + public List searchBookByIsbn(String isbn) { + String apiToken = getApiToken(); + if (apiToken == null) { + return Collections.emptyList(); + } + + GraphQLRequest body = new GraphQLRequest(); + body.setQuery(""" + query BookSearchByIsbn($isbn: String!) { + books( + where: {editions: {_or: [{isbn_13: {_eq: $isbn}}, {isbn_10: {_eq: $isbn}}]}} + ) { + id + slug + title + subtitle + description + cached_contributors + featured_book_series { + series { + name + books_count + } + position + } + rating + ratings_count + reviews_count + pages + release_date + release_year + image { + url + } + cached_tags + editions(where: {_or: [{isbn_13: {_eq: $isbn}}, {isbn_10: {_eq: $isbn}}]}) { + id + title + subtitle + cached_contributors + pages + release_date + release_year + image { + url + } + publisher { + name + } + isbn_10 + isbn_13 + language { + code2 + } + } + } + }"""); + body.setVariables(java.util.Map.of("isbn", isbn)); + + GraphQLResponse response = executeRequest(body, GraphQLResponse.class, apiToken); + if (response == null || response.getData() == null || + response.getData().getBooks() == null || + response.getData().getBooks().isEmpty()) { + return Collections.emptyList(); + } + + return response.getData().getBooks(); + } + public List searchBooks(String query) { return searchBooks(query, DEFAULT_PER_PAGE); } @@ -46,7 +115,7 @@ public class HardcoverBookSearchService { } int sanitizedPerPage = Math.min(Math.max(perPage, 1), 100); - + GraphQLRequest body = new GraphQLRequest(); body.setQuery("query BookSearch($q: String!, $limit: Int!) { search(query: $q, query_type: \"Book\", per_page: $limit, page: 1) { results } }"); body.setVariables(java.util.Map.of("q", query, "limit", sanitizedPerPage)); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverCachedTag.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverCachedTag.java new file mode 100644 index 000000000..4e097be2f --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverCachedTag.java @@ -0,0 +1,28 @@ +package org.booklore.service.metadata.parser.hardcover; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public class HardcoverCachedTag { + private String tag; + + @JsonProperty("tagSlug") + private String tagSlug; + + private String category; + + @JsonProperty("categorySlug") + private String categorySlug; + + @JsonProperty("spoilerRatio") + private Double spoilerRatio; + + private Integer count; + } + diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverMoodFilter.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverMoodFilter.java index 9bc695338..df5a3b9dd 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverMoodFilter.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/hardcover/HardcoverMoodFilter.java @@ -38,12 +38,15 @@ public class HardcoverMoodFilter { .collect(Collectors.toCollection(LinkedHashSet::new)); } - public static Set filterMoodsWithCounts(Map> cachedTags) { + public static Set filterMoodsWithCounts(Map> cachedTags) { if (cachedTags == null || cachedTags.isEmpty()) { return Collections.emptySet(); } - List moodTags = cachedTags.get("Mood"); + return filterMoodsWithCounts(cachedTags.get("Mood")); + } + + public static Set filterMoodsWithCounts(List moodTags) { if (moodTags == null || moodTags.isEmpty()) { return Collections.emptySet(); } @@ -51,7 +54,7 @@ public class HardcoverMoodFilter { // Find the maximum vote count int maxCount = moodTags.stream() .filter(tag -> tag.getCount() != null) - .mapToInt(HardcoverBookDetails.CachedTag::getCount) + .mapToInt(HardcoverCachedTag::getCount) .max() .orElse(0); @@ -62,10 +65,10 @@ public class HardcoverMoodFilter { int minCountThreshold = Math.max(MIN_VOTE_COUNT, (int) (maxCount * MIN_VOTE_RATIO)); - List filteredMoods = moodTags.stream() + List filteredMoods = moodTags.stream() .filter(tag -> tag.getCount() != null && tag.getCount() >= minCountThreshold) .filter(tag -> tag.getTag() != null) - .sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed()) + .sorted(Comparator.comparingInt(HardcoverCachedTag::getCount).reversed()) .limit(MAX_MOODS) .toList(); @@ -73,16 +76,19 @@ public class HardcoverMoodFilter { moodTags.size(), filteredMoods.size(), maxCount, minCountThreshold); return filteredMoods.stream() - .map(HardcoverBookDetails.CachedTag::getTag) + .map(HardcoverCachedTag::getTag) .collect(Collectors.toCollection(LinkedHashSet::new)); } - public static Set filterGenresWithCounts(Map> cachedTags) { + public static Set filterGenresWithCounts(Map> cachedTags) { if (cachedTags == null || cachedTags.isEmpty()) { return Collections.emptySet(); } - List genreTags = cachedTags.get("Genre"); + return filterGenresWithCounts(cachedTags.get("Genre")); + } + + public static Set filterGenresWithCounts(List genreTags) { if (genreTags == null || genreTags.isEmpty()) { return Collections.emptySet(); } @@ -91,18 +97,21 @@ public class HardcoverMoodFilter { return genreTags.stream() .filter(tag -> tag.getCount() != null && tag.getCount() >= 1) .filter(tag -> tag.getTag() != null) - .sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed()) + .sorted(Comparator.comparingInt(HardcoverCachedTag::getCount).reversed()) .limit(10) // Allow more genres - .map(HardcoverBookDetails.CachedTag::getTag) + .map(HardcoverCachedTag::getTag) .collect(Collectors.toCollection(LinkedHashSet::new)); } - public static Set filterTagsWithCounts(Map> cachedTags) { + public static Set filterTagsWithCounts(Map> cachedTags) { if (cachedTags == null || cachedTags.isEmpty()) { return Collections.emptySet(); } - List tagList = cachedTags.get("Tag"); + return filterTagsWithCounts(cachedTags.get("Tag")); + } + + public static Set filterTagsWithCounts(List tagList) { if (tagList == null || tagList.isEmpty()) { return Collections.emptySet(); } @@ -111,9 +120,9 @@ public class HardcoverMoodFilter { return tagList.stream() .filter(tag -> tag.getCount() != null && tag.getCount() >= 2) .filter(tag -> tag.getTag() != null) - .sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed()) + .sorted(Comparator.comparingInt(HardcoverCachedTag::getCount).reversed()) .limit(10) - .map(HardcoverBookDetails.CachedTag::getTag) + .map(HardcoverCachedTag::getTag) .collect(Collectors.toCollection(LinkedHashSet::new)); } diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/parser/HardcoverParserTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/parser/HardcoverParserTest.java index b254aa79e..e17c53473 100644 --- a/booklore-api/src/test/java/org/booklore/service/metadata/parser/HardcoverParserTest.java +++ b/booklore-api/src/test/java/org/booklore/service/metadata/parser/HardcoverParserTest.java @@ -7,6 +7,7 @@ import org.booklore.model.enums.MetadataProvider; import org.booklore.service.metadata.parser.hardcover.GraphQLResponse; import org.booklore.service.metadata.parser.hardcover.HardcoverBookDetails; import org.booklore.service.metadata.parser.hardcover.HardcoverBookSearchService; +import org.booklore.service.metadata.parser.hardcover.HardcoverCachedTag; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; @@ -23,7 +24,7 @@ import static org.mockito.Mockito.*; /** * Unit tests for HardcoverParser. - * + *

* These tests verify: * - Combined title+author search strategy for better reliability * - ISBN search behavior @@ -79,7 +80,7 @@ class HardcoverParserTest { when(hardcoverBookSearchService.searchBooks("Some Book Unknown Author")) .thenReturn(Collections.emptyList()); - + GraphQLResponse.Hit hit = createHitWithAuthor("Some Book", "Different Author"); when(hardcoverBookSearchService.searchBooks("Some Book")) .thenReturn(List.of(hit)); @@ -126,17 +127,159 @@ class HardcoverParserTest { .isbn("978-0316769488") .build(); - GraphQLResponse.Hit hit = createHitWithAuthor("The Catcher in the Rye", "J.D. Salinger"); - hit.getDocument().setIsbns(List.of("9780316769488", "0316769487")); - when(hardcoverBookSearchService.searchBooks("978-0316769488")) + GraphQLResponse.BookWithEditions hit = createBookWithEditions(); + hit.getEditions().get(0).setIsbn13("9780316769488"); + hit.getEditions().get(0).setIsbn10("0316769487"); + when(hardcoverBookSearchService.searchBookByIsbn("9780316769488")) .thenReturn(List.of(hit)); List results = parser.fetchMetadata(book, request); - verify(hardcoverBookSearchService).searchBooks("978-0316769488"); + verify(hardcoverBookSearchService).searchBookByIsbn("9780316769488"); verify(hardcoverBookSearchService, never()).searchBooks(contains("title")); } + @Test + @DisplayName("Should return empty list when ISBN search returns book with no editions") + void fetchMetadata_isbnSearchNoEditions_returnsEmptyList() { + Book book = Book.builder().title("Any Title").build(); + FetchMetadataRequest request = FetchMetadataRequest.builder() + .title("Any Title") + .isbn("9780316769488") + .build(); + + GraphQLResponse.BookWithEditions bookWithNoEditions = new GraphQLResponse.BookWithEditions(); + bookWithNoEditions.setId(12345); + bookWithNoEditions.setTitle("Test Book"); + bookWithNoEditions.setEditions(Collections.emptyList()); + + when(hardcoverBookSearchService.searchBookByIsbn("9780316769488")) + .thenReturn(List.of(bookWithNoEditions)); + + List results = parser.fetchMetadata(book, request); + + assertThat(results).isEmpty(); + } + + @Test + @DisplayName("Should return empty list when ISBN search returns book with null editions") + void fetchMetadata_isbnSearchNullEditions_returnsEmptyList() { + Book book = Book.builder().title("Any Title").build(); + FetchMetadataRequest request = FetchMetadataRequest.builder() + .title("Any Title") + .isbn("9780316769488") + .build(); + + GraphQLResponse.BookWithEditions bookWithNullEditions = new GraphQLResponse.BookWithEditions(); + bookWithNullEditions.setId(12345); + bookWithNullEditions.setTitle("Test Book"); + bookWithNullEditions.setEditions(null); + + when(hardcoverBookSearchService.searchBookByIsbn("9780316769488")) + .thenReturn(List.of(bookWithNullEditions)); + + List results = parser.fetchMetadata(book, request); + + assertThat(results).isEmpty(); + } + + @Test + @DisplayName("Should return empty list when ISBN search returns null") + void fetchMetadata_isbnSearchReturnsNull_returnsEmptyList() { + Book book = Book.builder().title("Any Title").build(); + FetchMetadataRequest request = FetchMetadataRequest.builder() + .title("Any Title") + .isbn("9780316769488") + .build(); + + when(hardcoverBookSearchService.searchBookByIsbn("9780316769488")) + .thenReturn(null); + + List results = parser.fetchMetadata(book, request); + + assertThat(results).isEmpty(); + } + + @Test + @DisplayName("Should return all editions when ISBN search returns book with multiple editions") + void fetchMetadata_isbnSearchMultipleEditions_returnsAllEditions() { + Book book = Book.builder().title("Any Title").build(); + FetchMetadataRequest request = FetchMetadataRequest.builder() + .title("Any Title") + .isbn("9780316769488") + .build(); + + GraphQLResponse.BookWithEditions bookWithEditions = createBookWithEditions(); + + // Add a second edition + GraphQLResponse.Edition secondEdition = new GraphQLResponse.Edition(); + secondEdition.setId(2); + secondEdition.setTitle("Test Book - Paperback Edition"); + secondEdition.setIsbn13("9780316769489"); + secondEdition.setIsbn10("0316769489"); + secondEdition.setPages(400); + + GraphQLResponse.Author author = new GraphQLResponse.Author(); + author.setName("Test Author"); + GraphQLResponse.Contributor contributor = new GraphQLResponse.Contributor(); + contributor.setAuthor(author); + secondEdition.setCachedContributors(List.of(contributor)); + + bookWithEditions.setEditions(List.of(bookWithEditions.getEditions().get(0), secondEdition)); + + when(hardcoverBookSearchService.searchBookByIsbn("9780316769488")) + .thenReturn(List.of(bookWithEditions)); + + List results = parser.fetchMetadata(book, request); + + assertThat(results).hasSize(2); + assertThat(results.get(0).getTitle()).isEqualTo("Test Book - Hardcover Edition"); + assertThat(results.get(1).getTitle()).isEqualTo("Test Book - Paperback Edition"); + } + + @Test + @DisplayName("Should handle edition with null optional fields gracefully") + void fetchMetadata_editionWithNullOptionalFields_handlesGracefully() { + Book book = Book.builder().title("Any Title").build(); + FetchMetadataRequest request = FetchMetadataRequest.builder() + .title("Any Title") + .isbn("9780316769488") + .build(); + + GraphQLResponse.BookWithEditions bookWithEditions = new GraphQLResponse.BookWithEditions(); + bookWithEditions.setId(12345); + bookWithEditions.setSlug("test-book"); + bookWithEditions.setTitle("Test Book"); + bookWithEditions.setDescription("A description"); + bookWithEditions.setRating(4.0); + bookWithEditions.setRatingsCount(50); + + // Edition with null language, publisher, and cachedContributors + GraphQLResponse.Edition edition = new GraphQLResponse.Edition(); + edition.setId(1); + edition.setTitle("Test Book Edition"); + edition.setIsbn13("9780316769488"); + edition.setLanguage(null); + edition.setPublisher(null); + edition.setCachedContributors(null); + edition.setImage(null); + + bookWithEditions.setEditions(List.of(edition)); + + when(hardcoverBookSearchService.searchBookByIsbn("9780316769488")) + .thenReturn(List.of(bookWithEditions)); + + List results = parser.fetchMetadata(book, request); + + assertThat(results).hasSize(1); + BookMetadata metadata = results.get(0); + assertThat(metadata.getTitle()).isEqualTo("Test Book Edition"); + assertThat(metadata.getLanguage()).isNull(); + assertThat(metadata.getPublisher()).isNull(); + assertThat(metadata.getAuthors()).isNullOrEmpty(); + assertThat(metadata.getThumbnailUrl()).isNull(); + } + @Test @DisplayName("Should search title-only when no author provided") void fetchMetadata_noAuthor_searchesTitleOnly() { @@ -210,12 +353,16 @@ class HardcoverParserTest { .author("Wrong Author") // Should be ignored .build(); - GraphQLResponse.Hit hit = createHitWithAuthor("Any Book", "Correct Author"); - when(hardcoverBookSearchService.searchBooks("123456789X")) - .thenReturn(List.of(hit)); + GraphQLResponse.BookWithEditions bookWithEditions = createBookWithEditions(); + // The book has "Test Author" but request has "Wrong Author" - should still return results + when(hardcoverBookSearchService.searchBookByIsbn("123456789X")) + .thenReturn(List.of(bookWithEditions)); List results = parser.fetchMetadata(book, request); assertThat(results).hasSize(1); // Should not filter out + verify(hardcoverBookSearchService).searchBookByIsbn("123456789X"); + + assertThat(results.get(0).getAuthors()).contains("Test Author"); } } @@ -229,18 +376,17 @@ class HardcoverParserTest { Book book = Book.builder().title("Test").build(); FetchMetadataRequest request = FetchMetadataRequest.builder() .title("Test") - .isbn("9781234567897") .build(); GraphQLResponse.Hit hit = createFullyPopulatedHit(); - when(hardcoverBookSearchService.searchBooks("9781234567897")) + when(hardcoverBookSearchService.searchBooks("Test")) .thenReturn(List.of(hit)); List results = parser.fetchMetadata(book, request); assertThat(results).hasSize(1); BookMetadata metadata = results.get(0); - + assertThat(metadata.getTitle()).isEqualTo("Test Book"); assertThat(metadata.getSubtitle()).isEqualTo("A Subtitle"); assertThat(metadata.getDescription()).isEqualTo("A description"); @@ -253,8 +399,48 @@ class HardcoverParserTest { assertThat(metadata.getSeriesName()).isEqualTo("Test Series"); assertThat(metadata.getSeriesNumber()).isEqualTo(2.0f); assertThat(metadata.getSeriesTotal()).isEqualTo(5); + assertThat(metadata.getIsbn13()).isEqualTo("9781111111113"); + assertThat(metadata.getIsbn10()).isEqualTo("1111111111"); + assertThat(metadata.getProvider()).isEqualTo(MetadataProvider.Hardcover); + } + + @Test + @DisplayName("Should map all basic metadata fields correctly when searching with ISBN") + void fetchMetadata_fullDocument_mapsAllFields_fromISBN() { + Book book = Book.builder().title("Test").build(); + FetchMetadataRequest request = FetchMetadataRequest.builder() + .title("Test") + .isbn("9781234567897") + .build(); + + GraphQLResponse.BookWithEditions hit = createBookWithEditions(); + when(hardcoverBookSearchService.searchBookByIsbn("9781234567897")) + .thenReturn(List.of(hit)); + + List results = parser.fetchMetadata(book, request); + + assertThat(results).hasSize(1); + BookMetadata metadata = results.get(0); + + assertThat(metadata.getTitle()).isEqualTo("Test Book - Hardcover Edition"); + assertThat(metadata.getSubtitle()).isEqualTo("A Subtitle"); + assertThat(metadata.getDescription()).isEqualTo("A description"); + assertThat(metadata.getHardcoverId()).isEqualTo("test-book-slug"); + assertThat(metadata.getHardcoverBookId()).isEqualTo("12345"); + assertThat(metadata.getHardcoverRating()).isEqualTo(4.25); + assertThat(metadata.getHardcoverReviewCount()).isEqualTo(100); + assertThat(metadata.getPageCount()).isEqualTo(350); + assertThat(metadata.getAuthors()).contains("Test Author"); + assertThat(metadata.getSeriesName()).isEqualTo("Test Series"); + assertThat(metadata.getSeriesNumber()).isEqualTo(2.0f); + assertThat(metadata.getSeriesTotal()).isEqualTo(5); assertThat(metadata.getIsbn13()).isEqualTo("9781234567897"); assertThat(metadata.getIsbn10()).isEqualTo("123456789X"); + assertThat(metadata.getPublisher()).isEqualTo("Test Publisher"); + assertThat(metadata.getLanguage()).isEqualTo("en"); + assertThat(metadata.getMoods()).containsExactlyInAnyOrder("Adventurous", "Exciting"); + assertThat(metadata.getCategories()).containsExactlyInAnyOrder("Fiction", "Fantasy"); + assertThat(metadata.getTags()).containsExactlyInAnyOrder("Epic", "Quest"); assertThat(metadata.getProvider()).isEqualTo(MetadataProvider.Hardcover); } @@ -267,8 +453,8 @@ class HardcoverParserTest { .isbn("123456789X") .build(); - GraphQLResponse.Hit hit = createFullyPopulatedHit(); - when(hardcoverBookSearchService.searchBooks("123456789X")) + GraphQLResponse.BookWithEditions hit = createBookWithEditions(); + when(hardcoverBookSearchService.searchBookByIsbn("123456789X")) .thenReturn(List.of(hit)); List results = parser.fetchMetadata(book, request); @@ -286,8 +472,11 @@ class HardcoverParserTest { .isbn("9791111111112") .build(); - GraphQLResponse.Hit hit = createFullyPopulatedHit(); - when(hardcoverBookSearchService.searchBooks("9791111111112")) + GraphQLResponse.BookWithEditions hit = createBookWithEditions(); + hit.getEditions().get(0).setIsbn13("9791111111112"); + hit.getEditions().get(0).setIsbn10(null); + + when(hardcoverBookSearchService.searchBookByIsbn("9791111111112")) .thenReturn(List.of(hit)); List results = parser.fetchMetadata(book, request); @@ -308,7 +497,7 @@ class HardcoverParserTest { GraphQLResponse.Image image = new GraphQLResponse.Image(); image.setUrl("https://example.com/cover.jpg"); hit.getDocument().setImage(image); - + when(hardcoverBookSearchService.searchBooks("Test")) .thenReturn(List.of(hit)); @@ -327,7 +516,7 @@ class HardcoverParserTest { GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author"); hit.getDocument().setImage(null); - + when(hardcoverBookSearchService.searchBooks("Test")) .thenReturn(List.of(hit)); @@ -352,7 +541,7 @@ class HardcoverParserTest { GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author"); hit.getDocument().setId("12345"); hit.getDocument().setMoods(List.of("sad", "dark", "funny", "hopeful")); - + when(hardcoverBookSearchService.searchBooks("Test")) .thenReturn(List.of(hit)); @@ -377,7 +566,7 @@ class HardcoverParserTest { GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author"); hit.getDocument().setId("12345"); hit.getDocument().setMoods(List.of("sad", "funny", "invalid-mood")); - + when(hardcoverBookSearchService.searchBooks("Test")) .thenReturn(List.of(hit)); when(hardcoverBookSearchService.fetchBookDetails(12345)) @@ -400,7 +589,7 @@ class HardcoverParserTest { GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author"); hit.getDocument().setMoods(null); - + when(hardcoverBookSearchService.searchBooks("Test")) .thenReturn(List.of(hit)); @@ -456,7 +645,7 @@ class HardcoverParserTest { GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author"); hit.getDocument().setId("not-a-number"); - + when(hardcoverBookSearchService.searchBooks("Test")) .thenReturn(List.of(hit)); @@ -492,7 +681,7 @@ class HardcoverParserTest { GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author"); hit.getDocument().setReleaseDate("invalid-date"); - + when(hardcoverBookSearchService.searchBooks("Test")) .thenReturn(List.of(hit)); @@ -551,7 +740,7 @@ class HardcoverParserTest { doc.setSlug(title.toLowerCase().replace(" ", "-")); doc.setAuthorNames(Set.of(author)); doc.setId(String.valueOf(new Random().nextInt(100000))); - + GraphQLResponse.Hit hit = new GraphQLResponse.Hit(); hit.setDocument(doc); return hit; @@ -573,22 +762,22 @@ class HardcoverParserTest { doc.setGenres(List.of("Fiction", "Fantasy")); doc.setMoods(List.of("adventurous", "exciting")); doc.setTags(List.of("Epic")); - + // Series info GraphQLResponse.Series series = new GraphQLResponse.Series(); series.setName("Test Series"); series.setBooksCount(5); - + GraphQLResponse.FeaturedSeries featuredSeries = new GraphQLResponse.FeaturedSeries(); featuredSeries.setSeries(series); featuredSeries.setPosition(2); doc.setFeaturedSeries(featuredSeries); - + // Image GraphQLResponse.Image image = new GraphQLResponse.Image(); image.setUrl("https://example.com/cover.jpg"); doc.setImage(image); - + GraphQLResponse.Hit hit = new GraphQLResponse.Hit(); hit.setDocument(doc); return hit; @@ -598,27 +787,114 @@ class HardcoverParserTest { HardcoverBookDetails details = new HardcoverBookDetails(); details.setId(12345); details.setTitle("Test Book"); - - Map> cachedTags = new HashMap<>(); - - List moods = new ArrayList<>(); + + Map> cachedTags = new HashMap<>(); + + List moods = new ArrayList<>(); moods.add(createCachedTag("sad", 15)); moods.add(createCachedTag("dark", 12)); moods.add(createCachedTag("emotional", 8)); moods.add(createCachedTag("funny", 2)); // Low count, should be filtered cachedTags.put("Mood", moods); - - List genres = new ArrayList<>(); + + List genres = new ArrayList<>(); genres.add(createCachedTag("Fiction", 10)); genres.add(createCachedTag("Drama", 8)); cachedTags.put("Genre", genres); - + details.setCachedTags(cachedTags); return details; } - private HardcoverBookDetails.CachedTag createCachedTag(String tag, int count) { - HardcoverBookDetails.CachedTag cachedTag = new HardcoverBookDetails.CachedTag(); + private GraphQLResponse.BookWithEditions createBookWithEditions() { + GraphQLResponse.BookWithEditions book = new GraphQLResponse.BookWithEditions(); + + book.setId(12345); + book.setSlug("test-book-slug"); + book.setTitle("Test Book"); + book.setSubtitle("A Subtitle"); + book.setDescription("A description"); + book.setRating(4.25); + book.setRatingsCount(100); + book.setReviewsCount(50); + book.setPages(350); + book.setReleaseDate("2023-01-15"); + book.setReleaseYear(2023); + + // Series info + GraphQLResponse.Series series = new GraphQLResponse.Series(); + series.setName("Test Series"); + series.setBooksCount(5); + + GraphQLResponse.FeaturedSeries featuredSeries = new GraphQLResponse.FeaturedSeries(); + featuredSeries.setSeries(series); + featuredSeries.setPosition(2); + book.setFeaturedBookSeries(featuredSeries); + + GraphQLResponse.Image image = new GraphQLResponse.Image(); + image.setUrl("https://example.com/cover.jpg"); + book.setImage(image); + + // Cached contributors for the book + GraphQLResponse.Author bookAuthor = new GraphQLResponse.Author(); + bookAuthor.setId(1); + bookAuthor.setSlug("test-author"); + bookAuthor.setName("Test Author"); + + GraphQLResponse.Contributor bookContributor = new GraphQLResponse.Contributor(); + bookContributor.setAuthor(bookAuthor); + bookContributor.setContribution("Author"); + book.setCachedContributors(List.of(bookContributor)); + + // Editions + GraphQLResponse.Edition edition = new GraphQLResponse.Edition(); + edition.setId(1); + edition.setTitle("Test Book - Hardcover Edition"); + edition.setSubtitle("A Subtitle"); + edition.setPages(350); + edition.setReleaseDate("2023-01-15"); + edition.setReleaseYear(2023); + + // Cached contributors for the edition + GraphQLResponse.Author editionAuthor = new GraphQLResponse.Author(); + editionAuthor.setId(1); + editionAuthor.setSlug("test-author"); + editionAuthor.setName("Test Author"); + + GraphQLResponse.Contributor editionContributor = new GraphQLResponse.Contributor(); + editionContributor.setAuthor(editionAuthor); + editionContributor.setContribution("Author"); + edition.setCachedContributors(List.of(editionContributor)); + + GraphQLResponse.Image editionImage = new GraphQLResponse.Image(); + editionImage.setUrl("https://example.com/edition-cover.jpg"); + edition.setImage(editionImage); + + edition.setIsbn10("123456789X"); + edition.setIsbn13("9781234567897"); + + GraphQLResponse.Publisher publisher = new GraphQLResponse.Publisher(); + publisher.setName("Test Publisher"); + edition.setPublisher(publisher); + + GraphQLResponse.Language language = new GraphQLResponse.Language(); + language.setCode2("en"); + edition.setLanguage(language); + + book.setEditions(List.of(edition)); + + // Cached tags for the book (moods, genres, tags) + GraphQLResponse.CachedTags cachedTags = new GraphQLResponse.CachedTags(); + cachedTags.setMood(List.of(createCachedTag("adventurous", 15), createCachedTag("exciting", 12), createCachedTag("novotes", 0))); + cachedTags.setGenre(List.of(createCachedTag("fiction", 20), createCachedTag("fantasy", 18), createCachedTag("novotes", 0))); + cachedTags.setTag(List.of(createCachedTag("epic", 10), createCachedTag("quest", 8), createCachedTag("novotes", 0))); + book.setCachedTags(cachedTags); + + return book; + } + + private HardcoverCachedTag createCachedTag(String tag, int count) { + HardcoverCachedTag cachedTag = new HardcoverCachedTag(); cachedTag.setTag(tag); cachedTag.setCount(count); return cachedTag; diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/parser/hardcover/HardcoverMoodFilterTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/parser/hardcover/HardcoverMoodFilterTest.java index 16dfab670..2ec7e9294 100644 --- a/booklore-api/src/test/java/org/booklore/service/metadata/parser/hardcover/HardcoverMoodFilterTest.java +++ b/booklore-api/src/test/java/org/booklore/service/metadata/parser/hardcover/HardcoverMoodFilterTest.java @@ -27,9 +27,9 @@ class HardcoverMoodFilterTest { @DisplayName("filterBasicMoods should only return recognized moods") void filterBasicMoods_mixedMoods_returnsOnlyRecognized() { List moods = List.of("funny", "invalid-mood", "sad", "not-a-mood", "dark"); - + Set result = HardcoverMoodFilter.filterBasicMoods(moods); - + assertThat(result) .containsExactlyInAnyOrder("funny", "sad", "dark") .doesNotContain("invalid-mood", "not-a-mood"); @@ -39,9 +39,9 @@ class HardcoverMoodFilterTest { @DisplayName("filterBasicMoods should normalize case to lowercase") void filterBasicMoods_mixedCase_normalizesToLowercase() { List moods = List.of("FUNNY", "Sad", "DaRk", "Emotional"); - + Set result = HardcoverMoodFilter.filterBasicMoods(moods); - + assertThat(result) .containsExactlyInAnyOrder("funny", "sad", "dark", "emotional"); } @@ -53,9 +53,9 @@ class HardcoverMoodFilterTest { "funny", "sad", "dark", "emotional", "tense", "hopeful", "romantic", "scary", "mysterious", "reflective" ); - + Set result = HardcoverMoodFilter.filterBasicMoods(moods); - + assertThat(result).hasSize(HardcoverMoodFilter.MAX_MOODS); } @@ -67,9 +67,9 @@ class HardcoverMoodFilterTest { moods.add(null); moods.add("sad"); moods.add(null); - + Set result = HardcoverMoodFilter.filterBasicMoods(moods); - + assertThat(result).containsExactlyInAnyOrder("funny", "sad"); } @@ -77,27 +77,27 @@ class HardcoverMoodFilterTest { @DisplayName("filterBasicMoods should trim whitespace from moods") void filterBasicMoods_whitespace_trimsCorrectly() { List moods = List.of(" funny ", " sad", "dark "); - + Set result = HardcoverMoodFilter.filterBasicMoods(moods); - + assertThat(result).containsExactlyInAnyOrder("funny", "sad", "dark"); } @Test @DisplayName("filterMoodsWithCounts should return empty set for null cached_tags") void filterMoodsWithCounts_nullCachedTags_returnsEmptySet() { - Set result = HardcoverMoodFilter.filterMoodsWithCounts(null); + Set result = HardcoverMoodFilter.filterMoodsWithCounts((Map>) null); assertThat(result).isEmpty(); } @Test @DisplayName("filterMoodsWithCounts should return empty set when no Mood category") void filterMoodsWithCounts_noMoodCategory_returnsEmptySet() { - Map> cachedTags = new HashMap<>(); + Map> cachedTags = new HashMap<>(); cachedTags.put("Genre", List.of(createCachedTag("Fiction", 10))); - + Set result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags); - + assertThat(result).isEmpty(); } @@ -108,7 +108,7 @@ class HardcoverMoodFilterTest { // "sad" has 17 votes, "funny" has 4 votes // With max=17 and MIN_VOTE_RATIO=0.15, threshold is ~3 // But "funny" at 4 votes should still be filtered if we use higher threshold - Map> cachedTags = new HashMap<>(); + Map> cachedTags = new HashMap<>(); cachedTags.put("Mood", List.of( createCachedTag("sad", 17), createCachedTag("dark", 16), @@ -117,9 +117,9 @@ class HardcoverMoodFilterTest { createCachedTag("hopeful", 1), // Very low createCachedTag("scary", 1) // Very low )); - + Set result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags); - + // Top moods should be included assertThat(result).contains("sad", "dark", "emotional"); // Low-vote moods should be filtered @@ -129,31 +129,31 @@ class HardcoverMoodFilterTest { @Test @DisplayName("filterMoodsWithCounts should respect MAX_MOODS limit") void filterMoodsWithCounts_manyHighVoteMoods_limitsToMax() { - Map> cachedTags = new HashMap<>(); - List moodTags = new ArrayList<>(); + Map> cachedTags = new HashMap<>(); + List moodTags = new ArrayList<>(); // Create 10 moods all with high vote counts for (int i = 0; i < 10; i++) { moodTags.add(createCachedTag("mood" + i, 20 - i)); } cachedTags.put("Mood", moodTags); - + Set result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags); - + assertThat(result).hasSize(HardcoverMoodFilter.MAX_MOODS); } @Test @DisplayName("filterMoodsWithCounts should order moods by vote count (highest first)") void filterMoodsWithCounts_orderedByVoteCount() { - Map> cachedTags = new HashMap<>(); + Map> cachedTags = new HashMap<>(); cachedTags.put("Mood", List.of( createCachedTag("emotional", 5), createCachedTag("sad", 15), createCachedTag("dark", 10) )); - + Set result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags); - + // Result should be LinkedHashSet preserving order List resultList = new ArrayList<>(result); assertThat(resultList).containsExactly("sad", "dark", "emotional"); @@ -162,16 +162,16 @@ class HardcoverMoodFilterTest { @Test @DisplayName("filterMoodsWithCounts should handle null vote counts") void filterMoodsWithCounts_nullVoteCounts_handlesGracefully() { - Map> cachedTags = new HashMap<>(); - HardcoverBookDetails.CachedTag tagWithNullCount = createCachedTag("mysterious", null); + Map> cachedTags = new HashMap<>(); + HardcoverCachedTag tagWithNullCount = createCachedTag("mysterious", null); cachedTags.put("Mood", List.of( createCachedTag("sad", 10), tagWithNullCount, createCachedTag("dark", 8) )); - + Set result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags); - + assertThat(result).containsExactlyInAnyOrder("sad", "dark"); assertThat(result).doesNotContain("mysterious"); } @@ -179,30 +179,30 @@ class HardcoverMoodFilterTest { @Test @DisplayName("filterMoodsWithCounts should return empty when all votes are zero") void filterMoodsWithCounts_allZeroVotes_returnsEmpty() { - Map> cachedTags = new HashMap<>(); + Map> cachedTags = new HashMap<>(); cachedTags.put("Mood", List.of( createCachedTag("sad", 0), createCachedTag("dark", 0) )); - + Set result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags); - + assertThat(result).isEmpty(); } @Test @DisplayName("filterGenresWithCounts should return filtered genres") void filterGenresWithCounts_validData_returnsFiltered() { - Map> cachedTags = new HashMap<>(); + Map> cachedTags = new HashMap<>(); cachedTags.put("Genre", List.of( createCachedTag("Fiction", 10), createCachedTag("War", 8), createCachedTag("Classics", 5), createCachedTag("Comics", 0) // Should be filtered out )); - + Set result = HardcoverMoodFilter.filterGenresWithCounts(cachedTags); - + assertThat(result).containsExactlyInAnyOrder("Fiction", "War", "Classics"); assertThat(result).doesNotContain("Comics"); } @@ -210,15 +210,15 @@ class HardcoverMoodFilterTest { @Test @DisplayName("filterTagsWithCounts should filter tags with low votes") void filterTagsWithCounts_mixedVotes_filtersLowVotes() { - Map> cachedTags = new HashMap<>(); + Map> cachedTags = new HashMap<>(); cachedTags.put("Tag", List.of( createCachedTag("Loveable Characters", 13), createCachedTag("Strong Character Development", 9), createCachedTag("Plot driven", 1) // Should be filtered (below threshold) )); - + Set result = HardcoverMoodFilter.filterTagsWithCounts(cachedTags); - + assertThat(result).contains("Loveable Characters", "Strong Character Development"); assertThat(result).doesNotContain("Plot driven"); } @@ -249,8 +249,8 @@ class HardcoverMoodFilterTest { /** * Helper method to create a CachedTag for testing. */ - private HardcoverBookDetails.CachedTag createCachedTag(String tag, Integer count) { - HardcoverBookDetails.CachedTag cachedTag = new HardcoverBookDetails.CachedTag(); + private HardcoverCachedTag createCachedTag(String tag, Integer count) { + HardcoverCachedTag cachedTag = new HardcoverCachedTag(); cachedTag.setTag(tag); cachedTag.setCount(count); return cachedTag;