diff --git a/backend/src/main/java/org/booklore/browse/Link.java b/backend/src/main/java/org/booklore/browse/Link.java index 4534f2bbf..5b2c5cf25 100644 --- a/backend/src/main/java/org/booklore/browse/Link.java +++ b/backend/src/main/java/org/booklore/browse/Link.java @@ -1,11 +1,12 @@ package org.booklore.browse; import com.fasterxml.jackson.annotation.JsonInclude; +import tools.jackson.databind.annotation.JsonSerialize; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) -public record Link(List rel, String href, String type) { +public record Link(@JsonSerialize(using = RelSerializer.class) List rel, String href, String type) { public static final String JSON_TYPE = "application/json"; diff --git a/backend/src/main/java/org/booklore/browse/LinksBuilder.java b/backend/src/main/java/org/booklore/browse/LinksBuilder.java index 85c82dd70..f959c3a7f 100644 --- a/backend/src/main/java/org/booklore/browse/LinksBuilder.java +++ b/backend/src/main/java/org/booklore/browse/LinksBuilder.java @@ -5,8 +5,8 @@ import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; -// Builds the paging links for a browse page (self/first/previous/next) -// Each carries the request's facet/query params + a cursor offset +// Builds the links for a browse page (self/first/previous/next/facet) +// Paging links carry the request's facet/query params + a cursor offset @Component public class LinksBuilder { @@ -18,6 +18,7 @@ public class LinksBuilder { public record Context( String pagePath, + String facetPath, String preservedQuery, long offset, int limit, @@ -28,6 +29,11 @@ public class LinksBuilder { public List build(Context ctx) { List links = new ArrayList<>(); + String facetHref = ctx.facetPath(); + if (ctx.preservedQuery() != null && !ctx.preservedQuery().isBlank()) { + facetHref = facetHref + "?" + ctx.preservedQuery(); + } + links.add(Link.json(List.of("facet"), facetHref)); links.add(pageLink(List.of("self"), ctx, ctx.offset())); links.add(pageLink(List.of("first"), ctx, 0)); diff --git a/backend/src/main/java/org/booklore/browse/RelSerializer.java b/backend/src/main/java/org/booklore/browse/RelSerializer.java new file mode 100644 index 000000000..82e7ebc4b --- /dev/null +++ b/backend/src/main/java/org/booklore/browse/RelSerializer.java @@ -0,0 +1,25 @@ +package org.booklore.browse; + +import tools.jackson.core.JsonGenerator; +import tools.jackson.databind.SerializationContext; +import tools.jackson.databind.ValueSerializer; + +import java.util.List; + +// Serializes rel following the RWPM Link Object convention used by the OPDS 2.0 +// examples: a bare string for a single relation, an array for several. +public class RelSerializer extends ValueSerializer> { + + @Override + public void serialize(List rels, JsonGenerator gen, SerializationContext context) { + if (rels.size() == 1) { + gen.writeString(rels.getFirst()); + return; + } + gen.writeStartArray(); + for (String rel : rels) { + gen.writeString(rel); + } + gen.writeEndArray(); + } +} diff --git a/backend/src/main/java/org/booklore/controller/BookController.java b/backend/src/main/java/org/booklore/controller/BookController.java index 268073f1d..5d4ae7d48 100644 --- a/backend/src/main/java/org/booklore/controller/BookController.java +++ b/backend/src/main/java/org/booklore/controller/BookController.java @@ -25,6 +25,8 @@ import org.booklore.service.book.BookUpdateService; import org.booklore.service.book.DuplicateDetectionService; import org.booklore.service.book.PhysicalBookService; import org.booklore.service.browse.BookBrowseService; +import org.booklore.service.browse.BookFacetService; +import org.booklore.model.dto.browse.FacetGroupsResponse; import org.booklore.service.metadata.BookMetadataService; import org.booklore.service.progress.ReadingProgressService; import org.booklore.service.recommender.BookRecommendationService; @@ -61,6 +63,7 @@ public class BookController { private final BookService bookService; private final BookBrowseService bookBrowseService; + private final BookFacetService bookFacetService; private final BookUpdateService bookUpdateService; private final BookRecommendationService bookRecommendationService; private final BookFileAttachmentService bookFileAttachmentService; @@ -102,6 +105,19 @@ public class BookController { return ResponseEntity.ok(bookBrowseService.wrapLegacy(bookService.getBookDTOsPaged(pageable), pageable)); } + @Operation(summary = "Get book facets", description = "Available facet values and counts for the current user, scoped by the same facet, facet_logic, and query parameters as the page endpoint. Each facet omits its own selections from its counts.") + @ApiResponse(responseCode = "200", description = "Facet groups returned successfully") + @GetMapping("/facets") + public ResponseEntity getBookFacets( + @Parameter(description = "Facet selection in key:value form; repeatable") + @RequestParam(required = false) List facet, + @Parameter(description = "How facet values combine within a group: and, or, or not") + @RequestParam(name = "facet_logic", required = false) String facetLogic, + @Parameter(description = "Free-text search applied to the counts") + @RequestParam(required = false) String query) { + return ResponseEntity.ok(bookFacetService.getFacets(facet, facetLogic, query)); + } + @Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Book details returned successfully"), diff --git a/backend/src/main/java/org/booklore/model/dto/browse/FacetGroupsResponse.java b/backend/src/main/java/org/booklore/model/dto/browse/FacetGroupsResponse.java new file mode 100644 index 000000000..78cca8ec6 --- /dev/null +++ b/backend/src/main/java/org/booklore/model/dto/browse/FacetGroupsResponse.java @@ -0,0 +1,28 @@ +package org.booklore.model.dto.browse; + +import com.fasterxml.jackson.annotation.JsonInclude; +import tools.jackson.databind.annotation.JsonSerialize; +import org.booklore.browse.Link; +import org.booklore.browse.RelSerializer; + +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public record FacetGroupsResponse(List links, List facets) { + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record FacetGroup(Metadata metadata, List links) { + } + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record Metadata(String rel, String key, String title) { + } + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record FacetLink(@JsonSerialize(using = RelSerializer.class) List rel, String href, String type, String title, String value, Properties properties) { + } + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record Properties(Long numberOfItems) { + } +} diff --git a/backend/src/main/java/org/booklore/service/browse/BookBrowseService.java b/backend/src/main/java/org/booklore/service/browse/BookBrowseService.java index ee755d821..8653cb6c6 100644 --- a/backend/src/main/java/org/booklore/service/browse/BookBrowseService.java +++ b/backend/src/main/java/org/booklore/service/browse/BookBrowseService.java @@ -37,6 +37,7 @@ import java.util.stream.Collectors; public class BookBrowseService { private static final String PAGE_PATH = "/api/v1/books/page"; + private static final String FACET_PATH = "/api/v1/books/facets"; private static final int MAX_PAGE_SIZE = 100; private final AuthenticationService authenticationService; @@ -86,7 +87,7 @@ public class BookBrowseService { CursorState baseState = new CursorState(offset, limit, sortString, paramsHash); String currentCursor = cursorCodec.encode(baseState); List links = linksBuilder.build(new LinksBuilder.Context( - PAGE_PATH, BrowseParams.preserved(facet, facetLogicParam, query), offset, limit, page.getTotalElements(), baseState)); + PAGE_PATH, FACET_PATH, BrowseParams.preserved(facet, facetLogicParam, query), offset, limit, page.getTotalElements(), baseState)); return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), currentCursor, links); } @@ -97,7 +98,7 @@ public class BookBrowseService { String paramsHash = ParamsHash.compute(null, Map.of(), FacetLogic.AND); CursorState baseState = new CursorState(offset, limit, null, paramsHash); List links = linksBuilder.build(new LinksBuilder.Context( - PAGE_PATH, "", offset, limit, page.getTotalElements(), baseState)); + PAGE_PATH, FACET_PATH, "", offset, limit, page.getTotalElements(), baseState)); return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), cursorCodec.encode(baseState), links); } diff --git a/backend/src/main/java/org/booklore/service/browse/BookFacetService.java b/backend/src/main/java/org/booklore/service/browse/BookFacetService.java new file mode 100644 index 000000000..ddce8d7a6 --- /dev/null +++ b/backend/src/main/java/org/booklore/service/browse/BookFacetService.java @@ -0,0 +1,165 @@ +package org.booklore.service.browse; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Tuple; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Expression; +import jakarta.persistence.criteria.Join; +import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import lombok.RequiredArgsConstructor; +import org.booklore.browse.FacetLogic; +import org.booklore.browse.Link; +import org.booklore.browse.ParamsHash; +import org.booklore.config.security.service.AuthenticationService; +import org.booklore.model.dto.BookLoreUser; +import org.booklore.model.dto.browse.FacetGroupsResponse; +import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup; +import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink; +import org.booklore.model.dto.browse.FacetGroupsResponse.Metadata; +import org.booklore.model.dto.browse.FacetGroupsResponse.Properties; +import org.booklore.model.entity.BookEntity; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class BookFacetService { + + private static final String PAGE_PATH = "/api/v1/books/page"; + private static final String FACET_PATH = "/api/v1/books/facets"; + private static final int MAX_VALUES = 100; + + private static final List FACETS = List.of( + new FacetDef("author", "Authors", root -> metadata(root).join("authors", JoinType.LEFT).get("name")), + new FacetDef("genre", "Genre", root -> metadata(root).join("categories", JoinType.LEFT).get("name")), + new FacetDef("tag", "Tags", root -> metadata(root).join("tags", JoinType.LEFT).get("name")), + new FacetDef("mood", "Moods", root -> metadata(root).join("moods", JoinType.LEFT).get("name")), + new FacetDef("series", "Series", root -> metadata(root).get("seriesName")), + new FacetDef("publisher", "Publisher", root -> metadata(root).get("publisher")), + new FacetDef("language", "Language", root -> metadata(root).get("language")), + new FacetDef("narrator", "Narrator", root -> metadata(root).get("narrator")), + new FacetDef("file_type", "File Type", root -> root.join("bookFiles", JoinType.LEFT).get("bookType"))); + + private final AuthenticationService authenticationService; + private final BookFilterSpecifications filterSpecifications; + private final BookSortRegistry sortRegistry; + + @PersistenceContext + private EntityManager entityManager; + + private final Cache cache = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofSeconds(30)) + .maximumSize(200) + .build(); + + public FacetGroupsResponse getFacets(List facet, String facetLogicParam, String query) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + Long userId = user.getId(); + boolean isAdmin = user.getPermissions().isAdmin(); + Set libraryIds = BookFilterSpecifications.libraryIds(user); + + Map> facets = BookFilterSpecifications.parseFacets(facet); + FacetLogic facetLogic = FacetLogic.from(facetLogicParam); + + String cacheKey = userId + ":" + ParamsHash.compute(query, facets, facetLogic); + return cache.get(cacheKey, key -> { + String preserved = BrowseParams.preserved(facet, facetLogicParam, query); + List groups = new ArrayList<>(); + groups.add(sortGroup(preserved)); + for (FacetDef def : FACETS) { + Specification base = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, libraryIds, def.key()); + groups.add(toGroup(def, count(def, base), facet, preserved)); + } + List links = List.of(Link.json(List.of("self"), href(FACET_PATH, preserved))); + return new FacetGroupsResponse(links, groups); + }); + } + + // Package-private: lets tests reset the shared singleton cache between runs. + void clearCache() { + cache.invalidateAll(); + } + + private List count(FacetDef def, Specification base) { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BookEntity.class); + Expression value = def.value().apply(root); + Expression count = cb.countDistinct(root.get("id")); + + List predicates = new ArrayList<>(); + Predicate basePredicate = base.toPredicate(root, cq, cb); + if (basePredicate != null) { + predicates.add(basePredicate); + } + predicates.add(cb.isNotNull(value)); + + cq.multiselect(value.alias("value"), count.alias("count")); + cq.where(predicates.toArray(Predicate[]::new)); + cq.groupBy(value); + cq.orderBy(cb.desc(count), cb.asc(value)); + + return entityManager.createQuery(cq).setMaxResults(MAX_VALUES).getResultList().stream() + .map(tuple -> new FacetCount(String.valueOf(tuple.get("value")), ((Number) tuple.get("count")).longValue())) + .toList(); + } + + private FacetGroup toGroup(FacetDef def, List counts, List facet, String preserved) { + List links = counts.stream() + .map(c -> { + boolean active = BrowseParams.hasFacet(facet, def.key(), c.value()); + List rel = active ? List.of("self", "facet") : List.of("facet"); + String href = active + ? href(PAGE_PATH, preserved) + : pageLink(preserved, "facet=" + BrowseParams.encode(def.key() + ":" + c.value())); + return new FacetLink(rel, href, Link.JSON_TYPE, c.value(), c.value(), new Properties(c.count())); + }) + .toList(); + return new FacetGroup(new Metadata("facet", def.key(), def.title()), links); + } + + private FacetGroup sortGroup(String preserved) { + List links = new ArrayList<>(); + for (String key : sortRegistry.registry().keys()) { + if (key.equals("id")) { + continue; + } + links.add(new FacetLink(List.of("sort"), pageLink(preserved, "sort=" + BrowseParams.encode(key)), Link.JSON_TYPE, key + " ascending", key, null)); + links.add(new FacetLink(List.of("sort"), pageLink(preserved, "sort=-" + BrowseParams.encode(key)), Link.JSON_TYPE, key + " descending", "-" + key, null)); + } + return new FacetGroup(new Metadata("sort", "sort", "Sort"), links); + } + + private static String pageLink(String preserved, String param) { + return preserved.isBlank() ? PAGE_PATH + "?" + param : PAGE_PATH + "?" + preserved + "&" + param; + } + + private static String href(String path, String preserved) { + return preserved.isBlank() ? path : path + "?" + preserved; + } + + private static Join metadata(Root root) { + return root.join("metadata", JoinType.LEFT); + } + + private record FacetDef(String key, String title, Function, Expression> value) { + } + + private record FacetCount(String value, long count) { + } +} diff --git a/backend/src/main/java/org/booklore/service/browse/BrowseParams.java b/backend/src/main/java/org/booklore/service/browse/BrowseParams.java index 6e41cee29..0760b52cb 100644 --- a/backend/src/main/java/org/booklore/service/browse/BrowseParams.java +++ b/backend/src/main/java/org/booklore/service/browse/BrowseParams.java @@ -28,6 +28,24 @@ final class BrowseParams { return String.join("&", parts); } + static boolean hasFacet(List facet, String key, String value) { + if (facet == null) { + return false; + } + return facet.stream().anyMatch(entry -> matchesFacet(entry, key, value)); + } + + private static boolean matchesFacet(String entry, String key, String value) { + if (entry == null) { + return false; + } + int colon = entry.indexOf(':'); + if (colon <= 0 || colon == entry.length() - 1) { + return false; + } + return entry.substring(0, colon).equals(key) && entry.substring(colon + 1).equalsIgnoreCase(value); + } + static String encode(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); } diff --git a/backend/src/test/java/org/booklore/browse/LinksBuilderTest.java b/backend/src/test/java/org/booklore/browse/LinksBuilderTest.java index c26ab4f01..e16b98fc9 100644 --- a/backend/src/test/java/org/booklore/browse/LinksBuilderTest.java +++ b/backend/src/test/java/org/booklore/browse/LinksBuilderTest.java @@ -17,7 +17,7 @@ class LinksBuilderTest { private LinksBuilder.Context context(long offset, int limit, long total, String preservedQuery) { CursorState base = new CursorState(offset, limit, "title", "hash00000000"); - return new LinksBuilder.Context("/api/v1/books/page", preservedQuery, offset, limit, total, base); + return new LinksBuilder.Context("/api/v1/books/page", "/api/v1/books/facets", preservedQuery, offset, limit, total, base); } private boolean hasRel(List links, String rel) { @@ -31,12 +31,27 @@ class LinksBuilderTest { } @Test - void selfAndFirstAlwaysPresent() { + void alwaysIncludesFacetSelfAndFirst() { List links = builder.build(context(40, 20, 100, "")); + assertTrue(hasRel(links, "facet")); assertTrue(hasRel(links, "self")); assertTrue(hasRel(links, "first")); } + @Test + void facetLinkPointsAtFacetsEndpointWithoutCursor() { + Link facet = withRel(builder.build(context(0, 20, 100, "")), "facet"); + assertEquals("/api/v1/books/facets", facet.href()); + assertEquals(Link.JSON_TYPE, facet.type()); + } + + @Test + void facetLinkCarriesPreservedQuery() { + Link facet = withRel(builder.build(context(0, 20, 100, "facet=genre%3AFiction")), "facet"); + assertEquals("/api/v1/books/facets?facet=genre%3AFiction", facet.href()); + assertEquals(Link.JSON_TYPE, facet.type()); + } + @Test void firstPageOmitsPreviousButHasNext() { List links = builder.build(context(0, 20, 100, "")); @@ -111,7 +126,7 @@ class LinksBuilderTest { @Test void nullPreservedQueryStillProducesValidLinks() { List links = builder.build(new LinksBuilder.Context( - "/api/v1/books/page", null, 0, 20, 5, + "/api/v1/books/page", "/api/v1/books/facets", null, 0, 20, 5, new CursorState(0, 20, "title", "hash00000000"))); assertTrue(hasRel(links, "self")); Link self = withRel(links, "self"); diff --git a/backend/src/test/java/org/booklore/browse/RelSerializerTest.java b/backend/src/test/java/org/booklore/browse/RelSerializerTest.java new file mode 100644 index 000000000..322187f7b --- /dev/null +++ b/backend/src/test/java/org/booklore/browse/RelSerializerTest.java @@ -0,0 +1,47 @@ +package org.booklore.browse; + +import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink; +import org.booklore.model.dto.browse.FacetGroupsResponse.Properties; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +// Uses the Jackson 3 (tools.jackson) mapper, the one Spring Boot wires into HTTP +// message conversion; a Jackson 2 mapper would ignore the rel serializer entirely. +class RelSerializerTest { + + private final ObjectMapper mapper = JsonMapper.builder().build(); + + @Test + void emptyRelSerializesAsEmptyArray() { + String json = mapper.writeValueAsString(Link.json(List.of(), "/api/v1/books/facets")); + assertThat(json).isEqualTo("{\"rel\":[],\"href\":\"/api/v1/books/facets\",\"type\":\"application/json\"}"); + } + + @Test + void singleRelSerializesAsString() { + String json = mapper.writeValueAsString(Link.json(List.of("self"), "/api/v1/books/facets")); + assertThat(json).isEqualTo("{\"rel\":\"self\",\"href\":\"/api/v1/books/facets\",\"type\":\"application/json\"}"); + } + + @Test + void multipleRelsSerializeAsArray() { + String json = mapper.writeValueAsString(Link.json(List.of("first", "previous"), "/api/v1/books/page")); + assertThat(json).isEqualTo("{\"rel\":[\"first\",\"previous\"],\"href\":\"/api/v1/books/page\",\"type\":\"application/json\"}"); + } + + @Test + void facetLinkFollowsTheSameConvention() { + FacetLink inactive = new FacetLink(List.of("facet"), "/x", Link.JSON_TYPE, "Horror", "Horror", new Properties(2L)); + assertThat(mapper.writeValueAsString(inactive)) + .isEqualTo("{\"rel\":\"facet\",\"href\":\"/x\",\"type\":\"application/json\",\"title\":\"Horror\",\"value\":\"Horror\",\"properties\":{\"numberOfItems\":2}}"); + + FacetLink active = new FacetLink(List.of("self", "facet"), "/x", Link.JSON_TYPE, "Horror", "Horror", new Properties(2L)); + assertThat(mapper.writeValueAsString(active)) + .isEqualTo("{\"rel\":[\"self\",\"facet\"],\"href\":\"/x\",\"type\":\"application/json\",\"title\":\"Horror\",\"value\":\"Horror\",\"properties\":{\"numberOfItems\":2}}"); + } +} diff --git a/backend/src/test/java/org/booklore/service/browse/BookFacetServiceTest.java b/backend/src/test/java/org/booklore/service/browse/BookFacetServiceTest.java new file mode 100644 index 000000000..3f0b6e3ff --- /dev/null +++ b/backend/src/test/java/org/booklore/service/browse/BookFacetServiceTest.java @@ -0,0 +1,369 @@ +package org.booklore.service.browse; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import org.booklore.BookloreApplication; +import org.booklore.browse.Link; +import org.booklore.config.security.service.AuthenticationService; +import org.booklore.model.dto.BookLoreUser; +import org.booklore.model.dto.Library; +import org.booklore.model.dto.browse.FacetGroupsResponse; +import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup; +import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink; +import org.booklore.model.entity.AuthorEntity; +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookLoreUserEntity; +import org.booklore.model.entity.BookMetadataEntity; +import org.booklore.model.entity.CategoryEntity; +import org.booklore.model.entity.LibraryEntity; +import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.service.task.TaskCronService; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.annotation.Transactional; +import tools.jackson.databind.ObjectMapper; + +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@SpringBootTest(classes = BookloreApplication.class) +@Transactional +@TestPropertySource(properties = { + "spring.flyway.enabled=false", + "spring.jpa.hibernate.ddl-auto=create-drop", + "spring.jpa.database-platform=org.hibernate.dialect.H2Dialect", + "spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect", + "spring.datasource.url=jdbc:h2:mem:facettest;DB_CLOSE_DELAY=-1;NON_KEYWORDS=VALUE", + "spring.datasource.driver-class-name=org.h2.Driver", + "spring.datasource.username=sa", + "spring.datasource.password=", + "app.path-config=build/tmp/test-config", + "app.bookdrop-folder=build/tmp/test-bookdrop", + "spring.main.allow-bean-definition-overriding=true", + "spring.task.scheduling.enabled=false", + "app.task.scan-library-cron=*/1 * * * * *", + "app.task.process-bookdrop-cron=*/1 * * * * *", + "app.features.oidc-enabled=false" +}) +@Import(BookFacetServiceTest.TestConfig.class) +class BookFacetServiceTest { + + @Autowired + private BookFacetService facetService; + @Autowired + private ObjectMapper springMapper; + @MockitoBean + private AuthenticationService authenticationService; + + @PersistenceContext + private EntityManager em; + + private BookLoreUserEntity userEntity; + private LibraryEntity library; + private LibraryPathEntity libraryPath; + private final Map categories = new HashMap<>(); + private final Map authors = new HashMap<>(); + + @TestConfiguration + public static class TestConfig { + @Bean("flyway") + @Primary + public Flyway flyway() { + return mock(Flyway.class); + } + + @Bean + @Primary + public TaskCronService taskCronService() { + return mock(TaskCronService.class); + } + } + + @BeforeEach + void seed() { + facetService.clearCache(); + userEntity = BookLoreUserEntity.builder().username("reader").passwordHash("x").name("Reader").build(); + em.persist(userEntity); + library = LibraryEntity.builder().name("Lib").icon("book").watch(false) + .formatPriority(List.of(BookFileType.EPUB)).build(); + em.persist(library); + libraryPath = LibraryPathEntity.builder().library(library).path("/p").build(); + em.persist(libraryPath); + when(authenticationService.getAuthenticatedUser()).thenReturn(nonAdminUser()); + } + + private BookLoreUser nonAdminUser() { + BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions(); + permissions.setAdmin(false); + return BookLoreUser.builder() + .id(userEntity.getId()) + .assignedLibraries(List.of(Library.builder().id(library.getId()).build())) + .permissions(permissions) + .build(); + } + + private void book(String title, String genre, String authorName) { + BookEntity bookEntity = BookEntity.builder() + .library(library).libraryPath(libraryPath).addedOn(Instant.now()).deleted(false).build(); + em.persist(bookEntity); + BookMetadataEntity metadata = BookMetadataEntity.builder().book(bookEntity).title(title).build(); + metadata.setCategories(java.util.Set.of(category(genre))); + metadata.setAuthors(List.of(author(authorName))); + em.persist(metadata); + bookEntity.setMetadata(metadata); + } + + private CategoryEntity category(String name) { + return categories.computeIfAbsent(name, n -> { + CategoryEntity e = CategoryEntity.builder().name(n).build(); + em.persist(e); + return e; + }); + } + + private AuthorEntity author(String name) { + return authors.computeIfAbsent(name, n -> { + AuthorEntity e = AuthorEntity.builder().name(n).build(); + em.persist(e); + return e; + }); + } + + private FacetGroup group(FacetGroupsResponse response, String key) { + return response.facets().stream() + .filter(g -> g.metadata() != null && key.equals(g.metadata().key())) + .findFirst().orElseThrow(); + } + + private Long count(FacetGroup group, String value) { + Optional link = group.links().stream().filter(l -> value.equals(l.value())).findFirst(); + return link.map(l -> l.properties().numberOfItems()).orElse(null); + } + + private FacetLink link(FacetGroup group, String value) { + return group.links().stream() + .filter(l -> value.equals(l.value())) + .findFirst().orElseThrow(); + } + + @Test + void countsDiscreteFacetsWithCounts() { + book("A", "Horror", "Alice"); + book("B", "Romance", "Bob"); + em.flush(); + + FacetGroupsResponse response = facetService.getFacets(null, null, null); + + assertThat(count(group(response, "genre"), "Horror")).isEqualTo(1); + assertThat(count(group(response, "genre"), "Romance")).isEqualTo(1); + assertThat(group(response, "author").links()).extracting(FacetLink::value).contains("Alice", "Bob"); + } + + @Test + void selectedFacetIsOmittedFromItsOwnCounts() { + book("A", "Horror", "Alice"); + book("B", "Horror", "Alice"); + book("C", "Romance", "Bob"); + em.flush(); + + FacetGroupsResponse response = facetService.getFacets(List.of("genre:Horror"), null, null); + + // genre omits itself: both Horror (2) and Romance (1) still appear with full counts. + assertThat(count(group(response, "genre"), "Horror")).isEqualTo(2); + assertThat(count(group(response, "genre"), "Romance")).isEqualTo(1); + + // a different facet honors the genre:Horror filter: only Horror authors remain. + assertThat(group(response, "author").links()).extracting(FacetLink::value).containsExactly("Alice"); + } + + @Test + void valuesAreOrderedByCountDescending() { + book("A", "Horror", "Alice"); + book("B", "Horror", "Alice"); + book("C", "Romance", "Bob"); + em.flush(); + + List genres = group(facetService.getFacets(null, null, null), "genre").links() + .stream().map(FacetLink::value).toList(); + assertThat(genres).containsExactly("Horror", "Romance"); + } + + @Test + void linksCarryAddHrefAndCount() { + book("A", "Horror", "Alice"); + em.flush(); + + FacetLink horror = link(group(facetService.getFacets(null, null, null), "genre"), "Horror"); + assertThat(horror.href()).isEqualTo("/api/v1/books/page?facet=genre%3AHorror"); + assertThat(horror.properties().numberOfItems()).isEqualTo(1); + assertThat(horror.rel()).containsExactly("facet"); + } + + @Test + void responseIsCachedPerParameters() { + book("A", "Horror", "Alice"); + em.flush(); + FacetGroupsResponse first = facetService.getFacets(null, null, null); + FacetGroupsResponse second = facetService.getFacets(null, null, null); + assertThat(first).isSameAs(second); + } + + @Test + void includesSortGroup() { + book("A", "Horror", "Alice"); + em.flush(); + FacetGroup sort = group(facetService.getFacets(null, null, null), "sort"); + assertThat(sort.metadata().rel()).isEqualTo("sort"); + assertThat(sort.links()).extracting(FacetLink::value).contains("title", "-title"); + assertThat(sort.links()).allSatisfy(l -> assertThat(l.rel()).containsExactly("sort")); + } + + @Test + void emptyFacetListBehavesLikeNullFacet() { + book("A", "Horror", "Alice"); + book("B", "Romance", "Bob"); + em.flush(); + + FacetGroupsResponse withNull = facetService.getFacets(null, null, null); + FacetGroupsResponse withEmpty = facetService.getFacets(List.of(), null, null); + + assertThat(count(group(withEmpty, "genre"), "Horror")).isEqualTo(count(group(withNull, "genre"), "Horror")); + assertThat(count(group(withEmpty, "genre"), "Romance")).isEqualTo(count(group(withNull, "genre"), "Romance")); + assertThat(count(group(withEmpty, "genre"), "Horror")).isEqualTo(1); + } + + @Test + void multipleSelectionsFilterAcrossFacets() { + book("A", "Horror", "Alice"); + book("B", "Horror", "Bob"); + book("C", "Romance", "Alice"); + em.flush(); + + FacetGroupsResponse response = facetService.getFacets(List.of("genre:Horror", "author:Alice"), null, null); + + assertThat(count(group(response, "genre"), "Horror")).isEqualTo(1); + assertThat(count(group(response, "genre"), "Romance")).isEqualTo(1); + + assertThat(count(group(response, "author"), "Alice")).isEqualTo(1); + assertThat(count(group(response, "author"), "Bob")).isEqualTo(1); + } + + @Test + void facetLogicCombinesSelectedValues() { + book("A", "Horror", "Alice"); + book("B", "Romance", "Bob"); + book("C", "Fantasy", "Cara"); + em.flush(); + + List genres = List.of("genre:Horror", "genre:Romance"); + + assertThat(group(facetService.getFacets(genres, "or", null), "author").links()) + .extracting(FacetLink::value).containsExactlyInAnyOrder("Alice", "Bob"); + + assertThat(group(facetService.getFacets(genres, "and", null), "author").links()).isEmpty(); + + assertThat(group(facetService.getFacets(genres, "not", null), "author").links()) + .extracting(FacetLink::value).containsExactly("Cara"); + } + + @Test + void truncatesValuesAtMax() { + for (int i = 0; i < 101; i++) { + book("T" + i, "Genre" + i, "Author" + i); + } + em.flush(); + + FacetGroupsResponse response = facetService.getFacets(null, null, null); + + assertThat(group(response, "genre").links()).hasSize(100); + assertThat(group(response, "author").links()).hasSize(100); + } + + @Test + void activeFacetIsMarkedSelfWithCurrentPageHref() { + book("A", "Horror", "Alice"); + book("B", "Romance", "Bob"); + em.flush(); + + FacetGroup genre = group(facetService.getFacets(List.of("genre:Horror"), null, null), "genre"); + FacetLink horror = link(genre, "Horror"); + FacetLink romance = link(genre, "Romance"); + + assertThat(horror.rel()).containsExactly("self", "facet"); + assertThat(horror.href()).isEqualTo("/api/v1/books/page?facet=genre%3AHorror"); + + assertThat(romance.rel()).containsExactly("facet"); + assertThat(romance.href()).isEqualTo("/api/v1/books/page?facet=genre%3AHorror&facet=genre%3ARomance"); + } + + @Test + void activeFacetSelfHrefKeepsAllSelections() { + book("A", "Horror", "Alice"); + em.flush(); + + FacetGroup genre = group(facetService.getFacets(List.of("genre:Horror", "author:Alice"), null, null), "genre"); + FacetLink horror = link(genre, "Horror"); + + assertThat(horror.rel()).containsExactly("self", "facet"); + assertThat(horror.href()).isEqualTo("/api/v1/books/page?facet=genre%3AHorror&facet=author%3AAlice"); + } + + @Test + void activeFacetMatchIsCaseInsensitive() { + book("A", "Horror", "Alice"); + em.flush(); + + FacetGroup genre = group(facetService.getFacets(List.of("genre:horror"), null, null), "genre"); + FacetLink horror = link(genre, "Horror"); + + assertThat(horror.rel()).contains("self"); + } + + @Test + void responseCarriesTopLevelSelfLink() { + book("A", "Horror", "Alice"); + em.flush(); + + Link bare = facetService.getFacets(null, null, null).links().getFirst(); + assertThat(bare.rel()).containsExactly("self"); + assertThat(bare.href()).isEqualTo("/api/v1/books/facets"); + assertThat(bare.type()).isEqualTo(Link.JSON_TYPE); + + Link filtered = facetService.getFacets(List.of("genre:Horror"), null, "dune").links().getFirst(); + assertThat(filtered.rel()).containsExactly("self"); + assertThat(filtered.href()).isEqualTo("/api/v1/books/facets?facet=genre%3AHorror&query=dune"); + } + + // Serializes through the Spring-managed Jackson 3 mapper, the same one the HTTP + // layer uses, so a mapper/annotation mismatch can't slip through unit tests again. + @Test + void springMapperSerializesSingleRelAsString() { + book("A", "Horror", "Alice"); + em.flush(); + + String json = springMapper.writeValueAsString(facetService.getFacets(List.of("genre:Horror"), null, null)); + + assertThat(json).contains("\"rel\":\"self\""); + assertThat(json).contains("\"rel\":[\"self\",\"facet\"]"); + assertThat(json).doesNotContain("\"rel\":[\"self\"]"); + assertThat(json).doesNotContain("\"rel\":[\"facet\"]"); + } +}