fix(hardcover): hardcover sync duplicates reads and doesn't update progress (#247)

* 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

* fix: initial fix to hardcover sync

* added some additional logic to cover the hardcover API

* feat: added tests for hardcover progress sync

* chore: code cleanup

* fix: check if the progress insert and update are actually successful before logging

* fix: ensure book edition id is being updated

* fix: updateUserBookRead returned true even if there was an error
This commit is contained in:
Pedro Nave
2026-04-22 17:27:06 -04:00
committed by Zach Yale
parent 4527d43e84
commit a261749b8c
2 changed files with 554 additions and 182 deletions
@@ -104,9 +104,6 @@ public class HardcoverSyncService {
return;
}
// Determine the status based on progress
int statusId = progressPercent >= 99.0f ? STATUS_READ : STATUS_CURRENTLY_READING;
// Calculate progress in pages
int progressPages = 0;
if (hardcoverBook.pages == null || hardcoverBook.pages == 0) {
@@ -116,25 +113,82 @@ public class HardcoverSyncService {
progressPages = Math.round((progressPercent / 100.0f) * hardcoverBook.pages);
progressPages = Math.max(0, Math.min(hardcoverBook.pages, progressPages));
boolean isFinished = progressPercent >= 99.0f;
log.info("Progress calculation: userId={}, progressPercent={}%, totalPages={}, progressPages={}",
userId, progressPercent, hardcoverBook.pages, progressPages);
// Step 1: Add/update the book in user's library
Integer bookIdInt = Integer.parseInt(hardcoverBook.bookId);
Integer userBookId = insertOrGetUserBook(bookIdInt, hardcoverBook.editionId, statusId);
if (userBookId == null) {
log.warn("Hardcover sync failed: could not get user_book_id for book {}", bookId);
Integer hardcoverBookIdInt = extractInteger(hardcoverBook.bookId);
// Check if user already has the book in their library and get existing reading progress
UserBookWithReads userBook = getUserBookAndReads(hardcoverBookIdInt);
// If user doesn't have the book in their library, insert it with the matching edition.
if (userBook == null) {
// Inserting the user_book will automatically create a user_book_read entry with 0 progress and in the "Currently Reading" status, which we will then update with the correct progress below.
userBook = insertUserBook(hardcoverBookIdInt, hardcoverBook.editionId);
} else if (userBook.statusId == STATUS_READ && isFinished) {
// If the user already has the book marked as read and the progress is finished, we can skip syncing to avoid creating duplicate reads for finished books.
// This also prevents accidentally resetting the finished date if the user had already marked it as read with a finished date.
log.info("User {} has book {} marked as read on Hardcover and progress is finished, skipping progress update",
userId, bookId);
return;
} else {
// If the user already has the book in their library, check if it is not Currently Reading status or if the edition is different from the one we are syncing.
// If it's not Currently Reading, we need to update the user_book status to Currently Reading to be able to update the reading progress. This will create a new user_book_read entry with 0 progress, which we will then update with the correct progress below.
if (userBook.statusId != STATUS_CURRENTLY_READING || userBook.editionId == null || !userBook.editionId.equals(hardcoverBook.editionId)) {
userBook = updateUserBook(userBook.id, hardcoverBook.editionId);
}
}
// If we couldn't get the existing user_book and we also failed to create it, we cannot proceed with syncing progress
if (userBook == null) {
log.warn("Hardcover sync failed: could not get or create user_book entry for book {} (user {})", bookId, userId);
return;
}
// Step 2: Create or update the reading progress
boolean isFinished = progressPercent >= 99.0f;
boolean success = upsertReadingProgress(userBookId, hardcoverBook.editionId, progressPages, isFinished);
if (success) {
boolean requiresNewReadEntry = true;
// If the user already has the book in their library and is currently reading, check if the current reading activity matches the edition we want to update.
// If so, we can update the existing reading progress instead of creating a new one, which will keep the user's reading history cleaner.
if (userBook.statusId == STATUS_CURRENTLY_READING && userBook.reads != null && !userBook.reads.isEmpty()) {
// Get the last reading activity, which matches the most recent reading activity. The user might have multiple reads if they restarted the book, but we want to update the most recent one.
UserBookReadInfo readInfo = userBook.reads.getLast();
// Only update if the edition matches (to avoid updating progress on a different edition if the user restarted the book with a different edition). If edition is missing, we assume it's the same edition and update it.
if (readInfo.editionId == null || (readInfo.editionId != null && readInfo.editionId.equals(hardcoverBook.editionId))) {
readInfo.progressPages = progressPages;
if (isFinished) {
readInfo.finishedAt = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
}
// Update existing reading progress and the user book to match the edition and status based on the new progress
log.info("Updating existing reading progress for book {} (user {}), hardcoverBookId={}, hardcoverEditionId={}, progress={}% ({}pages)",
bookId, userId, hardcoverBook.bookId, hardcoverBook.editionId, Math.round(progressPercent), progressPages);
boolean updatedRead = updateUserBookRead(userBook.id, readInfo);
if (!updatedRead) {
log.warn("Failed to update existing user_book_read entry for book {} (user {})", bookId, userId);
return;
}
requiresNewReadEntry = false;
}
}
// If the book is not being currently read or there is no matching reading activity, we want to create a new one
// This should only happen if the user already has the book in their library and without a reading activity, or the latest reading activity is for another edition.
if (requiresNewReadEntry) {
boolean insertedRead = insertUserBookRead(userBook.id, hardcoverBook.editionId, progressPages, isFinished);
requiresNewReadEntry = !insertedRead;
}
if (requiresNewReadEntry) {
log.warn("Hardcover sync failed: could not update user_book_read entry for book {} (user {})", bookId, userId);
} else {
log.info("Synced progress to Hardcover: userId={}, book={}, hardcoverBookId={}, hardcoverEditionId={}, progress={}% ({}pages)",
userId, bookId, hardcoverBook.bookId, hardcoverBook.editionId, Math.round(progressPercent), progressPages);
userId, bookId, hardcoverBook.bookId, hardcoverBook.editionId, Math.round(progressPercent), progressPages);
}
} finally {
// Clean up thread-local
@@ -394,180 +448,249 @@ public class HardcoverSyncService {
}
/**
* Insert a book into the user's library or get existing user_book_id.
* Get the user's user_book entry for the specified book ID, along with all associated user_book_read entries to check existing reading progress.
* @param bookId the Hardcover book ID to fetch the user's book entry for
* @return a UserBookWithReads object containing the user's book entry and associated reading progress, or null if not found
* @throws Exception when an error occurs, distinguishing between "not found" (returns null) vs "error fetching from Hardcover" (throws exception)
*/
private Integer insertOrGetUserBook(Integer bookId, Integer editionId, int statusId) {
private UserBookWithReads getUserBookAndReads(Integer bookId) throws Exception {
String query = """
query GetUserBookAndReads($bookId:Int!) {
me {
user_books(where: {book_id:{_eq: $bookId}}) {
id
status_id
edition_id
user_book_reads {
id
edition_id
started_at
finished_at
progress
progress_pages
}
}
}
}
""";
GraphQLRequest request = new GraphQLRequest();
request.setQuery(query);
Map<String, Object> variables = new java.util.HashMap<>();
variables.put("bookId", bookId);
request.setVariables(variables);
Map<String, Object> response = executeGraphQL(request);
if (response == null) {
log.warn("No response from Hardcover for book ID {}", bookId);
throw new Exception("No response from Hardcover for book ID " + bookId);
}
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) throw new Exception("No data returned from Hardcover for book ID " + bookId);
List<Map<String, Object>> meList = (List<Map<String, Object>>) data.get("me");
if (meList == null || meList.isEmpty()) {
log.debug("No user data returned from Hardcover for book ID {}", bookId);
return null;
}
Map<String, Object> me = meList.getFirst();
List<Map<String, Object>> userBooks = (List<Map<String, Object>>) me.get("user_books");
if (userBooks == null || userBooks.isEmpty()) {
log.debug("No user_book found for book ID {}", bookId);
return null;
}
Map<String, Object> userBook = userBooks.getFirst();
if (userBook == null) {
log.debug("User_book entry is null for book ID {}", bookId);
return null;
}
log.debug("Found user_book for book ID {}: {} {}", bookId, userBooks, userBook);
return UserBookWithReads.fromMap(userBook);
}
/**
* Insert a new user_book and a corresponding user_book_read entry. This is used when there is no existing user_book for the book.
* Sets the user_book status to "currently reading". Hardcover automatically creates a user_book_read.
* @param bookId the Hardcover book ID to add to the user's library
* @param editionId the edition ID to use for the user_book and user_book_read entries
* @param progressPages the number of pages read to set in the user_book_read entry
* @param isFinished whether to set the user_book status to "read" and include a finished_at date in the user_book_read entry
* @return the created UserBookWithReads object with the new user_book and user_book_read entries, or null if the insert failed
*/
private UserBookWithReads insertUserBook(Integer bookId, Integer editionId) {
String mutation = """
mutation InsertUserBook($object: UserBookCreateInput!) {
insert_user_book(object: $object) {
user_book {
id
insert_user_book(object: $object) {
user_book {
id
status_id
edition_id
user_book_reads {
id
edition_id
started_at
finished_at
progress
progress_pages
}
}
error
}
error
}
}
""";
Map<String, Object> bookInput = new java.util.HashMap<>();
bookInput.put("book_id", bookId);
bookInput.put("status_id", statusId);
bookInput.put("date_added", LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
if (editionId != null) {
bookInput.put("edition_id", editionId);
}
bookInput.put("edition_id", editionId);
bookInput.put("status_id", STATUS_CURRENTLY_READING);
GraphQLRequest request = new GraphQLRequest();
request.setQuery(mutation);
request.setVariables(Map.of("object", bookInput));
request.setVariables(Map.of(
"object", bookInput
));
try {
Map<String, Object> response = executeGraphQL(request);
log.debug("insert_user_book response: {}", response);
log.trace("insert_user_book response: {}", response);
if (response == null) return null;
if (response.containsKey("errors")) {
log.warn("Failed to insert user_book: {}", response.get("errors"));
return null;
}
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
Map<String, Object> insertResult = (Map<String, Object>) data.get("insert_user_book");
if (insertResult == null) return null;
// Check for error (might mean book already exists)
String error = (String) insertResult.get("error");
if (error != null && !error.isBlank()) {
log.debug("insert_user_book returned error: {} - book may already exist, trying to find it", error);
return findExistingUserBook(bookId);
log.warn("Error inserting user_book: {}", error);
return null;
}
Map<String, Object> userBook = (Map<String, Object>) insertResult.get("user_book");
if (userBook == null) return null;
Object idObj = userBook.get("id");
if (idObj instanceof Number) {
return ((Number) idObj).intValue();
}
return null;
return UserBookWithReads.fromMap(userBook);
} catch (RestClientException e) {
log.warn("Failed to insert user_book: {}", e.getMessage());
// Try to find existing
return findExistingUserBook(bookId);
log.error("Failed to insert user_book: {}", e.getMessage());
}
return null;
}
/**
* Find an existing user_book entry for a book.
* Updates an existing user_book to set the edition_id and status_id based on the parameters, and returns the updated user_book with reads.
* Notes: When updating the user_book status to "Currently Reading", Hardcover automatically creates a new user_book_read entry with 0 progress. When setting to "Read", it also sets the finished_at date on that user_book_read entry, but progress stays unchanged.
* @param userBookId the ID of the existing user_book
* @param editionId the edition ID to use for the user_book_read entry
* @return the updated UserBookWithReads object, or null if the update failed
*/
private Integer findExistingUserBook(Integer bookId) {
String query = """
query FindUserBook($bookId: Int!) {
me {
user_books(where: {book_id: {_eq: $bookId}}, limit: 1) {
id
}
}
}
""";
GraphQLRequest request = new GraphQLRequest();
request.setQuery(query);
request.setVariables(Map.of("bookId", bookId));
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;
Map<String, Object> me = (Map<String, Object>) data.get("me");
if (me == null) return null;
List<Map<String, Object>> userBooks = (List<Map<String, Object>>) me.get("user_books");
if (userBooks == null || userBooks.isEmpty()) return null;
Object idObj = userBooks.getFirst().get("id");
if (idObj instanceof Number) {
return ((Number) idObj).intValue();
}
return null;
} catch (RestClientException e) {
log.warn("Failed to find existing user_book: {}", e.getMessage());
return null;
}
}
/**
* Create or update reading progress for a user_book.
*/
private boolean upsertReadingProgress(Integer userBookId, Integer editionId, int progressPages, boolean isFinished) {
log.info("upsertReadingProgress: userBookId={}, editionId={}, progressPages={}, isFinished={}",
userBookId, editionId, progressPages, isFinished);
// First, try to find existing user_book_read
Integer existingReadId = findExistingUserBookRead(userBookId);
if (existingReadId != null) {
// Update existing
log.info("Updating existing user_book_read: id={}", existingReadId);
return updateUserBookRead(existingReadId, editionId, progressPages, isFinished);
} else {
// Create new
log.info("Creating new user_book_read for userBookId={}", userBookId);
return insertUserBookRead(userBookId, editionId, progressPages, isFinished);
}
}
private Integer findExistingUserBookRead(Integer userBookId) {
String query = """
query FindUserBookRead($userBookId: Int!) {
user_book_reads(where: {user_book_id: {_eq: $userBookId}}, limit: 1) {
id
}
}
""";
GraphQLRequest request = new GraphQLRequest();
request.setQuery(query);
request.setVariables(Map.of("userBookId", userBookId));
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>> reads = (List<Map<String, Object>>) data.get("user_book_reads");
if (reads == null || reads.isEmpty()) return null;
Object idObj = reads.getFirst().get("id");
if (idObj instanceof Number) {
return ((Number) idObj).intValue();
}
return null;
} catch (RestClientException e) {
log.warn("Failed to find existing user_book_read: {}", e.getMessage());
return null;
}
}
private boolean insertUserBookRead(Integer userBookId, Integer editionId, int progressPages, boolean isFinished) {
private UserBookWithReads updateUserBook(Integer userBookId, Integer editionId) {
// Updating the user book on Hardcover has some quirky behavior that we need to account for:
// - If edition_id is changed, Hardcover updates the first non-finished user_book_read entry with the new edition_id.
// - If status is changed to "Read", Hardcover sets the finished_at date on the last user_book_read entry, but does not update the progress or progress_pages.
// Because we may be inserting a new user_book_read entry, we never set the book to finished and let the insertUserBookRead mutation handle the read status update.
String mutation = """
mutation InsertUserBookRead($userBookId: Int!, $object: DatesReadInput!) {
insert_user_book_read(user_book_id: $userBookId, user_book_read: $object) {
user_book_read {
id
mutation UpdateUserBook($userBookId: Int!, $userBookObject: UserBookUpdateInput!) {
update_user_book(id: $userBookId, object: $userBookObject) {
id
error
user_book {
id
status_id
edition_id
user_book_reads {
id
edition_id
started_at
finished_at
progress
progress_pages
}
}
}
error
}
}
""";
Map<String, Object> bookInput = new java.util.HashMap<>();
bookInput.put("edition_id", editionId);
bookInput.put("status_id", STATUS_CURRENTLY_READING);
GraphQLRequest request = new GraphQLRequest();
request.setQuery(mutation);
request.setVariables(Map.of(
"userBookId", userBookId,
"userBookObject", bookInput
));
try {
Map<String, Object> response = executeGraphQL(request);
log.trace("update_user_book response: {}", response);
if (response == null) return null;
if (response.containsKey("errors")) {
log.warn("update_user_book returned errors: {}", response.get("errors"));
return null;
}
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
Map<String, Object> updateResult = (Map<String, Object>) data.get("update_user_book");
if (updateResult == null) return null;
String error = (String) updateResult.get("error");
if (error != null && !error.isBlank()) {
log.warn("update_user_book returned error: {}", error);
return null;
}
Map<String, Object> userBook = (Map<String, Object>) updateResult.get("user_book");
if (userBook == null) return null;
return UserBookWithReads.fromMap(userBook);
} catch (RestClientException e) {
log.error("Failed to update user_book: {}", e.getMessage());
}
return null;
}
/**
* Insert a new user_book_read entry for an existing user_book.
* This is used when there is no existing reading progress for the book, or when a new one should be created (e.g. user restarted the book).
* This also updates the user_book entry to set the edition_id and status_id based on the parameters, in case it was missing or needs to be updated.
* @param userBookId the ID of the existing user_book
* @param editionId the edition ID to use for the user_book_read entry
* @param progressPages the number of pages read to set in the user_book_read entry
* @param isFinished whether to set the user_book_read entry as finished
* @return true if the insert was successful, false otherwise
*/
private boolean insertUserBookRead(Integer userBookId, Integer editionId, Integer progressPages, boolean isFinished) {
String mutation = """
mutation InsertUserBookRead($userBookId: Int!, $userBookReadObject: DatesReadInput!) {
insert_user_book_read(user_book_id: $userBookId, user_book_read: $userBookReadObject) {
user_book_read {
id
}
error
}
}
""";
Map<String, Object> bookInput = new java.util.HashMap<>();
bookInput.put("edition_id", editionId);
bookInput.put("status_id", isFinished ? STATUS_READ : STATUS_CURRENTLY_READING);
Map<String, Object> readInput = new java.util.HashMap<>();
readInput.put("started_at", LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
readInput.put("progress_pages", progressPages);
@@ -582,12 +705,12 @@ public class HardcoverSyncService {
request.setQuery(mutation);
request.setVariables(Map.of(
"userBookId", userBookId,
"object", readInput
"userBookReadObject", readInput
));
try {
Map<String, Object> response = executeGraphQL(request);
log.info("insert_user_book_read response: {}", response);
log.trace("insert_user_book_read response: {}", response);
if (response == null) return false;
if (response.containsKey("errors")) {
@@ -595,59 +718,76 @@ public class HardcoverSyncService {
return false;
}
return true;
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return false;
Map<String, Object> insertResult = (Map<String, Object>) data.get("insert_user_book_read");
if (insertResult == null) return false;
String error = (String) insertResult.get("error");
if (error != null && !error.isBlank()) {
log.warn("insert_user_book_read returned error: {}", error);
return false;
}
return true;
} catch (RestClientException e) {
log.error("Failed to insert user_book_read: {}", e.getMessage());
return false;
}
return false;
}
private boolean updateUserBookRead(Integer readId, Integer editionId, int progressPages, boolean isFinished) {
/**
* Updates an existing user_book_read entry with new progress information. This is used when there is already reading progress for the book, and we want to update it with new progress (e.g. user continued reading).
* If the user_book_read is being updated to finished, the user_book status is automatically updated to "Read" by Hardcover.
* @param userBookId the ID of the existing user_book
* @param readInfo the entire user_book_read info. We need to pass the entire info because the API requires all fields to update, and we need to update the progress and finished_at fields based on the new progress.
* @return true if the update was successful, false otherwise
*/
private boolean updateUserBookRead(Integer userBookId, UserBookReadInfo readInfo) {
String mutation = """
mutation UpdateUserBookRead($id: Int!, $object: DatesReadInput!) {
update_user_book_read(id: $id, object: $object) {
user_book_read {
id
progress
mutation UpdateUserBookRead($userBookReadId: Int!, $userBookReadObject: DatesReadInput!) {
update_user_book_read(id: $userBookReadId, object: $userBookReadObject) {
id
error
}
error
}
}
""";
Map<String, Object> readInput = new java.util.HashMap<>();
readInput.put("progress_pages", progressPages);
if (isFinished) {
readInput.put("finished_at", LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
}
if (editionId != null) {
readInput.put("edition_id", editionId);
readInput.put("edition_id", readInfo.editionId);
readInput.put("started_at", readInfo.startedAt);
readInput.put("progress_pages", readInfo.progressPages);
if (readInfo.finishedAt != null) {
readInput.put("finished_at", readInfo.finishedAt);
}
GraphQLRequest request = new GraphQLRequest();
request.setQuery(mutation);
request.setVariables(Map.of(
"id", readId,
"object", readInput
"userBookReadId", readInfo.id,
"userBookReadObject", readInput
));
try {
Map<String, Object> response = executeGraphQL(request);
log.debug("update_user_book_read response: {}", response);
if (response == null) return false;
Map<String, Object> response = executeGraphQL(request);
if (response.containsKey("errors")) {
log.warn("update_user_book_read returned errors: {}", response.get("errors"));
return false;
}
return true;
} catch (RestClientException e) {
log.error("Failed to update user_book_read: {}", e.getMessage());
log.trace("update_user_book_read response: {}", response);
if (response == null) return false;
if (response.containsKey("errors")) {
log.warn("update_user_book_read returned errors: {}", response.get("errors"));
return false;
}
if (response.containsKey("data")) {
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data != null) {
Map<String, Object> updateUserBookReadResult = (Map<String, Object>) data.get("update_user_book_read");
if (updateUserBookReadResult != null && updateUserBookReadResult.get("error") != null) {
log.warn("update_user_book_read returned error: {}", updateUserBookReadResult.get("error"));
return false;
}
}
}
return true;
}
private Map<String, Object> executeGraphQL(GraphQLRequest request) {
@@ -668,7 +808,7 @@ public class HardcoverSyncService {
/**
* Helper method to safely extract Integer from various number types or strings.
*/
private Integer extractInteger(Object obj) {
private static Integer extractInteger(Object obj) {
if (obj == null) return null;
if (obj instanceof Number) {
return ((Number) obj).intValue();
@@ -683,6 +823,21 @@ public class HardcoverSyncService {
return null;
}
private static Float extractFloat(Object obj) {
if (obj == null) return null;
if (obj instanceof Number) {
return ((Number) obj).floatValue();
}
if (obj instanceof String) {
try {
return Float.parseFloat((String) obj);
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
/**
* Helper class to hold Hardcover book information.
*/
@@ -699,4 +854,44 @@ public class HardcoverSyncService {
Integer id;
Integer pages;
}
private static class UserBookWithReads {
Integer id;
Integer statusId;
Integer editionId;
List<UserBookReadInfo> reads;
static UserBookWithReads fromMap(Map<String, Object> userBook) {
UserBookWithReads result = new UserBookWithReads();
result.reads = new java.util.ArrayList<>();
result.id = extractInteger(userBook.get("id"));
result.statusId = extractInteger(userBook.get("status_id"));
result.editionId = extractInteger(userBook.get("edition_id"));
List<Map<String, Object>> reads = (List<Map<String, Object>>) userBook.get("user_book_reads");
if (reads != null) {
for (Map<String, Object> read : reads) {
UserBookReadInfo readInfo = new UserBookReadInfo();
readInfo.id = extractInteger(read.get("id"));
readInfo.editionId = extractInteger(read.get("edition_id"));
readInfo.startedAt = (String) read.get("started_at");
readInfo.finishedAt = (String) read.get("finished_at");
readInfo.progress = extractFloat(read.get("progress"));
readInfo.progressPages = extractInteger(read.get("progress_pages"));
result.reads.add(readInfo);
}
}
return result;
}
}
private static class UserBookReadInfo {
Integer id;
Integer editionId;
String startedAt;
String finishedAt;
Integer progressPages;
Float progress;
}
}
@@ -333,6 +333,132 @@ class HardcoverSyncServiceTest {
verify(restClient, never()).post();
}
// === Tests for sync behavior (after book resolution) ===
@Test
@DisplayName("Should skip progress update when book is already READ on Hardcover and progress is finished")
void syncProgressToHardcover_whenBookAlreadyReadAndProgressFinished_shouldSkip() {
testMetadata.setHardcoverBookId("12345");
testMetadata.setPageCount(300);
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createGetUserBookAndReadsResponse(5001, 3, 10, List.of()));
service.syncProgressToHardcover(TEST_BOOK_ID, 99.0f, TEST_USER_ID);
// Resolves book (1) + fetches user book (2), then skips — no insert/update calls
verify(restClient, times(2)).post();
}
@Test
@DisplayName("Should proceed when book is READ but progress is not finished")
void syncProgressToHardcover_whenBookAlreadyReadAndProgressNotFinished_shouldProceed() {
testMetadata.setHardcoverBookId("12345");
testMetadata.setPageCount(300);
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createGetUserBookAndReadsResponse(5001, 3, 10, List.of()))
.thenReturn(createUpdateUserBookResponse(5001, 2, 10, List.of()))
.thenReturn(createInsertUserBookReadResponse());
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
// More than 2 API calls — did not skip
verify(restClient, atLeast(3)).post();
}
@Test
@DisplayName("Should skip when resolved book has zero pages")
void syncProgressToHardcover_whenResolvedBookHasZeroPages_shouldSkip() {
testMetadata.setHardcoverBookId("12345");
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 0, edition(10, 0), null, null));
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
// Only resolveHardcoverBook is called; page guard returns early
verify(restClient, times(1)).post();
}
@Test
@DisplayName("Should call updateUserBook when user_book exists but status is not CURRENTLY_READING")
void syncProgressToHardcover_whenUserBookExistsWithWantToReadStatus_shouldCallUpdateUserBook() {
testMetadata.setHardcoverBookId("12345");
testMetadata.setPageCount(300);
// Status 1 = Want to Read (not currently reading, not read)
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createGetUserBookAndReadsResponse(5001, 1, 10, List.of()))
.thenReturn(createUpdateUserBookResponse(5001, 2, 10, List.of()))
.thenReturn(createInsertUserBookReadResponse());
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
// Resolve (1) + getUserBookAndReads (2) + updateUserBook (3) + insertUserBookRead (4)
verify(restClient, times(4)).post();
}
@Test
@DisplayName("Should update existing read when currently reading and edition matches")
void syncProgressToHardcover_whenCurrentlyReadingWithMatchingEdition_shouldUpdateRead() {
testMetadata.setHardcoverBookId("12345");
testMetadata.setPageCount(300);
Map<String, Object> existingRead = existingUserBookRead(6001, 10, "2024-01-01", null, 50);
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createGetUserBookAndReadsResponse(5001, 2, 10, List.of(existingRead)))
.thenReturn(createUpdateUserBookReadResponse());
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
// Resolve (1) + getUserBookAndReads (2) + updateUserBookRead (3)
verify(restClient, times(3)).post();
}
@Test
@DisplayName("Should insert new read when currently reading but edition does not match")
void syncProgressToHardcover_whenCurrentlyReadingWithDifferentEdition_shouldInsertRead() {
testMetadata.setHardcoverBookId("12345");
testMetadata.setPageCount(300);
// Existing read has edition_id=99, but resolved edition is 10 — no match
Map<String, Object> existingRead = existingUserBookRead(6001, 99, "2024-01-01", null, 50);
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createGetUserBookAndReadsResponse(5001, 2, 10, List.of(existingRead)))
.thenReturn(createInsertUserBookReadResponse());
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
// Resolve (1) + getUserBookAndReads (2) + insertUserBookRead (3)
verify(restClient, times(3)).post();
}
@Test
@DisplayName("Should abort sync when insertUserBook returns null")
void syncProgressToHardcover_whenInsertUserBookFails_shouldAbortSync() {
testMetadata.setHardcoverBookId("12345");
testMetadata.setPageCount(300);
// getUserBookAndReads returns no user_book; insertUserBook also returns null (empty response)
when(responseSpec.body(Map.class))
.thenReturn(createBookByIdResponse(12345, 300, edition(10, 300), null, null))
.thenReturn(createEmptyBooksResponse()) // getUserBookAndReads: no me entry -> null
.thenReturn(null); // insertUserBook: null response -> null
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
// Resolve (1) + getUserBookAndReads (2) + insertUserBook attempt (3) — then stops
verify(restClient, times(3)).post();
}
// === resolveHardcoverBook ===
@Test
@DisplayName("Returns null when all identifiers are blank")
@@ -587,4 +713,55 @@ class HardcoverSyncServiceTest {
field.setAccessible(true);
return (Integer) field.get(target);
}
/**
* Creates a mock response for the getUserBookAndReads query.
* The Hardcover API returns 'me' as a list; this matches that structure.
*/
private Map<String, Object> createGetUserBookAndReadsResponse(
Integer userBookId, Integer statusId, Integer editionId,
List<Map<String, Object>> reads) {
Map<String, Object> userBook = new HashMap<>();
if (userBookId != null) userBook.put("id", userBookId);
if (statusId != null) userBook.put("status_id", statusId);
if (editionId != null) userBook.put("edition_id", editionId);
userBook.put("user_book_reads", reads != null ? reads : List.of());
Map<String, Object> me = new HashMap<>();
me.put("user_books", List.of(userBook));
return Map.of("data", Map.of("me", List.of(me)));
}
/**
* Creates a mock response for the updateUserBook mutation.
*/
private Map<String, Object> createUpdateUserBookResponse(
Integer userBookId, Integer statusId, Integer editionId,
List<Map<String, Object>> reads) {
Map<String, Object> userBook = new HashMap<>();
if (userBookId != null) userBook.put("id", userBookId);
if (statusId != null) userBook.put("status_id", statusId);
if (editionId != null) userBook.put("edition_id", editionId);
userBook.put("user_book_reads", reads != null ? reads : List.of());
Map<String, Object> updateResult = new HashMap<>();
updateResult.put("user_book", userBook);
return Map.of("data", Map.of("update_user_book", updateResult));
}
/**
* Builds a user_book_read map as returned inside getUserBookAndReads.
*/
private Map<String, Object> existingUserBookRead(
Integer id, Integer editionId, String startedAt, String finishedAt, Integer progressPages) {
Map<String, Object> read = new HashMap<>();
if (id != null) read.put("id", id);
if (editionId != null) read.put("edition_id", editionId);
if (startedAt != null) read.put("started_at", startedAt);
if (finishedAt != null) read.put("finished_at", finishedAt);
if (progressPages != null) read.put("progress_pages", progressPages);
return read;
}
}