fix(hardcover): use hardcover edition based on ISBN for syncing progress (#173)

* fix: use ISBN to match the edition to sync

* fix: optimize fallback to default editions when ISBN is not present

* chore: added tests for hardcover sync

* fix: handle cases where hardcover does not have page count
This commit is contained in:
Pedro Nave
2026-04-22 17:26:53 -04:00
committed by Zach Yale
parent 5f06ab92e9
commit 85c1749a13
2 changed files with 389 additions and 376 deletions
@@ -92,31 +92,16 @@ public class HardcoverSyncService {
return;
}
// Find the book on Hardcover - use stored ID if available
HardcoverBookInfo hardcoverBook;
if (metadata.getHardcoverBookId() != null) {
// Use the stored numeric book ID and fetch edition/page info from Hardcover
hardcoverBook = new HardcoverBookInfo();
hardcoverBook.bookId = metadata.getHardcoverBookId();
log.debug("Using stored Hardcover book ID: {}", hardcoverBook.bookId);
String hardcoverBookId = metadata.getHardcoverBookId();
String isbn13 = metadata.getIsbn13();
String isbn10 = metadata.getIsbn10();
// Always fetch the default edition and page count from Hardcover
Integer bookIdInt = Integer.parseInt(hardcoverBook.bookId);
HardcoverBookInfo fetched = findHardcoverBookById(bookIdInt);
if (fetched != null) {
hardcoverBook.editionId = fetched.editionId;
hardcoverBook.pages = fetched.pages;
log.debug("Fetched from Hardcover: editionId={}, pages={}", hardcoverBook.editionId, hardcoverBook.pages);
} else {
log.warn("Could not fetch edition info from Hardcover for book ID: {}", hardcoverBook.bookId);
}
} else {
// Search by ISBN
hardcoverBook = findHardcoverBook(metadata);
if (hardcoverBook == null) {
log.debug("Hardcover sync skipped: book {} not found on Hardcover", bookId);
return;
}
// Find the book and closest edition on Hardcover
HardcoverBookInfo hardcoverBook = resolveHardcoverBook(hardcoverBookId, isbn13, isbn10);
if (hardcoverBook == null) {
log.debug("Hardcover sync skipped: book {} not found on Hardcover", bookId);
return;
}
// Determine the status based on progress
@@ -124,10 +109,14 @@ public class HardcoverSyncService {
// Calculate progress in pages
int progressPages = 0;
if (hardcoverBook.pages != null && hardcoverBook.pages > 0) {
progressPages = Math.round((progressPercent / 100.0f) * hardcoverBook.pages);
progressPages = Math.max(0, Math.min(hardcoverBook.pages, progressPages));
if (hardcoverBook.pages == null || hardcoverBook.pages == 0) {
log.warn("Hardcover sync failed: book {} has no page count information, cannot calculate progress in pages", bookId);
return;
}
progressPages = Math.round((progressPercent / 100.0f) * hardcoverBook.pages);
progressPages = Math.max(0, Math.min(hardcoverBook.pages, progressPages));
log.info("Progress calculation: userId={}, progressPercent={}%, totalPages={}, progressPages={}",
userId, progressPercent, hardcoverBook.pages, progressPages);
@@ -144,10 +133,9 @@ public class HardcoverSyncService {
boolean success = upsertReadingProgress(userBookId, hardcoverBook.editionId, progressPages, isFinished);
if (success) {
log.info("Synced progress to Hardcover: userId={}, book={}, hardcoverBookId={}, progress={}% ({}pages)",
userId, bookId, hardcoverBook.bookId, Math.round(progressPercent), progressPages);
log.info("Synced progress to Hardcover: userId={}, book={}, hardcoverBookId={}, hardcoverEditionId={}, progress={}% ({}pages)",
userId, bookId, hardcoverBook.bookId, hardcoverBook.editionId, Math.round(progressPercent), progressPages);
}
} finally {
// Clean up thread-local
currentApiToken.remove();
@@ -177,273 +165,230 @@ public class HardcoverSyncService {
}
/**
* Find a book on Hardcover by ISBN or hardcoverId.
* Returns the numeric book_id, edition_id, and page count.
* Resolve Hardcover book information using bookId and/or ISBN.
* Returns bookId, editionId, and page count based on the following logic:
* - If bookId + ISBN: Get book by ID, find edition by ISBN (with highest user_count), fallback to default editions
* - If bookId only: Get book by ID, use default_ebook_edition, fallback to default_physical_edition
* - If ISBN only: Find book with edition matching ISBN (with highest user_count)
*
* @param hardcoverBookId The Hardcover book ID (can be null)
* @param isbn13 The ISBN-13 (can be null)
* @param isbn10 The ISBN-10 (can be null)
* @return HardcoverBookInfo with bookId, editionId, and pages, or null if not found
*/
private HardcoverBookInfo findHardcoverBook(BookMetadataEntity metadata) {
// Try ISBN first
String isbn = metadata.getIsbn13();
if (isbn == null || isbn.isBlank()) {
isbn = metadata.getIsbn10();
private HardcoverBookInfo resolveHardcoverBook(String hardcoverBookId, String isbn13, String isbn10) {
// No identifiers at all, it's impossible to resolve
if ((hardcoverBookId == null || hardcoverBookId.isBlank()) &&
(isbn13 == null || isbn13.isBlank()) &&
(isbn10 == null || isbn10.isBlank())) {
log.debug("Cannot resolve Hardcover book: no bookId or ISBN provided");
return null;
}
if (isbn == null || isbn.isBlank()) {
log.debug("No ISBN available for Hardcover lookup");
return null;
}
try {
String searchQuery = """
query SearchBooks($query: String!) {
search(query: $query, query_type: "Book", per_page: 1, page: 1) {
results
}
}
""";
GraphQLRequest request = new GraphQLRequest();
request.setQuery(searchQuery);
request.setVariables(Map.of("query", isbn));
Map<String, Object> response = executeGraphQL(request);
log.debug("Hardcover search response for ISBN {}: {}", isbn, response);
if (response == null) {
// We have a specific bookId, try to resolve using it (with optional ISBN for edition matching)
if (hardcoverBookId != null && !hardcoverBookId.isBlank()) {
try {
return resolveByBookId(Integer.parseInt(hardcoverBookId), isbn13, isbn10);
} catch (NumberFormatException e) {
log.warn("Invalid Hardcover book ID format: {}", hardcoverBookId);
return null;
}
// Navigate the response to get book info
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
Map<String, Object> search = (Map<String, Object>) data.get("search");
if (search == null) return null;
Map<String, Object> results = (Map<String, Object>) search.get("results");
if (results == null) return null;
List<Map<String, Object>> hits = (List<Map<String, Object>>) results.get("hits");
if (hits == null || hits.isEmpty()) return null;
Map<String, Object> document = (Map<String, Object>) hits.getFirst().get("document");
if (document == null) return null;
// Extract book info
HardcoverBookInfo info = new HardcoverBookInfo();
// The 'id' field contains the book ID
Object idObj = document.get("id");
if (idObj instanceof String) {
info.bookId = (String) idObj;
} else if (idObj instanceof Number) {
info.bookId = String.valueOf(((Number) idObj).intValue());
}
// Get page count
Object pagesObj = document.get("pages");
if (pagesObj instanceof Number) {
info.pages = ((Number) pagesObj).intValue();
}
// Try to get default_physical_edition_id from the search results
Object defaultPhysicalEditionObj = document.get("default_physical_edition_id");
if (defaultPhysicalEditionObj instanceof Number) {
info.editionId = ((Number) defaultPhysicalEditionObj).intValue();
} else if (defaultPhysicalEditionObj instanceof String) {
try {
info.editionId = Integer.parseInt((String) defaultPhysicalEditionObj);
} catch (NumberFormatException e) {
// Ignore
}
}
// If no default physical edition found, try to look up edition by ISBN as fallback
if (info.bookId != null && info.editionId == null) {
EditionInfo edition = findEditionByIsbn(info.bookId, isbn);
if (edition != null) {
info.editionId = edition.id;
}
}
// Fetch page count from the edition (prioritizing edition page count over book-level page count)
if (info.editionId != null) {
EditionInfo edition = findEditionById(info.editionId);
if (edition != null && edition.pages != null && edition.pages > 0) {
info.pages = edition.pages;
log.debug("Using page count from edition {}: {} pages", info.editionId, info.pages);
}
}
log.info("Found Hardcover book: bookId={}, editionId={}, pages={}",
info.bookId, info.editionId, info.pages);
return info.bookId != null ? info : null;
} catch (Exception e) {
log.warn("Failed to search Hardcover by ISBN {}: {}", isbn, e.getMessage());
return null;
}
// No bookId but we have ISBN, try to resolve book by ISBN
return resolveByIsbn(isbn13, isbn10);
}
/**
* Find an edition by ISBN for a given book.
* This queries Hardcover's editions table to match by ISBN.
* Resolve book information when we have a bookId.
* Tries to match edition by ISBN, then falls back to default editions.
*/
private EditionInfo findEditionByIsbn(String bookId, String isbn) {
private HardcoverBookInfo resolveByBookId(Integer bookId, String isbn13, String isbn10) {
String query = """
query FindEditionByIsbn($bookId: Int!, $isbn: String!) {
editions(where: {
book_id: {_eq: $bookId},
_or: [
{isbn_10: {_eq: $isbn}},
{isbn_13: {_eq: $isbn}}
]
}, limit: 1) {
id
pages
}
}
""";
GraphQLRequest request = new GraphQLRequest();
request.setQuery(query);
request.setVariables(Map.of("bookId", Integer.parseInt(bookId), "isbn", isbn));
try {
Map<String, Object> response = executeGraphQL(request);
log.debug("Edition lookup response: {}", response);
if (response == null) return null;
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
List<Map<String, Object>> editions = (List<Map<String, Object>>) data.get("editions");
if (editions == null || editions.isEmpty()) return null;
Map<String, Object> edition = editions.getFirst();
EditionInfo info = new EditionInfo();
Object idObj = edition.get("id");
if (idObj instanceof Number) {
info.id = ((Number) idObj).intValue();
}
Object pagesObj = edition.get("pages");
if (pagesObj instanceof Number) {
info.pages = ((Number) pagesObj).intValue();
}
return info.id != null ? info : null;
} catch (Exception e) {
log.debug("Failed to find edition by ISBN: {}", e.getMessage());
return null;
}
}
private EditionInfo findEditionById(Integer editionId) {
String query = """
query FindEditionById($editionId: Int!) {
editions(where: {id: {_eq: $editionId}}, limit: 1) {
id
pages
}
}
""";
GraphQLRequest request = new GraphQLRequest();
request.setQuery(query);
request.setVariables(Map.of("editionId", editionId));
try {
Map<String, Object> response = executeGraphQL(request);
if (response == null) return null;
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
List<Map<String, Object>> editions = (List<Map<String, Object>>) data.get("editions");
if (editions == null || editions.isEmpty()) return null;
Map<String, Object> edition = editions.getFirst();
EditionInfo info = new EditionInfo();
Object idObj = edition.get("id");
if (idObj instanceof Number) {
info.id = ((Number) idObj).intValue();
}
Object pagesObj = edition.get("pages");
if (pagesObj instanceof Number) {
info.pages = ((Number) pagesObj).intValue();
}
return info.id != null ? info : null;
} catch (Exception e) {
log.debug("Failed to find edition by ID: {}", e.getMessage());
return null;
}
}
private HardcoverBookInfo findHardcoverBookById(Integer bookId) {
String query = """
query FindBookById($bookId: Int!) {
query GetBookWithEditions($bookId: Int!, $isbn13: String, $isbn10: String) {
books(where: {id: {_eq: $bookId}}, limit: 1) {
id
default_physical_edition_id
pages
default_ebook_edition {
id
pages
}
default_physical_edition {
id
pages
}
editions(where: {
_or: [
{isbn_13: {_eq: $isbn13}},
{isbn_10: {_eq: $isbn10}}
]
}, order_by: {users_count: desc}, limit: 1) {
id
pages
}
}
}
""";
GraphQLRequest request = new GraphQLRequest();
request.setQuery(query);
request.setVariables(Map.of("bookId", bookId));
Map<String, Object> variables = new java.util.HashMap<>();
variables.put("bookId", bookId);
variables.put("isbn13", (isbn13 != null && !isbn13.isBlank()) ? isbn13 : "");
variables.put("isbn10", (isbn10 != null && !isbn10.isBlank()) ? isbn10 : "");
request.setVariables(variables);
try {
Map<String, Object> response = executeGraphQL(request);
if (response == null) return null;
if (response == null) {
log.warn("No response from Hardcover for book ID {}", bookId);
return null;
}
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
List<Map<String, Object>> books = (List<Map<String, Object>>) data.get("books");
if (books == null || books.isEmpty()) return null;
if (books == null || books.isEmpty()) {
log.warn("Book ID {} not found on Hardcover", bookId);
return null;
}
Map<String, Object> book = books.getFirst();
HardcoverBookInfo info = new HardcoverBookInfo();
info.bookId = String.valueOf(bookId);
Object defaultPhysicalEditionObj = book.get("default_physical_edition_id");
if (defaultPhysicalEditionObj instanceof Number) {
info.editionId = ((Number) defaultPhysicalEditionObj).intValue();
} else if (defaultPhysicalEditionObj instanceof String) {
try {
info.editionId = Integer.parseInt((String) defaultPhysicalEditionObj);
} catch (NumberFormatException e) {
// Ignore
// Try to get edition by ISBN
List<Map<String, Object>> editions = (List<Map<String, Object>>) book.get("editions");
if (editions != null && !editions.isEmpty()) {
Map<String, Object> bestEdition = editions.getFirst();
info.editionId = extractInteger(bestEdition.get("id"));
info.pages = extractInteger(bestEdition.get("pages"));
log.debug("Found edition by ISBN: editionId={}, pages={}",
info.editionId, info.pages);
}
// Fallback to default_ebook_edition
if (info.editionId == null) {
Map<String, Object> defaultEbookEdition = (Map<String, Object>) book.get("default_ebook_edition");
if (defaultEbookEdition != null && defaultEbookEdition.get("id") != null) {
info.editionId = extractInteger(defaultEbookEdition.get("id"));
info.pages = extractInteger(defaultEbookEdition.get("pages"));
log.debug("Using default_ebook_edition: editionId={}, pages={}", info.editionId, info.pages);
}
}
// Get pages from the book level first
Object pagesObj = book.get("pages");
if (pagesObj instanceof Number) {
info.pages = ((Number) pagesObj).intValue();
}
// If we have an edition ID, fetch the page count from that edition
if (info.editionId != null) {
EditionInfo edition = findEditionById(info.editionId);
if (edition != null && edition.pages != null && edition.pages > 0) {
info.pages = edition.pages;
log.debug("Using page count from default physical edition {}: {} pages", info.editionId, info.pages);
// Fallback to default_physical_edition
if (info.editionId == null) {
Map<String, Object> defaultPhysicalEdition = (Map<String, Object>) book.get("default_physical_edition");
if (defaultPhysicalEdition != null && defaultPhysicalEdition.get("id") != null) {
info.editionId = extractInteger(defaultPhysicalEdition.get("id"));
info.pages = extractInteger(defaultPhysicalEdition.get("pages"));
log.debug("Using default_physical_edition: editionId={}, pages={}", info.editionId, info.pages);
}
}
return info.editionId != null || info.pages != null ? info : null;
// Fallback to book-level pages if edition has no pages
if (info.pages == null) {
info.pages = extractInteger(book.get("pages"));
}
if (info.editionId == null) {
log.warn("No edition found for book ID {}", bookId);
return null;
}
log.info("Resolved Hardcover book: bookId={}, editionId={}, pages={}",
info.bookId, info.editionId, info.pages);
return info;
} catch (Exception e) {
log.debug("Failed to find Hardcover book by ID {}: {}", bookId, e.getMessage());
log.error("Failed to resolve Hardcover book by ID {}: {}", bookId, e.getMessage());
return null;
}
}
/**
* Resolve book information when we only have ISBN.
* Finds books with matching edition and picks the one with highest user_count.
*/
private HardcoverBookInfo resolveByIsbn(String isbn13, String isbn10) {
String query = """
query GetBooksByIsbn($isbn13: String, $isbn10: String) {
books(where: {
editions: {
_or: [
{isbn_13: {_eq: $isbn13}},
{isbn_10: {_eq: $isbn10}}
]
}
}, order_by: {editions_aggregate: {max: {users_count: desc}}}, limit: 1) {
id
pages
editions(where: {
_or: [
{isbn_13: {_eq: $isbn13}},
{isbn_10: {_eq: $isbn10}}
]
}, order_by: {users_count: desc}, limit: 1) {
id
pages
}
}
}
""";
GraphQLRequest request = new GraphQLRequest();
request.setQuery(query);
Map<String, Object> variables = new java.util.HashMap<>();
variables.put("isbn13", (isbn13 != null && !isbn13.isBlank()) ? isbn13 : "");
variables.put("isbn10", (isbn10 != null && !isbn10.isBlank()) ? isbn10 : "");
request.setVariables(variables);
try {
Map<String, Object> response = executeGraphQL(request);
if (response == null) {
log.warn("No response from Hardcover for ISBN {} / {}", isbn13, isbn10);
return null;
}
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
List<Map<String, Object>> books = (List<Map<String, Object>>) data.get("books");
if (books == null || books.isEmpty()) {
log.warn("No books found on Hardcover with ISBN {} / {}", isbn13, isbn10);
return null;
}
Map<String, Object> book = books.getFirst();
List<Map<String, Object>> editions = (List<Map<String, Object>>) book.get("editions");
if (editions == null || editions.isEmpty()) {
log.warn("No valid editions found for ISBN {} / {}", isbn13, isbn10);
return null;
}
Map<String, Object> edition = editions.getFirst();
if (book == null || edition == null) {
log.warn("Book or edition data missing for ISBN {} / {}", isbn13, isbn10);
return null;
}
HardcoverBookInfo info = new HardcoverBookInfo();
info.bookId = String.valueOf(extractInteger(book.get("id")));
info.editionId = extractInteger(edition.get("id"));
info.pages = extractInteger(edition.get("pages"));
// Fallback to book-level pages if edition has no pages
if (info.pages == null) {
info.pages = extractInteger(book.get("pages"));
}
log.info("Resolved Hardcover book by ISBN: bookId={}, editionId={}, pages={}",
info.bookId, info.editionId, info.pages);
return info;
} catch (Exception e) {
log.error("Failed to resolve Hardcover book by ISBN {} / {}: {}", isbn13, isbn10, e.getMessage());
return null;
}
}
@@ -720,6 +665,24 @@ public class HardcoverSyncService {
}
}
/**
* Helper method to safely extract Integer from various number types or strings.
*/
private Integer extractInteger(Object obj) {
if (obj == null) return null;
if (obj instanceof Number) {
return ((Number) obj).intValue();
}
if (obj instanceof String) {
try {
return Integer.parseInt((String) obj);
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
/**
* Helper class to hold Hardcover book information.
*/
@@ -6,6 +6,7 @@ import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.repository.BookRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
@@ -151,10 +152,11 @@ class HardcoverSyncServiceTest {
}
@Test
@DisplayName("Should skip sync when no ISBN available")
void syncProgressToHardcover_whenNoIsbn_shouldSkip() {
@DisplayName("Should skip sync when no ISBN or hardcoverBookId available")
void syncProgressToHardcover_whenNoIsbnOrHardcoverBookId_shouldSkip() {
testMetadata.setIsbn13(null);
testMetadata.setIsbn10(null);
testMetadata.setHardcoverBookId(null);
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
@@ -171,6 +173,7 @@ class HardcoverSyncServiceTest {
// Mock successful responses for the chain
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createInsertUserBookResponse(5001, null))
.thenReturn(createEmptyUserBookReadsResponse())
.thenReturn(createInsertUserBookReadResponse());
@@ -186,7 +189,7 @@ class HardcoverSyncServiceTest {
void syncProgressToHardcover_withoutStoredBookId_shouldSearchByIsbn() {
// Mock successful responses for the chain
when(responseSpec.body(Map.class))
.thenReturn(createSearchResponse(12345, 300))
.thenReturn(createBooksByIsbnResponse(12345, 300, 10, 300))
.thenReturn(createInsertUserBookResponse(5001, null))
.thenReturn(createEmptyUserBookReadsResponse())
.thenReturn(createInsertUserBookReadResponse());
@@ -200,8 +203,7 @@ class HardcoverSyncServiceTest {
@Test
@DisplayName("Should skip further processing when book not found on Hardcover")
void syncProgressToHardcover_whenBookNotFoundOnHardcover_shouldSkipAfterSearch() {
// Mock: search returns empty results
when(responseSpec.body(Map.class)).thenReturn(createEmptySearchResponse());
when(responseSpec.body(Map.class)).thenReturn(createEmptyBooksResponse());
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
@@ -216,6 +218,7 @@ class HardcoverSyncServiceTest {
testMetadata.setPageCount(300);
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createInsertUserBookResponse(5001, null))
.thenReturn(createEmptyUserBookReadsResponse())
.thenReturn(createInsertUserBookReadResponse());
@@ -232,6 +235,7 @@ class HardcoverSyncServiceTest {
testMetadata.setPageCount(300);
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createInsertUserBookResponse(5001, null))
.thenReturn(createEmptyUserBookReadsResponse())
.thenReturn(createInsertUserBookReadResponse());
@@ -249,6 +253,7 @@ class HardcoverSyncServiceTest {
// Mock: insert_user_book returns error, then find existing, then create progress
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createInsertUserBookResponse(null, "Book already exists"))
.thenReturn(createFindUserBookResponse(5001))
.thenReturn(createEmptyUserBookReadsResponse())
@@ -267,6 +272,7 @@ class HardcoverSyncServiceTest {
// Mock: insert_user_book -> find existing read -> update read
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createInsertUserBookResponse(5001, null))
.thenReturn(createFindUserBookReadResponse(6001))
.thenReturn(createUpdateUserBookReadResponse());
@@ -283,7 +289,7 @@ class HardcoverSyncServiceTest {
testMetadata.setIsbn10("1234567890");
when(responseSpec.body(Map.class))
.thenReturn(createSearchResponse(12345, 300))
.thenReturn(createBooksByIsbnResponse(12345, 300, 10, 300))
.thenReturn(createInsertUserBookResponse(5001, null))
.thenReturn(createEmptyUserBookReadsResponse())
.thenReturn(createInsertUserBookReadResponse());
@@ -327,39 +333,168 @@ class HardcoverSyncServiceTest {
verify(restClient, never()).post();
}
// === Helper methods to create mock responses ===
private Map<String, Object> createSearchResponse(Integer bookId, Integer pages) {
Map<String, Object> response = new HashMap<>();
Map<String, Object> data = new HashMap<>();
Map<String, Object> search = new HashMap<>();
Map<String, Object> results = new HashMap<>();
Map<String, Object> hit = new HashMap<>();
Map<String, Object> document = new HashMap<>();
document.put("id", bookId.toString());
document.put("pages", pages);
hit.put("document", document);
results.put("hits", List.of(hit));
search.put("results", results);
data.put("search", search);
response.put("data", data);
return response;
// === resolveHardcoverBook ===
@Test
@DisplayName("Returns null when all identifiers are blank")
void whenAllBlank_returnsNull() throws Exception {
assertNull(resolveHardcoverBook("", " ", ""));
verify(restClient, never()).post();
}
private Map<String, Object> createEmptySearchResponse() {
Map<String, Object> response = new HashMap<>();
Map<String, Object> data = new HashMap<>();
Map<String, Object> search = new HashMap<>();
Map<String, Object> results = new HashMap<>();
@Test
@DisplayName("Returns null when bookId format is invalid")
void withInvalidBookIdFormat_returnsNull() throws Exception {
assertNull(resolveHardcoverBook("not-a-number", null, null));
verify(restClient, never()).post();
}
results.put("hits", List.of());
search.put("results", results);
data.put("search", search);
response.put("data", data);
@Test
@DisplayName("Uses default ebook edition when only bookId provided")
void withBookIdOnly_usesEbookEdition() throws Exception {
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 280), null, null));
return response;
Object result = resolveHardcoverBook("12345", null, null);
assertNotNull(result);
assertEquals(10, readPrivateIntField(result, "editionId"));
assertEquals(280, readPrivateIntField(result, "pages"));
}
@Test
@DisplayName("Falls back to physical edition when no ebook available")
void withBookIdOnly_fallsBackToPhysicalEdition() throws Exception {
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, null, edition(20, 250), null));
Object result = resolveHardcoverBook("12345", null, null);
assertNotNull(result);
assertEquals(20, readPrivateIntField(result, "editionId"));
assertEquals(250, readPrivateIntField(result, "pages"));
}
@Test
@DisplayName("Returns null when no editions found for bookId only")
void withBookIdOnly_noEditions_returnsNull() throws Exception {
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, null, null, null));
assertNull(resolveHardcoverBook("12345", null, null));
}
@Test
@DisplayName("Uses ISBN-matched edition over defaults when bookId and isbn provided")
void withBookIdAndIsbn_usesIsbnMatchedEdition() throws Exception {
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 200), null, List.of(edition(30, 320))));
Object result = resolveHardcoverBook("12345", "9781234567890", null);
assertNotNull(result);
assertEquals(30, readPrivateIntField(result, "editionId"));
assertEquals(320, readPrivateIntField(result, "pages"));
}
@Test
@DisplayName("Falls back to ebook edition when no ISBN match found")
void withBookIdAndIsbn_noIsbnMatch_fallsBackToEbook() throws Exception {
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, List.of()));
Object result = resolveHardcoverBook("12345", "9781234567890", null);
assertNotNull(result);
assertEquals(10, readPrivateIntField(result, "editionId"));
}
@Test
@DisplayName("Returns null when API returns null response for bookId only")
void withBookId_whenApiReturnsNull_returnsNull() throws Exception {
when(responseSpec.body(Map.class)).thenReturn(null);
assertNull(resolveHardcoverBook("12345", null, null));
}
@Test
@DisplayName("Resolves book and edition when only isbn13 provided")
void withIsbn13Only_resolvesViaIsbn() throws Exception {
when(responseSpec.body(Map.class))
.thenReturn(createBooksByIsbnResponse(12345, 300, 99, 280));
Object result = resolveHardcoverBook(null, "9781234567890", null);
assertNotNull(result);
assertEquals(99, readPrivateIntField(result, "editionId"));
assertEquals(280, readPrivateIntField(result, "pages"));
}
@Test
@DisplayName("Resolves book and edition when only isbn10 provided")
void withIsbn10Only_resolvesViaIsbn() throws Exception {
when(responseSpec.body(Map.class))
.thenReturn(createBooksByIsbnResponse(12345, 300, 99, 280));
Object result = resolveHardcoverBook(null, null, "1234567890");
assertNotNull(result);
assertEquals(99, readPrivateIntField(result, "editionId"));
assertEquals(280, readPrivateIntField(result, "pages"));
}
@Test
@DisplayName("Returns null when no books found for isbn only")
void withIsbnOnly_noBooksFound_returnsNull() throws Exception {
when(responseSpec.body(Map.class)).thenReturn(createEmptyBooksResponse());
assertNull(resolveHardcoverBook(null, "9781234567890", null));
}
@Test
@DisplayName("Returns null when API returns null response for isbn only")
void withIsbnOnly_whenApiReturnsNull_returnsNull() throws Exception {
when(responseSpec.body(Map.class)).thenReturn(null);
assertNull(resolveHardcoverBook(null, "9781234567890", null));
}
// === Reflection helpers ===
private Object resolveHardcoverBook(String bookId, String isbn13, String isbn10) throws Exception {
Method method = HardcoverSyncService.class
.getDeclaredMethod("resolveHardcoverBook", String.class, String.class, String.class);
method.setAccessible(true);
return method.invoke(service, bookId, isbn13, isbn10);
}
// === Helper methods to create mock responses ===
private Map<String, Object> edition(Integer id, Integer pages) {
return Map.of("id", id, "pages", pages);
}
private Map<String, Object> createBookByIdResponse(
Integer bookId,
Integer pages,
Map<String, Object> ebookEdition,
Map<String, Object> physicalEdition,
List<Map<String, Object>> isbnEditions) {
Map<String, Object> book = new HashMap<>();
if (bookId != null) book.put("id", bookId);
if (pages != null) book.put("pages", pages);
if (ebookEdition != null) book.put("default_ebook_edition", ebookEdition);
if (physicalEdition != null) book.put("default_physical_edition", physicalEdition);
book.put("editions", isbnEditions != null ? isbnEditions : List.of());
return Map.of("data", Map.of("books", List.of(book)));
}
private Map<String, Object> createBooksByIsbnResponse(Integer bookId, Integer bookPages, Integer editionId, Integer editionPages) {
Map<String, Object> book = Map.of("id", bookId, "pages", bookPages, "editions", List.of(edition(editionId, editionPages)));
return Map.of("data", Map.of("books", List.of(book)));
}
private Map<String, Object> createEmptyBooksResponse() {
return Map.of("data", Map.of("books", List.of()));
}
private Map<String, Object> createInsertUserBookResponse(Integer userBookId, String error) {
@@ -447,91 +582,6 @@ class HardcoverSyncServiceTest {
return response;
}
@Test
@DisplayName("findEditionById should return null on null response")
void findEditionById_nullResponse_shouldReturnNull() throws Exception {
when(responseSpec.body(ArgumentMatchers.<Class<Map>>eq(Map.class))).thenReturn(null);
Method method = HardcoverSyncService.class.getDeclaredMethod("findEditionById", Integer.class);
method.setAccessible(true);
Object result = method.invoke(service, 123);
assertNull(result);
}
@Test
@DisplayName("findEditionById should parse edition info when present")
void findEditionById_withData_shouldParse() throws Exception {
Map<String, Object> response = new HashMap<>();
Map<String, Object> data = new HashMap<>();
Map<String, Object> edition = new HashMap<>();
edition.put("id", 77);
edition.put("pages", 250);
data.put("editions", List.of(edition));
response.put("data", data);
when(responseSpec.body(ArgumentMatchers.<Class<Map>>eq(Map.class))).thenReturn(response);
Method method = HardcoverSyncService.class.getDeclaredMethod("findEditionById", Integer.class);
method.setAccessible(true);
Object result = method.invoke(service, 77);
assertNotNull(result);
assertEquals(77, readPrivateIntField(result, "id"));
assertEquals(250, readPrivateIntField(result, "pages"));
}
@Test
@DisplayName("findHardcoverBookById should return null on empty response")
void findHardcoverBookById_emptyResponse_shouldReturnNull() throws Exception {
when(responseSpec.body(ArgumentMatchers.<Class<Map>>eq(Map.class)))
.thenReturn(Map.of("data", Map.of("books", List.of())));
Method method = HardcoverSyncService.class.getDeclaredMethod("findHardcoverBookById", Integer.class);
method.setAccessible(true);
Object result = method.invoke(service, 123);
assertNull(result);
}
@Test
@DisplayName("findHardcoverBookById should use default edition and edition pages")
void findHardcoverBookById_withDefaultEdition_shouldUseEditionPages() throws Exception {
Map<String, Object> bookResponse = new HashMap<>();
Map<String, Object> bookData = new HashMap<>();
Map<String, Object> book = new HashMap<>();
book.put("default_physical_edition_id", "88");
bookData.put("books", List.of(book));
bookResponse.put("data", bookData);
Map<String, Object> editionResponse = new HashMap<>();
Map<String, Object> editionData = new HashMap<>();
Map<String, Object> edition = new HashMap<>();
edition.put("id", 88);
edition.put("pages", 320);
editionData.put("editions", List.of(edition));
editionResponse.put("data", editionData);
when(responseSpec.body(ArgumentMatchers.<Class<Map>>eq(Map.class)))
.thenReturn(bookResponse)
.thenReturn(editionResponse);
Method method = HardcoverSyncService.class.getDeclaredMethod("findHardcoverBookById", Integer.class);
method.setAccessible(true);
Object result = method.invoke(service, 123);
assertNotNull(result);
assertEquals("123", readPrivateStringField(result, "bookId"));
assertEquals(88, readPrivateIntField(result, "editionId"));
assertEquals(320, readPrivateIntField(result, "pages"));
}
private String readPrivateStringField(Object target, String fieldName) throws Exception {
Field field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (String) field.get(target);
}
private Integer readPrivateIntField(Object target, String fieldName) throws Exception {
Field field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(true);