feat(mobile): add author and series endpoints
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package org.booklore.mobile.controller;
|
||||
|
||||
import org.booklore.mobile.dto.MobileAuthorDetail;
|
||||
import org.booklore.mobile.dto.MobileAuthorSummary;
|
||||
import org.booklore.mobile.dto.MobilePageResponse;
|
||||
import org.booklore.mobile.service.MobileAuthorService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/mobile/v1/authors")
|
||||
@Tag(name = "Mobile Authors", description = "Mobile-optimized endpoints for browsing authors")
|
||||
public class MobileAuthorController {
|
||||
|
||||
private final MobileAuthorService mobileAuthorService;
|
||||
|
||||
@Operation(summary = "Get paginated author list",
|
||||
description = "Retrieve a paginated list of authors with optional filtering by library, search text, and photo availability.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Authors retrieved successfully"),
|
||||
@ApiResponse(responseCode = "403", description = "Access denied")
|
||||
})
|
||||
@GetMapping
|
||||
public ResponseEntity<MobilePageResponse<MobileAuthorSummary>> getAuthors(
|
||||
@Parameter(description = "Page number (0-indexed)") @RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@Parameter(description = "Page size (max 50)") @RequestParam(required = false, defaultValue = "30") Integer size,
|
||||
@Parameter(description = "Sort field (name, bookCount, recent)") @RequestParam(required = false, defaultValue = "name") String sort,
|
||||
@Parameter(description = "Sort direction (asc, desc)") @RequestParam(required = false, defaultValue = "asc") String dir,
|
||||
@Parameter(description = "Filter by library ID") @RequestParam(required = false) Long libraryId,
|
||||
@Parameter(description = "Search by author name") @RequestParam(required = false) String search,
|
||||
@Parameter(description = "Filter by photo availability") @RequestParam(required = false) Boolean hasPhoto) {
|
||||
|
||||
return ResponseEntity.ok(mobileAuthorService.getAuthors(page, size, sort, dir, libraryId, search, hasPhoto));
|
||||
}
|
||||
|
||||
@Operation(summary = "Get author details",
|
||||
description = "Retrieve full details for a specific author including description and book count.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Author details retrieved successfully"),
|
||||
@ApiResponse(responseCode = "403", description = "Access denied"),
|
||||
@ApiResponse(responseCode = "404", description = "Author not found")
|
||||
})
|
||||
@GetMapping("/{authorId}")
|
||||
public ResponseEntity<MobileAuthorDetail> getAuthorDetail(
|
||||
@Parameter(description = "Author ID") @PathVariable Long authorId) {
|
||||
|
||||
return ResponseEntity.ok(mobileAuthorService.getAuthorDetail(authorId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.booklore.mobile.controller;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.mobile.dto.MobileBookSummary;
|
||||
import org.booklore.mobile.dto.MobilePageResponse;
|
||||
import org.booklore.mobile.dto.MobileSeriesSummary;
|
||||
import org.booklore.mobile.service.MobileSeriesService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/mobile/v1/series")
|
||||
public class MobileSeriesController {
|
||||
|
||||
private final MobileSeriesService mobileSeriesService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<MobilePageResponse<MobileSeriesSummary>> getSeries(
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size,
|
||||
@RequestParam(required = false, defaultValue = "recentlyAdded") String sort,
|
||||
@RequestParam(required = false, defaultValue = "desc") String dir,
|
||||
@RequestParam(required = false) Long libraryId,
|
||||
@RequestParam(required = false) String search,
|
||||
@RequestParam(required = false) String status) {
|
||||
|
||||
boolean inProgressOnly = "in-progress".equalsIgnoreCase(status);
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> response = mobileSeriesService.getSeries(
|
||||
page, size, sort, dir, libraryId, search, inProgressOnly);
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@GetMapping("/{seriesName}/books")
|
||||
public ResponseEntity<MobilePageResponse<MobileBookSummary>> getSeriesBooks(
|
||||
@PathVariable String seriesName,
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size,
|
||||
@RequestParam(required = false, defaultValue = "seriesNumber") String sort,
|
||||
@RequestParam(required = false, defaultValue = "asc") String dir,
|
||||
@RequestParam(required = false) Long libraryId) {
|
||||
|
||||
MobilePageResponse<MobileBookSummary> response = mobileSeriesService.getSeriesBooks(
|
||||
seriesName, page, size, sort, dir, libraryId);
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.booklore.mobile.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class MobileAuthorDetail {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String asin;
|
||||
private int bookCount;
|
||||
private boolean hasPhoto;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.booklore.mobile.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class MobileAuthorSummary {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String asin;
|
||||
private int bookCount;
|
||||
private boolean hasPhoto;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.booklore.mobile.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class MobileSeriesSummary {
|
||||
private String seriesName;
|
||||
private int bookCount;
|
||||
private Integer seriesTotal;
|
||||
private List<String> authors;
|
||||
private int booksRead;
|
||||
private Instant latestAddedOn;
|
||||
private List<SeriesCoverBook> coverBooks;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.booklore.mobile.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class SeriesCoverBook {
|
||||
private Long bookId;
|
||||
private Instant coverUpdatedOn;
|
||||
private Float seriesNumber;
|
||||
private String primaryFileType;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package org.booklore.mobile.service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.mobile.dto.MobileAuthorDetail;
|
||||
import org.booklore.mobile.dto.MobileAuthorSummary;
|
||||
import org.booklore.mobile.dto.MobilePageResponse;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.repository.AuthorRepository;
|
||||
import org.booklore.util.FileService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.TypedQuery;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class MobileAuthorService {
|
||||
|
||||
private static final int DEFAULT_PAGE_SIZE = 30;
|
||||
private static final int MAX_PAGE_SIZE = 50;
|
||||
|
||||
private final AuthorRepository authorRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final FileService fileService;
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MobilePageResponse<MobileAuthorSummary> getAuthors(
|
||||
Integer page,
|
||||
Integer size,
|
||||
String sortBy,
|
||||
String sortDir,
|
||||
Long libraryId,
|
||||
String search,
|
||||
Boolean hasPhoto) {
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
|
||||
|
||||
int pageNum = page != null && page >= 0 ? page : 0;
|
||||
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
|
||||
|
||||
StringBuilder whereClause = new StringBuilder(" WHERE (1=1)");
|
||||
buildLibraryFilter(whereClause, accessibleLibraryIds, libraryId);
|
||||
buildSearchFilter(whereClause, search);
|
||||
|
||||
String fromClause = " FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm LEFT JOIN bm.book b";
|
||||
|
||||
// Count query
|
||||
String countJpql = "SELECT COUNT(DISTINCT a.id)" + fromClause + whereClause;
|
||||
TypedQuery<Long> countQuery = entityManager.createQuery(countJpql, Long.class);
|
||||
setQueryParams(countQuery, accessibleLibraryIds, libraryId, search);
|
||||
long totalElements = countQuery.getSingleResult();
|
||||
|
||||
if (totalElements == 0) {
|
||||
return MobilePageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
|
||||
}
|
||||
|
||||
// Data query with book count
|
||||
String orderClause = buildOrderClause(sortBy, sortDir);
|
||||
String dataJpql = "SELECT a, COUNT(DISTINCT bm.id)" + fromClause + whereClause
|
||||
+ " GROUP BY a" + orderClause;
|
||||
TypedQuery<Object[]> dataQuery = entityManager.createQuery(dataJpql, Object[].class);
|
||||
setQueryParams(dataQuery, accessibleLibraryIds, libraryId, search);
|
||||
dataQuery.setFirstResult(pageNum * pageSize);
|
||||
dataQuery.setMaxResults(pageSize);
|
||||
|
||||
List<Object[]> results = dataQuery.getResultList();
|
||||
|
||||
List<MobileAuthorSummary> summaries = results.stream()
|
||||
.map(row -> {
|
||||
AuthorEntity author = (AuthorEntity) row[0];
|
||||
long bookCount = (Long) row[1];
|
||||
boolean authorHasPhoto = Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId())));
|
||||
return MobileAuthorSummary.builder()
|
||||
.id(author.getId())
|
||||
.name(author.getName())
|
||||
.asin(author.getAsin())
|
||||
.bookCount((int) bookCount)
|
||||
.hasPhoto(authorHasPhoto)
|
||||
.build();
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Post-filter by hasPhoto if requested
|
||||
if (hasPhoto != null) {
|
||||
summaries = summaries.stream()
|
||||
.filter(s -> s.isHasPhoto() == hasPhoto)
|
||||
.collect(Collectors.toList());
|
||||
// Adjust total count for hasPhoto filter — requires a separate count
|
||||
long filteredTotal = countAuthorsWithPhotoFilter(accessibleLibraryIds, libraryId, search, hasPhoto);
|
||||
return MobilePageResponse.of(summaries, pageNum, pageSize, filteredTotal);
|
||||
}
|
||||
|
||||
return MobilePageResponse.of(summaries, pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MobileAuthorDetail getAuthorDetail(Long authorId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
|
||||
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
|
||||
// Verify access for non-admin users
|
||||
if (accessibleLibraryIds != null) {
|
||||
if (accessibleLibraryIds.isEmpty() || !authorRepository.existsByIdAndLibraryIds(authorId, accessibleLibraryIds)) {
|
||||
throw ApiError.AUTHOR_NOT_FOUND.createException(authorId);
|
||||
}
|
||||
}
|
||||
|
||||
// Count books accessible to this user
|
||||
int bookCount = countAccessibleBooks(authorId, accessibleLibraryIds);
|
||||
boolean authorHasPhoto = Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId())));
|
||||
|
||||
return MobileAuthorDetail.builder()
|
||||
.id(author.getId())
|
||||
.name(author.getName())
|
||||
.description(author.getDescription())
|
||||
.asin(author.getAsin())
|
||||
.bookCount(bookCount)
|
||||
.hasPhoto(authorHasPhoto)
|
||||
.build();
|
||||
}
|
||||
|
||||
private int countAccessibleBooks(Long authorId, Set<Long> accessibleLibraryIds) {
|
||||
StringBuilder jpql = new StringBuilder(
|
||||
"SELECT COUNT(DISTINCT bm.id) FROM AuthorEntity a JOIN a.bookMetadataEntityList bm JOIN bm.book b"
|
||||
+ " WHERE a.id = :authorId AND (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)");
|
||||
if (accessibleLibraryIds != null) {
|
||||
jpql.append(" AND b.library.id IN :libraryIds");
|
||||
}
|
||||
TypedQuery<Long> query = entityManager.createQuery(jpql.toString(), Long.class);
|
||||
query.setParameter("authorId", authorId);
|
||||
if (accessibleLibraryIds != null) {
|
||||
query.setParameter("libraryIds", accessibleLibraryIds);
|
||||
}
|
||||
return query.getSingleResult().intValue();
|
||||
}
|
||||
|
||||
private long countAuthorsWithPhotoFilter(Set<Long> accessibleLibraryIds, Long libraryId, String search, boolean hasPhoto) {
|
||||
// Since hasPhoto is file-system based, we need to count all matching authors
|
||||
// and check their photos. For large datasets this could be optimized with a DB column.
|
||||
StringBuilder whereClause = new StringBuilder(" WHERE (1=1)");
|
||||
buildLibraryFilter(whereClause, accessibleLibraryIds, libraryId);
|
||||
buildSearchFilter(whereClause, search);
|
||||
|
||||
String jpql = "SELECT DISTINCT a FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm LEFT JOIN bm.book b"
|
||||
+ whereClause;
|
||||
TypedQuery<AuthorEntity> query = entityManager.createQuery(jpql, AuthorEntity.class);
|
||||
setQueryParams(query, accessibleLibraryIds, libraryId, search);
|
||||
|
||||
return query.getResultList().stream()
|
||||
.filter(a -> Files.exists(Paths.get(fileService.getAuthorThumbnailFile(a.getId()))) == hasPhoto)
|
||||
.count();
|
||||
}
|
||||
|
||||
private void buildLibraryFilter(StringBuilder whereClause, Set<Long> accessibleLibraryIds, Long libraryId) {
|
||||
if (libraryId != null) {
|
||||
whereClause.append(" AND b.library.id = :libraryId");
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
whereClause.append(" AND b.library.id IN :libraryIds");
|
||||
}
|
||||
// Always filter out deleted/physical books when library filtering
|
||||
whereClause.append(" AND (b.deleted IS NULL OR b.deleted = false)");
|
||||
whereClause.append(" AND (b.isPhysical IS NULL OR b.isPhysical = false)");
|
||||
}
|
||||
|
||||
private void buildSearchFilter(StringBuilder whereClause, String search) {
|
||||
if (search != null && !search.trim().isEmpty()) {
|
||||
whereClause.append(" AND LOWER(a.name) LIKE :search");
|
||||
}
|
||||
}
|
||||
|
||||
private String buildOrderClause(String sortBy, String sortDir) {
|
||||
String direction = "asc".equalsIgnoreCase(sortDir) ? "ASC" : "DESC";
|
||||
String field = switch (sortBy != null ? sortBy.toLowerCase() : "") {
|
||||
case "name" -> "a.name";
|
||||
case "bookcount", "book_count" -> "COUNT(DISTINCT bm.id)";
|
||||
case "recent", "id" -> "a.id";
|
||||
default -> "a.name";
|
||||
};
|
||||
return " ORDER BY " + field + " " + direction;
|
||||
}
|
||||
|
||||
private void setQueryParams(TypedQuery<?> query, Set<Long> accessibleLibraryIds, Long libraryId, String search) {
|
||||
if (libraryId != null) {
|
||||
query.setParameter("libraryId", libraryId);
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
query.setParameter("libraryIds", accessibleLibraryIds);
|
||||
}
|
||||
if (search != null && !search.trim().isEmpty()) {
|
||||
query.setParameter("search", "%" + search.trim().toLowerCase() + "%");
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> getAccessibleLibraryIds(BookLoreUser user) {
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
return null;
|
||||
}
|
||||
if (user.getAssignedLibraries() == null || user.getAssignedLibraries().isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
package org.booklore.mobile.service;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.Tuple;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.mobile.dto.*;
|
||||
import org.booklore.mobile.mapper.MobileBookMapper;
|
||||
import org.booklore.mobile.specification.MobileBookSpecification;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.UserBookProgressRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class MobileSeriesService {
|
||||
|
||||
private static final int DEFAULT_PAGE_SIZE = 20;
|
||||
private static final int MAX_PAGE_SIZE = 50;
|
||||
|
||||
private final EntityManager entityManager;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final MobileBookMapper mobileBookMapper;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MobilePageResponse<MobileSeriesSummary> getSeries(
|
||||
Integer page,
|
||||
Integer size,
|
||||
String sortBy,
|
||||
String sortDir,
|
||||
Long libraryId,
|
||||
String search,
|
||||
boolean inProgressOnly) {
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
|
||||
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(accessibleLibraryIds, libraryId);
|
||||
}
|
||||
|
||||
int pageNum = page != null && page >= 0 ? page : 0;
|
||||
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
|
||||
|
||||
// Build WHERE clause fragments
|
||||
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
|
||||
String searchClause = (search != null && !search.trim().isEmpty())
|
||||
? " AND LOWER(m.seriesName) LIKE :searchPattern"
|
||||
: "";
|
||||
|
||||
String havingClause = inProgressOnly
|
||||
? " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0"
|
||||
: "";
|
||||
|
||||
String orderBy = buildSeriesOrderBy(sortBy, sortDir, inProgressOnly);
|
||||
|
||||
// Phase 1: Aggregate query
|
||||
String aggregateQuery = "SELECT m.seriesName, COUNT(b.id), MAX(m.seriesTotal), MAX(b.addedOn),"
|
||||
+ " SUM(CASE WHEN p.readStatus = org.booklore.model.enums.ReadStatus.READ THEN 1 ELSE 0 END)"
|
||||
+ (inProgressOnly ? ", MAX(p.lastReadTime)" : "")
|
||||
+ " FROM BookEntity b JOIN b.metadata m"
|
||||
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
|
||||
+ " AND m.seriesName IS NOT NULL"
|
||||
+ libraryClause
|
||||
+ searchClause
|
||||
+ " GROUP BY m.seriesName"
|
||||
+ havingClause
|
||||
+ " ORDER BY " + orderBy;
|
||||
|
||||
var aggregateQ = entityManager.createQuery(aggregateQuery, Tuple.class);
|
||||
aggregateQ.setParameter("userId", userId);
|
||||
setLibraryParams(aggregateQ, accessibleLibraryIds, libraryId);
|
||||
if (!searchClause.isEmpty()) {
|
||||
aggregateQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
|
||||
}
|
||||
aggregateQ.setFirstResult(pageNum * pageSize);
|
||||
aggregateQ.setMaxResults(pageSize);
|
||||
|
||||
List<Tuple> aggregateResults = aggregateQ.getResultList();
|
||||
|
||||
// Count query
|
||||
String countQuery = "SELECT COUNT(DISTINCT m.seriesName) FROM BookEntity b JOIN b.metadata m"
|
||||
+ (inProgressOnly ? " LEFT JOIN b.userBookProgress p ON p.user.id = :userId" : "")
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
|
||||
+ " AND m.seriesName IS NOT NULL"
|
||||
+ libraryClause
|
||||
+ searchClause;
|
||||
|
||||
if (inProgressOnly) {
|
||||
// For in-progress, we need the HAVING filter in the count — use a subquery approach
|
||||
String countWithHaving = "SELECT COUNT(*) FROM ("
|
||||
+ "SELECT m.seriesName FROM BookEntity b JOIN b.metadata m"
|
||||
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
|
||||
+ " AND m.seriesName IS NOT NULL"
|
||||
+ libraryClause
|
||||
+ searchClause
|
||||
+ " GROUP BY m.seriesName"
|
||||
+ " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0"
|
||||
+ ")";
|
||||
// JPQL doesn't support subqueries in FROM — count via result list size instead
|
||||
String countAlt = "SELECT m.seriesName FROM BookEntity b JOIN b.metadata m"
|
||||
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
|
||||
+ " AND m.seriesName IS NOT NULL"
|
||||
+ libraryClause
|
||||
+ searchClause
|
||||
+ " GROUP BY m.seriesName"
|
||||
+ " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0";
|
||||
var countQ = entityManager.createQuery(countAlt, String.class);
|
||||
countQ.setParameter("userId", userId);
|
||||
setLibraryParams(countQ, accessibleLibraryIds, libraryId);
|
||||
if (!searchClause.isEmpty()) {
|
||||
countQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
|
||||
}
|
||||
long totalElements = countQ.getResultList().size();
|
||||
return buildSeriesPage(aggregateResults, userId, accessibleLibraryIds, libraryId, inProgressOnly, pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
var countQ = entityManager.createQuery(countQuery, Long.class);
|
||||
if (inProgressOnly) {
|
||||
countQ.setParameter("userId", userId);
|
||||
}
|
||||
setLibraryParams(countQ, accessibleLibraryIds, libraryId);
|
||||
if (!searchClause.isEmpty()) {
|
||||
countQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
|
||||
}
|
||||
long totalElements = countQ.getSingleResult();
|
||||
|
||||
return buildSeriesPage(aggregateResults, userId, accessibleLibraryIds, libraryId, inProgressOnly, pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
private MobilePageResponse<MobileSeriesSummary> buildSeriesPage(
|
||||
List<Tuple> aggregateResults,
|
||||
Long userId,
|
||||
Set<Long> accessibleLibraryIds,
|
||||
Long libraryId,
|
||||
boolean inProgressOnly,
|
||||
int pageNum,
|
||||
int pageSize,
|
||||
long totalElements) {
|
||||
|
||||
if (aggregateResults.isEmpty()) {
|
||||
return MobilePageResponse.of(Collections.emptyList(), pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
List<String> seriesNames = aggregateResults.stream()
|
||||
.map(t -> t.get(0, String.class))
|
||||
.toList();
|
||||
|
||||
// Phase 2: Fetch books for enrichment
|
||||
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
|
||||
String booksQuery = "SELECT b FROM BookEntity b"
|
||||
+ " JOIN FETCH b.metadata m LEFT JOIN FETCH m.authors"
|
||||
+ " LEFT JOIN FETCH b.bookFiles"
|
||||
+ " WHERE m.seriesName IN :seriesNames"
|
||||
+ " AND (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
|
||||
+ libraryClause;
|
||||
|
||||
var booksQ = entityManager.createQuery(booksQuery, BookEntity.class);
|
||||
booksQ.setParameter("seriesNames", seriesNames);
|
||||
setLibraryParams(booksQ, accessibleLibraryIds, libraryId);
|
||||
|
||||
List<BookEntity> books = booksQ.getResultList();
|
||||
|
||||
// Group books by series name
|
||||
Map<String, List<BookEntity>> booksBySeries = books.stream()
|
||||
.collect(Collectors.groupingBy(b -> b.getMetadata().getSeriesName()));
|
||||
|
||||
// Build aggregates map from Phase 1
|
||||
Map<String, Tuple> aggregateMap = new LinkedHashMap<>();
|
||||
for (Tuple t : aggregateResults) {
|
||||
aggregateMap.put(t.get(0, String.class), t);
|
||||
}
|
||||
|
||||
// Merge into summaries, preserving Phase 1 order
|
||||
List<MobileSeriesSummary> summaries = new ArrayList<>();
|
||||
for (String seriesName : seriesNames) {
|
||||
Tuple agg = aggregateMap.get(seriesName);
|
||||
List<BookEntity> seriesBooks = booksBySeries.getOrDefault(seriesName, Collections.emptyList());
|
||||
|
||||
// Distinct authors across all books in series
|
||||
List<String> authors = seriesBooks.stream()
|
||||
.filter(b -> b.getMetadata() != null && b.getMetadata().getAuthors() != null)
|
||||
.flatMap(b -> b.getMetadata().getAuthors().stream())
|
||||
.map(AuthorEntity::getName)
|
||||
.distinct()
|
||||
.toList();
|
||||
|
||||
// Cover books sorted by seriesNumber ASC nulls last
|
||||
List<SeriesCoverBook> coverBooks = seriesBooks.stream()
|
||||
.sorted(Comparator.comparing(
|
||||
(BookEntity b) -> b.getMetadata().getSeriesNumber(),
|
||||
Comparator.nullsLast(Comparator.naturalOrder())))
|
||||
.map(b -> {
|
||||
BookFileEntity primaryFile = b.getPrimaryBookFile();
|
||||
String fileType = (primaryFile != null && primaryFile.getBookType() != null)
|
||||
? primaryFile.getBookType().name()
|
||||
: null;
|
||||
return SeriesCoverBook.builder()
|
||||
.bookId(b.getId())
|
||||
.coverUpdatedOn(b.getMetadata().getCoverUpdatedOn())
|
||||
.seriesNumber(b.getMetadata().getSeriesNumber())
|
||||
.primaryFileType(fileType)
|
||||
.build();
|
||||
})
|
||||
.toList();
|
||||
|
||||
Long booksReadLong = agg.get(4, Long.class);
|
||||
int booksRead = booksReadLong != null ? booksReadLong.intValue() : 0;
|
||||
|
||||
summaries.add(MobileSeriesSummary.builder()
|
||||
.seriesName(agg.get(0, String.class))
|
||||
.bookCount(agg.get(1, Long.class).intValue())
|
||||
.seriesTotal(agg.get(2, Integer.class))
|
||||
.latestAddedOn(agg.get(3, Instant.class))
|
||||
.booksRead(booksRead)
|
||||
.authors(authors)
|
||||
.coverBooks(coverBooks)
|
||||
.build());
|
||||
}
|
||||
|
||||
return MobilePageResponse.of(summaries, pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MobilePageResponse<MobileBookSummary> getSeriesBooks(
|
||||
String seriesName,
|
||||
Integer page,
|
||||
Integer size,
|
||||
String sortBy,
|
||||
String sortDir,
|
||||
Long libraryId) {
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
|
||||
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(accessibleLibraryIds, libraryId);
|
||||
}
|
||||
|
||||
int pageNum = page != null && page >= 0 ? page : 0;
|
||||
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
|
||||
|
||||
Sort sort = buildBookSort(sortBy, sortDir);
|
||||
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
|
||||
|
||||
Specification<BookEntity> spec = buildSeriesBooksSpec(accessibleLibraryIds, libraryId, seriesName);
|
||||
|
||||
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
|
||||
|
||||
Set<Long> bookIds = bookPage.getContent().stream()
|
||||
.map(BookEntity::getId)
|
||||
.collect(Collectors.toSet());
|
||||
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, bookIds);
|
||||
|
||||
List<MobileBookSummary> summaries = bookPage.getContent().stream()
|
||||
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
|
||||
.toList();
|
||||
|
||||
return MobilePageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
|
||||
}
|
||||
|
||||
// --- Access control helpers (duplicated from MobileBookService to minimize blast radius) ---
|
||||
|
||||
private Set<Long> getAccessibleLibraryIds(BookLoreUser user) {
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
return null;
|
||||
}
|
||||
if (user.getAssignedLibraries() == null || user.getAssignedLibraries().isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private void validateLibraryAccess(Set<Long> accessibleLibraryIds, Long libraryId) {
|
||||
if (accessibleLibraryIds != null && !accessibleLibraryIds.contains(libraryId)) {
|
||||
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Query helpers ---
|
||||
|
||||
private String buildLibraryClause(Set<Long> accessibleLibraryIds, Long libraryId) {
|
||||
if (libraryId != null) {
|
||||
return " AND b.library.id = :libraryId";
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
return " AND b.library.id IN :libraryIds";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private void setLibraryParams(jakarta.persistence.Query query, Set<Long> accessibleLibraryIds, Long libraryId) {
|
||||
if (libraryId != null) {
|
||||
query.setParameter("libraryId", libraryId);
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
query.setParameter("libraryIds", accessibleLibraryIds);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildSeriesOrderBy(String sortBy, String sortDir, boolean inProgressOnly) {
|
||||
String dir = "asc".equalsIgnoreCase(sortDir) ? "ASC" : "DESC";
|
||||
String nullsClause = "ASC".equals(dir) ? " NULLS LAST" : " NULLS FIRST";
|
||||
|
||||
return switch (sortBy != null ? sortBy.toLowerCase() : "") {
|
||||
case "name" -> "m.seriesName " + dir;
|
||||
case "bookcount" -> "COUNT(b.id) " + dir;
|
||||
case "readprogress" -> "SUM(CASE WHEN p.readStatus = org.booklore.model.enums.ReadStatus.READ THEN 1 ELSE 0 END) " + dir;
|
||||
case "lastreadtime" -> {
|
||||
if (inProgressOnly) {
|
||||
yield "MAX(p.lastReadTime) " + dir + nullsClause;
|
||||
}
|
||||
yield "MAX(b.addedOn) " + dir + nullsClause;
|
||||
}
|
||||
default -> {
|
||||
if (inProgressOnly) {
|
||||
yield "MAX(p.lastReadTime) " + dir + nullsClause;
|
||||
}
|
||||
yield "MAX(b.addedOn) " + dir + nullsClause;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private Sort buildBookSort(String sortBy, String sortDir) {
|
||||
Sort.Direction direction = "asc".equalsIgnoreCase(sortDir) ? Sort.Direction.ASC : Sort.Direction.DESC;
|
||||
String field = switch (sortBy != null ? sortBy.toLowerCase() : "") {
|
||||
case "title" -> "metadata.title";
|
||||
case "seriesnumber" -> "metadata.seriesNumber";
|
||||
case "recentlyadded" -> "addedOn";
|
||||
default -> "metadata.seriesNumber";
|
||||
};
|
||||
return Sort.by(direction, field);
|
||||
}
|
||||
|
||||
private Specification<BookEntity> buildSeriesBooksSpec(Set<Long> accessibleLibraryIds, Long libraryId, String seriesName) {
|
||||
List<Specification<BookEntity>> specs = new ArrayList<>();
|
||||
specs.add(MobileBookSpecification.notDeleted());
|
||||
specs.add(MobileBookSpecification.hasDigitalFile());
|
||||
specs.add(MobileBookSpecification.inSeries(seriesName));
|
||||
|
||||
if (accessibleLibraryIds != null) {
|
||||
specs.add(libraryId != null
|
||||
? MobileBookSpecification.inLibrary(libraryId)
|
||||
: MobileBookSpecification.inLibraries(accessibleLibraryIds));
|
||||
} else if (libraryId != null) {
|
||||
specs.add(MobileBookSpecification.inLibrary(libraryId));
|
||||
}
|
||||
|
||||
return MobileBookSpecification.combine(specs.toArray(new Specification[0]));
|
||||
}
|
||||
|
||||
private Map<Long, UserBookProgressEntity> getProgressMap(Long userId, Set<Long> bookIds) {
|
||||
if (bookIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream()
|
||||
.collect(Collectors.toMap(
|
||||
p -> p.getBook().getId(),
|
||||
Function.identity()
|
||||
));
|
||||
}
|
||||
}
|
||||
+10
@@ -229,6 +229,16 @@ public class MobileBookSpecification {
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inSeries(String seriesName) {
|
||||
return (root, query, cb) -> {
|
||||
if (seriesName == null || seriesName.trim().isEmpty()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
|
||||
return cb.equal(metadataJoin.get("seriesName"), seriesName);
|
||||
};
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static Specification<BookEntity> combine(Specification<BookEntity>... specs) {
|
||||
Specification<BookEntity> result = (root, query, cb) -> cb.conjunction();
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package org.booklore.mobile.controller;
|
||||
|
||||
import org.booklore.mobile.dto.*;
|
||||
import org.booklore.mobile.service.MobileSeriesService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MobileSeriesControllerTest {
|
||||
|
||||
@Mock
|
||||
private MobileSeriesService mobileSeriesService;
|
||||
|
||||
@InjectMocks
|
||||
private MobileSeriesController controller;
|
||||
|
||||
@Test
|
||||
void getSeries_defaultParams_delegatesCorrectly() {
|
||||
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
|
||||
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, false))
|
||||
.thenReturn(expected);
|
||||
|
||||
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
|
||||
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, null);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertSame(expected, response.getBody());
|
||||
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", null, null, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_withLibraryId_passesLibraryId() {
|
||||
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
|
||||
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", 5L, null, false))
|
||||
.thenReturn(expected);
|
||||
|
||||
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
|
||||
controller.getSeries(0, 20, "recentlyAdded", "desc", 5L, null, null);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", 5L, null, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_withSearch_passesSearch() {
|
||||
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
|
||||
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, "harry", false))
|
||||
.thenReturn(expected);
|
||||
|
||||
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
|
||||
controller.getSeries(0, 20, "recentlyAdded", "desc", null, "harry", null);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", null, "harry", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_withInProgressStatus_setsInProgressTrue() {
|
||||
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
|
||||
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, true))
|
||||
.thenReturn(expected);
|
||||
|
||||
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
|
||||
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, "in-progress");
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", null, null, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_withUnknownStatus_treatedAsNotInProgress() {
|
||||
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
|
||||
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, false))
|
||||
.thenReturn(expected);
|
||||
|
||||
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
|
||||
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, "completed");
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", null, null, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_defaultParams_delegatesCorrectly() {
|
||||
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
|
||||
when(mobileSeriesService.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", null))
|
||||
.thenReturn(expected);
|
||||
|
||||
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
|
||||
controller.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", null);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertSame(expected, response.getBody());
|
||||
verify(mobileSeriesService).getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_withLibraryId_passesLibraryId() {
|
||||
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
|
||||
when(mobileSeriesService.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", 5L))
|
||||
.thenReturn(expected);
|
||||
|
||||
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
|
||||
controller.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", 5L);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(mobileSeriesService).getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", 5L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_encodedSeriesName_passedAsIs() {
|
||||
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
|
||||
when(mobileSeriesService.getSeriesBooks("A Song of Ice and Fire", 0, 20, "seriesNumber", "asc", null))
|
||||
.thenReturn(expected);
|
||||
|
||||
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
|
||||
controller.getSeriesBooks("A Song of Ice and Fire", 0, 20, "seriesNumber", "asc", null);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(mobileSeriesService).getSeriesBooks("A Song of Ice and Fire", 0, 20, "seriesNumber", "asc", null);
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
private MobilePageResponse<MobileSeriesSummary> buildSeriesPage() {
|
||||
MobileSeriesSummary summary = MobileSeriesSummary.builder()
|
||||
.seriesName("Test Series")
|
||||
.bookCount(5)
|
||||
.seriesTotal(5)
|
||||
.booksRead(2)
|
||||
.authors(List.of("Author A"))
|
||||
.latestAddedOn(Instant.now())
|
||||
.coverBooks(List.of())
|
||||
.build();
|
||||
return MobilePageResponse.of(List.of(summary), 0, 20, 1);
|
||||
}
|
||||
|
||||
private MobilePageResponse<MobileBookSummary> buildBookPage() {
|
||||
MobileBookSummary summary = MobileBookSummary.builder()
|
||||
.id(1L)
|
||||
.title("Test Book")
|
||||
.authors(List.of("Author A"))
|
||||
.seriesName("Dune")
|
||||
.seriesNumber(1.0f)
|
||||
.build();
|
||||
return MobilePageResponse.of(List.of(summary), 0, 20, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package org.booklore.mobile.service;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.TypedQuery;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.mobile.dto.MobileAuthorDetail;
|
||||
import org.booklore.mobile.dto.MobileAuthorSummary;
|
||||
import org.booklore.mobile.dto.MobilePageResponse;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.repository.AuthorRepository;
|
||||
import org.booklore.util.FileService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class MobileAuthorServiceTest {
|
||||
|
||||
@Mock private EntityManager entityManager;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private AuthorRepository authorRepository;
|
||||
@Mock private FileService fileService;
|
||||
|
||||
private MobileAuthorService service;
|
||||
|
||||
private final Long userId = 1L;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MobileAuthorService(authorRepository, authenticationService, fileService, entityManager);
|
||||
}
|
||||
|
||||
// ---- getAuthors tests ----
|
||||
|
||||
@Nested
|
||||
class GetAuthorsTests {
|
||||
|
||||
@Test
|
||||
void getAuthors_admin_noFilters_returnsPage() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(2L);
|
||||
mockDataQuery(List.<Object[]>of(
|
||||
new Object[]{buildAuthor(1L, "Author A"), 5L},
|
||||
new Object[]{buildAuthor(2L, "Author B"), 3L}
|
||||
));
|
||||
mockAuthorThumbnailExists(1L, true);
|
||||
mockAuthorThumbnailExists(2L, false);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "name", "asc", null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(2, result.getContent().size());
|
||||
assertEquals("Author A", result.getContent().get(0).getName());
|
||||
assertEquals(5, result.getContent().get(0).getBookCount());
|
||||
assertTrue(result.getContent().get(0).isHasPhoto());
|
||||
assertEquals("Author B", result.getContent().get(1).getName());
|
||||
assertEquals(3, result.getContent().get(1).getBookCount());
|
||||
assertFalse(result.getContent().get(1).isHasPhoto());
|
||||
assertEquals(2, result.getTotalElements());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_admin_emptyResult_returnsEmptyPage() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.getContent().isEmpty());
|
||||
assertEquals(0, result.getTotalElements());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_nonAdmin_withAccessibleLibrary_succeeds() {
|
||||
mockNonAdminUser(Set.of(5L, 10L));
|
||||
mockCountQuery(1L);
|
||||
mockDataQuery(List.<Object[]>of(
|
||||
new Object[]{buildAuthor(3L, "Author C"), 2L}
|
||||
));
|
||||
mockAuthorThumbnailExists(3L, false);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, 5L, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
assertEquals("Author C", result.getContent().get(0).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_nonAdmin_noLibraryFilter_usesAccessibleLibraries() {
|
||||
mockNonAdminUser(Set.of(5L));
|
||||
mockCountQuery(1L);
|
||||
mockDataQuery(List.<Object[]>of(
|
||||
new Object[]{buildAuthor(4L, "Author D"), 1L}
|
||||
));
|
||||
mockAuthorThumbnailExists(4L, true);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_withSearch_filtersResultsByName() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(1L);
|
||||
mockDataQuery(List.<Object[]>of(
|
||||
new Object[]{buildAuthor(5L, "Brandon Sanderson"), 12L}
|
||||
));
|
||||
mockAuthorThumbnailExists(5L, true);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, "brandon", null);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
assertEquals("Brandon Sanderson", result.getContent().get(0).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_withHasPhotoTrue_filtersToAuthorsWithPhotos() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(2L);
|
||||
mockDataQuery(List.<Object[]>of(
|
||||
new Object[]{buildAuthor(6L, "Author E"), 4L},
|
||||
new Object[]{buildAuthor(7L, "Author F"), 2L}
|
||||
));
|
||||
mockAuthorThumbnailExists(6L, true);
|
||||
mockAuthorThumbnailExists(7L, false);
|
||||
// Mock the hasPhoto count query
|
||||
mockAuthorEntityQuery(List.of(buildAuthor(6L, "Author E"), buildAuthor(7L, "Author F")));
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, true);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
assertEquals("Author E", result.getContent().get(0).getName());
|
||||
assertTrue(result.getContent().get(0).isHasPhoto());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_withHasPhotoFalse_filtersToAuthorsWithoutPhotos() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(2L);
|
||||
mockDataQuery(List.<Object[]>of(
|
||||
new Object[]{buildAuthor(8L, "Author G"), 3L},
|
||||
new Object[]{buildAuthor(9L, "Author H"), 1L}
|
||||
));
|
||||
mockAuthorThumbnailExists(8L, true);
|
||||
mockAuthorThumbnailExists(9L, false);
|
||||
mockAuthorEntityQuery(List.of(buildAuthor(8L, "Author G"), buildAuthor(9L, "Author H")));
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
assertEquals("Author H", result.getContent().get(0).getName());
|
||||
assertFalse(result.getContent().get(0).isHasPhoto());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_paginationDefaults_appliedCorrectly() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(null, null, null, null, null, null, null);
|
||||
|
||||
assertEquals(0, result.getPage());
|
||||
assertEquals(30, result.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_pageSizeCapped_atMax() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 100, null, null, null, null, null);
|
||||
|
||||
assertEquals(50, result.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_sortByName_asc() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "name", "asc", null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_sortByBookCount_desc() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "bookCount", "desc", null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthors_sortByRecent_desc() {
|
||||
mockAdminUser();
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "recent", "desc", null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- getAuthorDetail tests ----
|
||||
|
||||
@Nested
|
||||
class GetAuthorDetailTests {
|
||||
|
||||
@Test
|
||||
void getAuthorDetail_admin_returnsDetail() {
|
||||
mockAdminUser();
|
||||
AuthorEntity author = buildAuthor(1L, "J.R.R. Tolkien");
|
||||
author.setDescription("English writer and philologist.");
|
||||
author.setAsin("B000AP9MCS");
|
||||
when(authorRepository.findById(1L)).thenReturn(Optional.of(author));
|
||||
mockAuthorThumbnailExists(1L, true);
|
||||
mockBookCountQuery(3);
|
||||
|
||||
MobileAuthorDetail result = service.getAuthorDetail(1L);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1L, result.getId());
|
||||
assertEquals("J.R.R. Tolkien", result.getName());
|
||||
assertEquals("English writer and philologist.", result.getDescription());
|
||||
assertEquals("B000AP9MCS", result.getAsin());
|
||||
assertEquals(3, result.getBookCount());
|
||||
assertTrue(result.isHasPhoto());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthorDetail_nonAdmin_withAccess_returnsDetail() {
|
||||
mockNonAdminUser(Set.of(5L));
|
||||
AuthorEntity author = buildAuthor(2L, "Frank Herbert");
|
||||
when(authorRepository.findById(2L)).thenReturn(Optional.of(author));
|
||||
when(authorRepository.existsByIdAndLibraryIds(eq(2L), anySet())).thenReturn(true);
|
||||
mockAuthorThumbnailExists(2L, false);
|
||||
mockBookCountQuery(6);
|
||||
|
||||
MobileAuthorDetail result = service.getAuthorDetail(2L);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("Frank Herbert", result.getName());
|
||||
assertEquals(6, result.getBookCount());
|
||||
assertFalse(result.isHasPhoto());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthorDetail_nonAdmin_noAccess_throwsNotFound() {
|
||||
mockNonAdminUser(Set.of(5L));
|
||||
AuthorEntity author = buildAuthor(3L, "Secret Author");
|
||||
when(authorRepository.findById(3L)).thenReturn(Optional.of(author));
|
||||
when(authorRepository.existsByIdAndLibraryIds(eq(3L), anySet())).thenReturn(false);
|
||||
|
||||
assertThrows(APIException.class, () -> service.getAuthorDetail(3L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthorDetail_nonExistentAuthor_throwsNotFound() {
|
||||
mockAdminUser();
|
||||
when(authorRepository.findById(999L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(APIException.class, () -> service.getAuthorDetail(999L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAuthorDetail_nonAdmin_emptyLibraries_throwsNotFound() {
|
||||
mockNonAdminUser(Collections.emptySet());
|
||||
AuthorEntity author = buildAuthor(4L, "Author X");
|
||||
when(authorRepository.findById(4L)).thenReturn(Optional.of(author));
|
||||
|
||||
assertThrows(APIException.class, () -> service.getAuthorDetail(4L));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
private void mockAdminUser() {
|
||||
var permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(true);
|
||||
BookLoreUser user = BookLoreUser.builder()
|
||||
.id(userId)
|
||||
.permissions(permissions)
|
||||
.build();
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
}
|
||||
|
||||
private void mockNonAdminUser(Set<Long> libraryIds) {
|
||||
List<Library> assignedLibraries = libraryIds.stream()
|
||||
.map(id -> Library.builder().id(id).build())
|
||||
.toList();
|
||||
var permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(false);
|
||||
BookLoreUser user = BookLoreUser.builder()
|
||||
.id(userId)
|
||||
.permissions(permissions)
|
||||
.assignedLibraries(assignedLibraries)
|
||||
.build();
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockCountQuery(long count) {
|
||||
TypedQuery<Long> countQ = mock(TypedQuery.class);
|
||||
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
|
||||
when(countQ.getSingleResult()).thenReturn(count);
|
||||
when(entityManager.createQuery(anyString(), eq(Long.class))).thenReturn(countQ);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockDataQuery(List<Object[]> results) {
|
||||
TypedQuery<Object[]> dataQ = mock(TypedQuery.class);
|
||||
when(dataQ.setParameter(anyString(), any())).thenReturn(dataQ);
|
||||
when(dataQ.setFirstResult(anyInt())).thenReturn(dataQ);
|
||||
when(dataQ.setMaxResults(anyInt())).thenReturn(dataQ);
|
||||
when(dataQ.getResultList()).thenReturn(results);
|
||||
when(entityManager.createQuery(anyString(), eq(Object[].class))).thenReturn(dataQ);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockAuthorEntityQuery(List<AuthorEntity> authors) {
|
||||
TypedQuery<AuthorEntity> authorQ = mock(TypedQuery.class);
|
||||
when(authorQ.setParameter(anyString(), any())).thenReturn(authorQ);
|
||||
when(authorQ.getResultList()).thenReturn(authors);
|
||||
when(entityManager.createQuery(anyString(), eq(AuthorEntity.class))).thenReturn(authorQ);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockBookCountQuery(int count) {
|
||||
TypedQuery<Long> countQ = mock(TypedQuery.class);
|
||||
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
|
||||
when(countQ.getSingleResult()).thenReturn((long) count);
|
||||
when(entityManager.createQuery(anyString(), eq(Long.class))).thenReturn(countQ);
|
||||
}
|
||||
|
||||
private void mockAuthorThumbnailExists(Long authorId, boolean exists) {
|
||||
String path = "/mock/authors/" + authorId + "/thumbnail.jpg";
|
||||
when(fileService.getAuthorThumbnailFile(authorId)).thenReturn(path);
|
||||
// Since Files.exists checks real filesystem, a non-existent mock path returns false.
|
||||
// For "exists = true" tests, we need a path that actually exists.
|
||||
if (exists) {
|
||||
// Use a path we know exists — the temp directory
|
||||
when(fileService.getAuthorThumbnailFile(authorId)).thenReturn(System.getProperty("java.io.tmpdir"));
|
||||
}
|
||||
}
|
||||
|
||||
private AuthorEntity buildAuthor(Long id, String name) {
|
||||
return AuthorEntity.builder()
|
||||
.id(id)
|
||||
.name(name)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
package org.booklore.mobile.service;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.Tuple;
|
||||
import jakarta.persistence.TypedQuery;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.mobile.dto.MobileBookSummary;
|
||||
import org.booklore.mobile.dto.MobilePageResponse;
|
||||
import org.booklore.mobile.dto.MobileSeriesSummary;
|
||||
import org.booklore.mobile.mapper.MobileBookMapper;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.UserBookProgressRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class MobileSeriesServiceTest {
|
||||
|
||||
@Mock private EntityManager entityManager;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private UserBookProgressRepository userBookProgressRepository;
|
||||
@Mock private MobileBookMapper mobileBookMapper;
|
||||
|
||||
private MobileSeriesService service;
|
||||
|
||||
private final Long userId = 1L;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MobileSeriesService(
|
||||
entityManager, authenticationService, bookRepository,
|
||||
userBookProgressRepository, mobileBookMapper
|
||||
);
|
||||
}
|
||||
|
||||
// ---- getSeries tests ----
|
||||
|
||||
@Nested
|
||||
class GetSeriesTests {
|
||||
|
||||
@Test
|
||||
void getSeries_admin_noParams_returnsPage() {
|
||||
mockAdminUser();
|
||||
mockAggregateQuery(List.of(
|
||||
mockSeriesTuple("The Expanse", 9L, 9, Instant.now(), 3L)
|
||||
));
|
||||
mockCountQuery(1L);
|
||||
mockBooksQuery(List.of(buildBook(1L, "The Expanse", 1.0f, "Author A")));
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
assertEquals("The Expanse", result.getContent().getFirst().getSeriesName());
|
||||
assertEquals(9, result.getContent().getFirst().getBookCount());
|
||||
assertEquals(3, result.getContent().getFirst().getBooksRead());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_admin_emptyResult_returnsEmptyPage() {
|
||||
mockAdminUser();
|
||||
mockAggregateQuery(Collections.emptyList());
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.getContent().isEmpty());
|
||||
assertEquals(0, result.getTotalElements());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_nonAdmin_withAccessibleLibrary_succeeds() {
|
||||
mockNonAdminUser(Set.of(5L, 10L));
|
||||
mockAggregateQuery(List.of(
|
||||
mockSeriesTuple("Dune", 6L, 6, Instant.now(), 2L)
|
||||
));
|
||||
mockCountQuery(1L);
|
||||
mockBooksQuery(List.of(buildBook(2L, "Dune", 1.0f, "Frank Herbert")));
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, 5L, null, false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_nonAdmin_noAccessToLibrary_throwsForbidden() {
|
||||
mockNonAdminUser(Set.of(10L));
|
||||
|
||||
assertThrows(APIException.class, () ->
|
||||
service.getSeries(0, 20, null, null, 5L, null, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_withSearch_passesSearchPattern() {
|
||||
mockAdminUser();
|
||||
mockAggregateQuery(List.of(
|
||||
mockSeriesTuple("Harry Potter", 7L, 7, Instant.now(), 7L)
|
||||
));
|
||||
mockCountQuery(1L);
|
||||
mockBooksQuery(List.of(buildBook(3L, "Harry Potter", 1.0f, "J.K. Rowling")));
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, "harry", false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_inProgressOnly_returnsFilteredResults() {
|
||||
mockAdminUser();
|
||||
mockAggregateQueryInProgress(List.of(
|
||||
mockSeriesTupleInProgress("The Expanse", 9L, 9, Instant.now(), 3L, Instant.now())
|
||||
));
|
||||
mockCountQueryInProgress(1L);
|
||||
mockBooksQuery(List.of(buildBook(1L, "The Expanse", 1.0f, "Author A")));
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, true);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_paginationDefaults_appliedCorrectly() {
|
||||
mockAdminUser();
|
||||
mockAggregateQuery(Collections.emptyList());
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(null, null, null, null, null, null, false);
|
||||
|
||||
assertEquals(0, result.getPage());
|
||||
assertEquals(20, result.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_pageSizeCapped_atMax() {
|
||||
mockAdminUser();
|
||||
mockAggregateQuery(Collections.emptyList());
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 100, null, null, null, null, false);
|
||||
|
||||
assertEquals(50, result.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_enrichesCoverBooksAndAuthors() {
|
||||
mockAdminUser();
|
||||
BookEntity book1 = buildBook(10L, "Series X", 1.0f, "Author A");
|
||||
BookEntity book2 = buildBook(11L, "Series X", 2.0f, "Author B");
|
||||
|
||||
mockAggregateQuery(List.of(
|
||||
mockSeriesTuple("Series X", 2L, 3, Instant.now(), 1L)
|
||||
));
|
||||
mockCountQuery(1L);
|
||||
mockBooksQuery(List.of(book1, book2));
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
|
||||
|
||||
MobileSeriesSummary series = result.getContent().getFirst();
|
||||
assertEquals(2, series.getCoverBooks().size());
|
||||
assertEquals(2, series.getAuthors().size());
|
||||
// Cover books should be ordered by seriesNumber ASC
|
||||
assertEquals(1.0f, series.getCoverBooks().get(0).getSeriesNumber());
|
||||
assertEquals(2.0f, series.getCoverBooks().get(1).getSeriesNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_sortByName_asc() {
|
||||
mockAdminUser();
|
||||
mockAggregateQuery(Collections.emptyList());
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, "name", "asc", null, null, false);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeries_sortByBookCount_desc() {
|
||||
mockAdminUser();
|
||||
mockAggregateQuery(Collections.emptyList());
|
||||
mockCountQuery(0L);
|
||||
|
||||
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, "bookCount", "desc", null, null, false);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- getSeriesBooks tests ----
|
||||
|
||||
@Nested
|
||||
class GetSeriesBooksTests {
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_admin_returnsBooks() {
|
||||
mockAdminUser();
|
||||
BookEntity book = buildBook(1L, "Dune", 1.0f, "Frank Herbert");
|
||||
mockBookPage(List.of(book), 1L);
|
||||
mockProgress(Collections.emptyList());
|
||||
mockMapperSummary();
|
||||
|
||||
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
assertEquals(1, result.getTotalElements());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_nonAdmin_withAccess_succeeds() {
|
||||
mockNonAdminUser(Set.of(5L));
|
||||
BookEntity book = buildBook(2L, "Dune", 2.0f, "Frank Herbert");
|
||||
mockBookPage(List.of(book), 1L);
|
||||
mockProgress(Collections.emptyList());
|
||||
mockMapperSummary();
|
||||
|
||||
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, 5L);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getContent().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_nonAdmin_noAccess_throwsForbidden() {
|
||||
mockNonAdminUser(Set.of(10L));
|
||||
|
||||
assertThrows(APIException.class, () ->
|
||||
service.getSeriesBooks("Dune", 0, 20, null, null, 5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_emptyResult_returnsEmptyPage() {
|
||||
mockAdminUser();
|
||||
mockBookPage(Collections.emptyList(), 0L);
|
||||
|
||||
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Nonexistent", 0, 20, null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.getContent().isEmpty());
|
||||
assertEquals(0, result.getTotalElements());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_sortByTitle_desc() {
|
||||
mockAdminUser();
|
||||
mockBookPage(Collections.emptyList(), 0L);
|
||||
|
||||
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, "title", "desc", null);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_sortByRecentlyAdded_asc() {
|
||||
mockAdminUser();
|
||||
mockBookPage(Collections.emptyList(), 0L);
|
||||
|
||||
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, "recentlyAdded", "asc", null);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_defaultSort_isSeriesNumber() {
|
||||
mockAdminUser();
|
||||
mockBookPage(Collections.emptyList(), 0L);
|
||||
|
||||
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, null);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_paginationDefaults() {
|
||||
mockAdminUser();
|
||||
mockBookPage(Collections.emptyList(), 0L);
|
||||
|
||||
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", null, null, null, null, null);
|
||||
|
||||
assertEquals(0, result.getPage());
|
||||
assertEquals(20, result.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSeriesBooks_pageSizeCapped() {
|
||||
mockAdminUser();
|
||||
mockBookPage(Collections.emptyList(), 0L);
|
||||
|
||||
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 200, null, null, null);
|
||||
|
||||
assertEquals(50, result.getSize());
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
private void mockAdminUser() {
|
||||
var permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(true);
|
||||
BookLoreUser user = BookLoreUser.builder()
|
||||
.id(userId)
|
||||
.permissions(permissions)
|
||||
.build();
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
}
|
||||
|
||||
private void mockNonAdminUser(Set<Long> libraryIds) {
|
||||
List<Library> assignedLibraries = libraryIds.stream()
|
||||
.map(id -> Library.builder().id(id).build())
|
||||
.toList();
|
||||
var permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(false);
|
||||
BookLoreUser user = BookLoreUser.builder()
|
||||
.id(userId)
|
||||
.permissions(permissions)
|
||||
.assignedLibraries(assignedLibraries)
|
||||
.build();
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
}
|
||||
|
||||
private Tuple mockSeriesTuple(String name, Long count, Integer total, Instant addedOn, Long booksRead) {
|
||||
Tuple tuple = mock(Tuple.class);
|
||||
when(tuple.get(0, String.class)).thenReturn(name);
|
||||
when(tuple.get(1, Long.class)).thenReturn(count);
|
||||
when(tuple.get(2, Integer.class)).thenReturn(total);
|
||||
when(tuple.get(3, Instant.class)).thenReturn(addedOn);
|
||||
when(tuple.get(4, Long.class)).thenReturn(booksRead);
|
||||
return tuple;
|
||||
}
|
||||
|
||||
private Tuple mockSeriesTupleInProgress(String name, Long count, Integer total, Instant addedOn, Long booksRead, Instant lastReadTime) {
|
||||
Tuple tuple = mockSeriesTuple(name, count, total, addedOn, booksRead);
|
||||
when(tuple.get(5, Instant.class)).thenReturn(lastReadTime);
|
||||
return tuple;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockAggregateQuery(List<Tuple> results) {
|
||||
TypedQuery<Tuple> aggregateQ = mock(TypedQuery.class);
|
||||
when(aggregateQ.setParameter(anyString(), any())).thenReturn(aggregateQ);
|
||||
when(aggregateQ.setFirstResult(anyInt())).thenReturn(aggregateQ);
|
||||
when(aggregateQ.setMaxResults(anyInt())).thenReturn(aggregateQ);
|
||||
when(aggregateQ.getResultList()).thenReturn(results);
|
||||
|
||||
TypedQuery<BookEntity> booksQ = mock(TypedQuery.class);
|
||||
when(booksQ.setParameter(anyString(), any())).thenReturn(booksQ);
|
||||
when(booksQ.getResultList()).thenReturn(Collections.emptyList());
|
||||
|
||||
when(entityManager.createQuery(anyString(), eq(Tuple.class))).thenReturn(aggregateQ);
|
||||
when(entityManager.createQuery(anyString(), eq(BookEntity.class))).thenReturn(booksQ);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockAggregateQueryInProgress(List<Tuple> results) {
|
||||
// Pre-compute series names before setting up mocks to avoid calling .get() on mock Tuples during stubbing
|
||||
List<String> seriesNames = new ArrayList<>();
|
||||
for (Tuple t : results) {
|
||||
seriesNames.add(t.get(0, String.class));
|
||||
}
|
||||
|
||||
TypedQuery<Tuple> aggregateQ = mock(TypedQuery.class);
|
||||
when(aggregateQ.setParameter(anyString(), any())).thenReturn(aggregateQ);
|
||||
when(aggregateQ.setFirstResult(anyInt())).thenReturn(aggregateQ);
|
||||
when(aggregateQ.setMaxResults(anyInt())).thenReturn(aggregateQ);
|
||||
when(aggregateQ.getResultList()).thenReturn(results);
|
||||
|
||||
TypedQuery<BookEntity> booksQ = mock(TypedQuery.class);
|
||||
when(booksQ.setParameter(anyString(), any())).thenReturn(booksQ);
|
||||
when(booksQ.getResultList()).thenReturn(Collections.emptyList());
|
||||
|
||||
// In-progress count uses String.class query
|
||||
TypedQuery<String> countQ = mock(TypedQuery.class);
|
||||
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
|
||||
when(countQ.getResultList()).thenReturn(seriesNames);
|
||||
|
||||
when(entityManager.createQuery(anyString(), eq(Tuple.class))).thenReturn(aggregateQ);
|
||||
when(entityManager.createQuery(anyString(), eq(BookEntity.class))).thenReturn(booksQ);
|
||||
when(entityManager.createQuery(anyString(), eq(String.class))).thenReturn(countQ);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockCountQuery(long count) {
|
||||
TypedQuery<Long> countQ = mock(TypedQuery.class);
|
||||
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
|
||||
when(countQ.getSingleResult()).thenReturn(count);
|
||||
when(entityManager.createQuery(anyString(), eq(Long.class))).thenReturn(countQ);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockCountQueryInProgress(long count) {
|
||||
TypedQuery<String> countQ = mock(TypedQuery.class);
|
||||
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
|
||||
List<String> names = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) names.add("series" + i);
|
||||
when(countQ.getResultList()).thenReturn(names);
|
||||
when(entityManager.createQuery(anyString(), eq(String.class))).thenReturn(countQ);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockBooksQuery(List<BookEntity> books) {
|
||||
TypedQuery<BookEntity> booksQ = mock(TypedQuery.class);
|
||||
when(booksQ.setParameter(anyString(), any())).thenReturn(booksQ);
|
||||
when(booksQ.getResultList()).thenReturn(books);
|
||||
when(entityManager.createQuery(anyString(), eq(BookEntity.class))).thenReturn(booksQ);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockBookPage(List<BookEntity> books, long total) {
|
||||
var page = new PageImpl<>(books, Pageable.ofSize(20), total);
|
||||
when(bookRepository.findAll(any(Specification.class), any(Pageable.class))).thenReturn(page);
|
||||
}
|
||||
|
||||
private void mockProgress(List<UserBookProgressEntity> progressList) {
|
||||
when(userBookProgressRepository.findByUserIdAndBookIdIn(eq(userId), anySet()))
|
||||
.thenReturn(progressList);
|
||||
}
|
||||
|
||||
private void mockMapperSummary() {
|
||||
when(mobileBookMapper.toSummary(any(BookEntity.class), any()))
|
||||
.thenAnswer(inv -> {
|
||||
BookEntity b = inv.getArgument(0);
|
||||
return MobileBookSummary.builder()
|
||||
.id(b.getId())
|
||||
.title(b.getMetadata() != null ? b.getMetadata().getTitle() : null)
|
||||
.build();
|
||||
});
|
||||
}
|
||||
|
||||
private BookEntity buildBook(Long id, String seriesName, Float seriesNumber, String authorName) {
|
||||
AuthorEntity author = new AuthorEntity();
|
||||
author.setName(authorName);
|
||||
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.bookId(id)
|
||||
.title(seriesName + " #" + seriesNumber.intValue())
|
||||
.seriesName(seriesName)
|
||||
.seriesNumber(seriesNumber)
|
||||
.coverUpdatedOn(Instant.now())
|
||||
.authors(Set.of(author))
|
||||
.build();
|
||||
|
||||
BookFileEntity bookFile = BookFileEntity.builder()
|
||||
.id(id)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
List<BookFileEntity> bookFiles = new ArrayList<>(List.of(bookFile));
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.id(id)
|
||||
.metadata(metadata)
|
||||
.addedOn(Instant.now())
|
||||
.bookFiles(bookFiles)
|
||||
.build();
|
||||
|
||||
metadata.setBook(book);
|
||||
bookFile.setBook(book);
|
||||
|
||||
return book;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user