From 6fa154a2e7364f14920bb60b611fd82998c26523 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 16 Aug 2026 10:34:08 -0700 Subject: [PATCH] Adds alpha picker filtering to the books lite query --- .../Common/DTO/Filtering/LibraryFilterDto.cs | 13 ++ .../DTO/Filtering/LibraryItemAlphaKeys.cs | 20 +++ .../Books/GetBooksLiteRequestMapping.cs | 4 +- .../GetBooksLiteQueryValidator.cs | 10 ++ .../BookLibrary/Books/GetBooksLiteRequest.cs | 8 ++ .../Core/Repositories/Books/BookRepository.cs | 23 ++- .../BookAlphaFilterSpecification.cs | 132 ++++++++++++++++++ .../Common/Errors/Errors.Library.cs | 1 + .../GetBooksLite/GetBooksLiteQueryFixture.cs | 8 +- .../Books/GetBooksLiteRequestFixture.cs | 6 + .../GetBooksLite/GetBooksLiteEndpointTests.cs | 119 +++++++++++++++- .../GetBooksLiteQueryValidatorTests.cs | 42 ++++++ 12 files changed, 376 insertions(+), 10 deletions(-) create mode 100644 src/Lumina.Application/Common/DTO/Filtering/LibraryItemAlphaKeys.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs diff --git a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs index d594dcc4..6b77d3dc 100644 --- a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs +++ b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs @@ -13,4 +13,17 @@ public record LibraryFilterDto : BaseFilterDto /// The Id of the media library used to filter data. /// public required Guid LibraryId { get; init; } + + /// + /// The alpha key used to filter the data by the first character of the item title, for the alpha picker. + /// Can be to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter, + /// to filter by titles whose first character is a digit, + /// or to filter by titles whose first character is neither a letter nor a digit. + /// + public string? FilterAlphaKey { get; init; } + + /// + /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. + /// + public bool IgnoreThePrefixForAlphaPicker { get; init; } } diff --git a/src/Lumina.Application/Common/DTO/Filtering/LibraryItemAlphaKeys.cs b/src/Lumina.Application/Common/DTO/Filtering/LibraryItemAlphaKeys.cs new file mode 100644 index 00000000..03693b53 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Filtering/LibraryItemAlphaKeys.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +#endregion + +namespace Lumina.Application.Common.DTO.Filtering; + +/// +/// Collection of the special alpha keys that can be used for alpha filtering, in addition to the single letters. +/// +public static class LibraryItemAlphaKeys +{ + /// + /// The alpha key that filters the items by titles whose first character is a digit. + /// + public const string NUMBER = "#"; + + /// + /// The alpha key that filters the items by titles whose first character is neither a letter nor a digit. + /// + public const string SYMBOL = "*"; +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs index 3e7a2c3e..c3fa2f9f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs @@ -30,7 +30,9 @@ public static class GetBooksLiteRequestMapping LibraryFilterDto libraryFilter = new() { LibraryId = request.LibraryId, - SearchTerm = request.SearchTerm + SearchTerm = request.SearchTerm, + FilterAlphaKey = request.FilterAlphaKey, + IgnoreThePrefixForAlphaPicker = request.IgnoreThePrefixForAlphaPicker }; return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder); diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs index 78cb8a79..6c8fb14b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; @@ -22,5 +23,14 @@ public class GetBooksLiteQueryValidator : AbstractValidator .WithError(Errors.Library.LibraryIdCannotBeEmpty) .Must(id => id != Guid.Empty) .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // the alpha key must be exactly one of the three picker bucket kinds, so that the filter specification can + // derive the key of a title unambiguously: no filter, a number bucket, a symbol bucket, or a single ASCII letter + RuleFor(query => query.Filter.FilterAlphaKey) + .Must(alphaKey => alphaKey is null + || alphaKey == LibraryItemAlphaKeys.NUMBER + || alphaKey == LibraryItemAlphaKeys.SYMBOL + || (alphaKey.Length == 1 && char.IsAsciiLetter(alphaKey[0]))) + .WithError(Errors.Library.InvalidFilterAlphaKey); } } diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs index 4dbd3438..6a5a1dc1 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs @@ -13,6 +13,12 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// The page of results to retrieve. Optional. /// The maximum number of books to retrieve per page. Optional. /// The search term used to filter results. Optional. +/// +/// The alpha key used to filter the results by the first character of their title, for the alpha picker. Optional. +/// Can be to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter, +/// "#" to filter by titles whose first character is a digit, or "*" to filter by titles whose first character is neither a letter nor a digit. +/// +/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// The name of the field by which to sort the results. Optional. /// The direction in which to sort the results. Optional. [DebuggerDisplay("LibraryId: {LibraryId}")] @@ -21,6 +27,8 @@ public record GetBooksLiteRequest( int? CurrentPage, int? PerPage, string? SearchTerm, + string? FilterAlphaKey, + bool IgnoreThePrefixForAlphaPicker, string? SortBy, SortOrder? SortOrder ); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index 91e237c0..9d1e95b1 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -120,7 +120,7 @@ internal sealed class BookRepository : IBookRepository booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId); - FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter.SearchTerm); + FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter); // apply filtering if (filterSpecification is not null) booksQuery = booksQuery.Where(filterSpecification.ToExpression()); @@ -277,15 +277,24 @@ internal sealed class BookRepository : IBookRepository /// /// Builds a filter specification for querying books. /// - /// The search term used to filter results. + /// The model containing the parameters used to filter the results. /// A filter specification that can be used to query books matching the provided criteria. - private static FilterSpecification? BuildFilterSpecification(string? searchTerm) + private static FilterSpecification? BuildFilterSpecification(LibraryFilterDto libraryFilter) { FilterSpecification? filterSpecification = null; - - // include the search term filter here, if provided - if (!string.IsNullOrWhiteSpace(searchTerm)) - filterSpecification = new BookSearchSpecification(searchTerm); + + // include the search term filter, if provided + if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm)) + filterSpecification = new BookSearchSpecification(libraryFilter.SearchTerm); + + // include the alpha key filter, if provided + if (libraryFilter.FilterAlphaKey is not null) + { + BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.IgnoreThePrefixForAlphaPicker); + filterSpecification = filterSpecification is null + ? alphaFilterSpecification + : filterSpecification.And(alphaFilterSpecification); + } return filterSpecification; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs new file mode 100644 index 00000000..460726ec --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.Specifications; +using Microsoft.EntityFrameworkCore; +using System; +using System.Linq.Expressions; +using System.Reflection; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Books.Specifications; + +/// +/// Represents a filter specification for filtering books by the alpha key of their title, for the alpha picker. +/// The alpha key is the first character of the title, lowercased, and optionally computed after ignoring a leading "The " prefix. +/// +internal sealed class BookAlphaFilterSpecification : FilterSpecification +{ + private static readonly MethodInfo s_toLowerMethod = typeof(string).GetMethod(nameof(string.ToLower), Type.EmptyTypes)!; + private static readonly MethodInfo s_startsWithMethod = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!; + private static readonly MethodInfo s_substringMethod = typeof(string).GetMethod(nameof(string.Substring), [typeof(int)])!; + private static readonly MethodInfo s_globMethod = typeof(SqliteDbFunctionsExtensions) + .GetMethod(nameof(SqliteDbFunctionsExtensions.Glob), [typeof(DbFunctions), typeof(string), typeof(string)])!; + + private readonly string? _filterAlphaKey; + private readonly bool _ignoreThePrefixForAlphaPicker; + + /// + /// Initializes a new instance of the class. + /// + /// The alpha key to filter by. A single ASCII letter, , or . + /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. + public BookAlphaFilterSpecification(string? filterAlphaKey, bool ignoreThePrefixForAlphaPicker) + { + _filterAlphaKey = filterAlphaKey; + _ignoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + } + + /// + /// Creates a LINQ expression that represents the predicate defined by the current specification. + /// + /// An expression tree that can be used to evaluate whether a satisfies the specification criteria. + public override Expression> ToExpression() + { + // when no alpha key was requested, every book matches + if (_filterAlphaKey is null) + return book => true; + + ParameterExpression book = Expression.Parameter(typeof(BookEntity), "book"); + Expression effectiveTitle = BuildEffectiveTitle(book); + + if (_filterAlphaKey == LibraryItemAlphaKeys.NUMBER) + return BuildGlobPredicate(book, effectiveTitle, "[0-9]*"); + + if (_filterAlphaKey == LibraryItemAlphaKeys.SYMBOL) + return BuildSymbolPredicate(book, effectiveTitle); + + // the alpha key is a single ASCII letter + string globPattern = char.ToLowerInvariant(_filterAlphaKey[0]) + "*"; + return BuildGlobPredicate(book, effectiveTitle, globPattern); + } + + /// + /// Builds the expression representing the lowercased title used to derive the alpha key, falling back to the original title + /// when the title is or empty, and optionally stripped of a leading "the " prefix. + /// + /// The parameter representing the book entity. + /// The expression of the effective title. + private Expression BuildEffectiveTitle(ParameterExpression book) + { + Expression titleProperty = Expression.Property(book, nameof(BookEntity.Title)); + + // the raw title: the title, unless it is null or empty, in which case the original title (or an empty string) is used + BinaryExpression isTitleMissing = Expression.OrElse( + Expression.Equal(titleProperty, Expression.Constant(null, typeof(string))), + Expression.Equal(titleProperty, Expression.Constant(string.Empty))); + Expression rawTitle = Expression.Condition(isTitleMissing, + Expression.Coalesce(Expression.Property(book, nameof(BookEntity.OriginalTitle)), Expression.Constant(string.Empty)), + titleProperty); + + MethodCallExpression lowerTitle = Expression.Call(rawTitle, s_toLowerMethod); + + // when ignoring the "The " prefix, strip a leading "the " from the lowercased title + Expression effectiveTitle = lowerTitle; + if (_ignoreThePrefixForAlphaPicker) + { + MethodCallExpression startsWithThe = Expression.Call(lowerTitle, s_startsWithMethod, Expression.Constant("the ")); + MethodCallExpression strippedTitle = Expression.Call(lowerTitle, s_substringMethod, Expression.Constant(4)); + effectiveTitle = Expression.Condition(startsWithThe, strippedTitle, lowerTitle); + } + + return effectiveTitle; + } + + /// + /// Builds a predicate that is satisfied when the effective title starts with a glob pattern. + /// + /// The parameter representing the book entity. + /// The expression of the effective title. + /// The glob pattern the effective title must match. + /// The built predicate. + private static Expression> BuildGlobPredicate(ParameterExpression book, Expression effectiveTitle, string globPattern) + { + MethodCallExpression glob = BuildGlobCall(effectiveTitle, globPattern); + return Expression.Lambda>(glob, book); + } + + /// + /// Builds a predicate that is satisfied when the first character of the effective title is neither a letter nor a digit. + /// + /// The parameter representing the book entity. + /// The expression of the effective title. + /// The built predicate. + private static Expression> BuildSymbolPredicate(ParameterExpression book, Expression effectiveTitle) + { + Expression notLetter = Expression.Not(BuildGlobCall(effectiveTitle, "[a-z]*")); + Expression notDigit = Expression.Not(BuildGlobCall(effectiveTitle, "[0-9]*")); + return Expression.Lambda>(Expression.AndAlso(notLetter, notDigit), book); + } + + /// + /// Builds the call to for the effective title and the provided glob pattern. + /// + /// The expression of the effective title. + /// The glob pattern the effective title must match. + /// The built method call. + private static MethodCallExpression BuildGlobCall(Expression effectiveTitle, string globPattern) + { + Expression functions = Expression.Property(null, typeof(EF), nameof(EF.Functions)); + return Expression.Call(s_globMethod, functions, effectiveTitle, Expression.Constant(globPattern)); + } +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs index 88aca409..906b5c69 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -15,6 +15,7 @@ public static partial class Errors public static Error CannotScanDisabledLibrary => Error.Forbidden(description: nameof(CannotScanDisabledLibrary)); public static Error LibraryIdCannotBeEmpty => Error.Validation(description: nameof(LibraryIdCannotBeEmpty)); public static Error FilterMustIncludeLibraryId => Error.Validation(description: nameof(FilterMustIncludeLibraryId)); + public static Error InvalidFilterAlphaKey => Error.Validation(description: nameof(InvalidFilterAlphaKey)); public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists)); public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound)); public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull)); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs index c23b0a8b..c7a7d0d9 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs @@ -26,6 +26,8 @@ public class GetBooksLiteQueryFixture /// Optional. The Id of the media library whose books are retrieved. /// Optional. The pagination data of the query. /// Optional. The search term used to filter results. + /// Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker. + /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. /// The created query to get the lightweight details of books. @@ -33,6 +35,8 @@ public class GetBooksLiteQueryFixture Guid? libraryId = null, PaginationDataDto? paginationData = null, string? searchTerm = null, + string? filterAlphaKey = null, + bool ignoreThePrefixForAlphaPicker = false, string? sortBy = null, SortOrder? sortOrder = null) { @@ -45,7 +49,9 @@ public class GetBooksLiteQueryFixture new LibraryFilterDto { LibraryId = libraryId ?? _faker.Random.Guid(), - SearchTerm = searchTerm + SearchTerm = searchTerm, + FilterAlphaKey = filterAlphaKey, + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker }, sortBy, sortOrder ?? _faker.PickRandom() diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs index 1d943636..ea878333 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs @@ -25,6 +25,8 @@ public class GetBooksLiteRequestFixture /// Optional. The page of results to retrieve. /// Optional. The maximum number of books to retrieve per page. /// Optional. The search term used to filter results. + /// Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker. + /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. /// The created . @@ -33,6 +35,8 @@ public class GetBooksLiteRequestFixture int? currentPage = null, int? perPage = null, string? searchTerm = null, + string? filterAlphaKey = null, + bool ignoreThePrefixForAlphaPicker = false, string? sortBy = null, SortOrder? sortOrder = null) { @@ -41,6 +45,8 @@ public class GetBooksLiteRequestFixture CurrentPage: currentPage ?? _faker.Random.Number(1, 100), PerPage: perPage ?? _faker.Random.Number(1, 200), SearchTerm: searchTerm ?? _faker.Lorem.Word(), + FilterAlphaKey: filterAlphaKey, + IgnoreThePrefixForAlphaPicker: ignoreThePrefixForAlphaPicker, SortBy: sortBy ?? _faker.Lorem.Word(), SortOrder: sortOrder ?? _faker.PickRandom() ); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index 6b39fd29..9071aed8 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -82,6 +82,121 @@ public class GetBooksLiteEndpointTests : IClassFixture book.Title == "Book B"); } + [Fact] + public async Task GetBooksLite_WhenCalledWithFilterAlphaKeyLetter_ShouldReturnOnlyBooksStartingWithThatLetter() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Quiet Place"); + await SeedBookAsync(libraryId, "The Quiet"); + await SeedBookAsync(libraryId, "Racing"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=q"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + BookLiteResponse book = Assert.Single(paginatedBooks!.Data); + Assert.Equal("Quiet Place", book.Title); + Assert.Equal(1, paginatedBooks.Count); + } + + [Fact] + public async Task GetBooksLite_WhenCalledWithFilterAlphaKeyLetterAndIgnoreThePrefix_ShouldIncludeThePrefixedTitles() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Quiet Place"); + await SeedBookAsync(libraryId, "The Quiet"); + await SeedBookAsync(libraryId, "Racing"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=q&ignoreThePrefixForAlphaPicker=true"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(2, paginatedBooks!.Count); + Assert.Contains(paginatedBooks.Data, book => book.Title == "Quiet Place"); + Assert.Contains(paginatedBooks.Data, book => book.Title == "The Quiet"); + } + + [Fact] + public async Task GetBooksLite_WhenCalledWithFilterAlphaKeyNumber_ShouldReturnOnlyBooksStartingWithADigit() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "1984"); + await SeedBookAsync(libraryId, "7 Habits of Highly Effective People"); + await SeedBookAsync(libraryId, "Brave New World"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=%23"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(2, paginatedBooks!.Count); + Assert.Contains(paginatedBooks.Data, book => book.Title == "1984"); + Assert.Contains(paginatedBooks.Data, book => book.Title == "7 Habits of Highly Effective People"); + } + + [Fact] + public async Task GetBooksLite_WhenCalledWithFilterAlphaKeySymbol_ShouldReturnOnlyBooksStartingWithASymbol() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "!Important"); + await SeedBookAsync(libraryId, "1984"); + await SeedBookAsync(libraryId, "Alpha"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=%2A"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + BookLiteResponse book = Assert.Single(paginatedBooks!.Data); + Assert.Equal("!Important", book.Title); + Assert.Equal(1, paginatedBooks.Count); + } + + [Fact] + public async Task GetBooksLite_WhenTitleIsEmptyAndFilterAlphaKeyIsProvided_ShouldUseOriginalTitle() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "", "Rendezvous"); + await SeedBookAsync(libraryId, "Racing"); + await SeedBookAsync(libraryId, "Quiet Place"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=r"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(2, paginatedBooks!.Count); + Assert.Contains(paginatedBooks.Data, book => book.Title == ""); // the empty title book matches the filter through its original title + Assert.Contains(paginatedBooks.Data, book => book.Title == "Racing"); + } + [Fact] public async Task GetBooksLite_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingBooks() { @@ -204,8 +319,9 @@ public class GetBooksLiteEndpointTests : IClassFixture /// The Id of the media library the book belongs to. /// The title of the book. + /// Optional. The original title of the book. /// A task representing the asynchronous operation. - private async Task SeedBookAsync(Guid libraryId, string title) + private async Task SeedBookAsync(Guid libraryId, string title, string? originalTitle = null) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -215,6 +331,7 @@ public class GetBooksLiteEndpointTests : IClassFixture result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.InvalidFilterAlphaKey); + } + + [Fact] + public void Validate_WhenFilterAlphaKeyIsASingleLetter_ShouldNotHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + query = query with { Filter = query.Filter with { FilterAlphaKey = "Q" } }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Fact] + public void Validate_WhenFilterAlphaKeyIsNumberOrSymbol_ShouldNotHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + query = query with { Filter = query.Filter with { FilterAlphaKey = "#" } }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } }