From 1d35cd01dbf45ee38f9cbe229cbc84567eb1eacc Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 13 Sep 2026 04:16:59 -0700 Subject: [PATCH] Refactors the get books and get books lite slices across the stack --- .../book-library/Api.Books.md | 55 +++- .../book-library/books/GetBooks.http | 3 +- .../book-library/books/GetBooksLite.http | 2 +- .../BookLibrary/BookLiteRow.cs | 31 ++ .../Actions/IGetAllLiteRepositoryAction.cs | 35 +++ .../BookLibrary/Books/BookEntityMapping.cs | 42 --- .../BookLibrary/Books/BookLiteRowMapping.cs | 57 ++++ .../Books/GetBooksLiteRequestMapping.cs | 22 +- .../Books/GetBooksRequestMapping.cs | 12 +- .../Books/Queries/GetBooks/GetBooksQuery.cs | 7 +- .../Queries/GetBooks/GetBooksQueryHandler.cs | 24 +- .../GetBooks/GetBooksQueryValidator.cs | 10 +- .../Queries/GetBooksLite/GetBooksLiteQuery.cs | 11 +- .../GetBooksLite/GetBooksLiteQueryHandler.cs | 31 +- .../GetBooksLiteQueryValidator.cs | 12 +- .../BookLibrary/Books/GetBooksLiteRequest.cs | 5 +- .../BookLibrary/Books/GetBooksRequest.cs | 5 +- .../Core/Repositories/Books/BookRepository.cs | 25 +- .../Books/GetBooks/GetBooksEndpoint.cs | 10 +- .../Books/GetBooks/GetBooksEndpointSummary.cs | 86 +++--- .../GetBooksLite/GetBooksLiteEndpoint.cs | 10 +- .../GetBooksLiteEndpointSummary.cs | 38 ++- .../BookLibrary/BookLiteRowFixture.cs | 52 ++++ .../Queries/GetBooks/GetBooksQueryFixture.cs | 23 +- .../GetBooksLite/GetBooksLiteQueryFixture.cs | 27 +- .../Books/GetBooksLiteRequestFixture.cs | 4 - .../Books/GetBooksRequestFixture.cs | 4 - .../Books/GetBooks/GetBooksEndpointTests.cs | 199 ++++++++++++- .../GetBooksLite/GetBooksLiteEndpointTests.cs | 219 +++++++++++++- .../Books/GetBooks/GetBooksEndpointTests.cs | 62 +++- .../GetBooksLite/GetBooksLiteEndpointTests.cs | 62 +++- .../Books/BookEntityMappingTests.cs | 69 ----- .../Books/BookLiteRowMappingTests.cs | 80 ++++++ .../Books/GetBooksLiteRequestMappingTests.cs | 50 +++- .../Books/GetBooksRequestMappingTests.cs | 48 +++- .../GetBooks/GetBooksQueryHandlerTests.cs | 50 ++-- .../GetBooks/GetBooksQueryValidatorTests.cs | 54 +++- .../GetBooksLiteQueryHandlerTests.cs | 69 +++-- .../GetBooksLiteQueryValidatorTests.cs | 54 +++- .../Books/GetBooksLiteRequestTests.cs | 18 +- .../BookLibrary/Books/GetBooksRequestTests.cs | 18 +- .../Repositories/Books/BookRepositoryTests.cs | 270 ++++++++++++++++++ .../Books/GetBooks/GetBooksEndpointTests.cs | 66 ++++- .../GetBooksLite/GetBooksLiteEndpointTests.cs | 68 ++++- 44 files changed, 1681 insertions(+), 418 deletions(-) create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllLiteRepositoryAction.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMapping.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMappingTests.cs diff --git a/docs/technical/api/library/written-content-library/book-library/Api.Books.md b/docs/technical/api/library/written-content-library/book-library/Api.Books.md index fa93fdc1..483bed8b 100644 --- a/docs/technical/api/library/written-content-library/book-library/Api.Books.md +++ b/docs/technical/api/library/written-content-library/book-library/Api.Books.md @@ -17,6 +17,9 @@ - [Update Book](#update-book) - [Update Book Request](#update-book-request) - [Update Book Response](#update-book-response) + - [Update Book Cover](#update-book-cover) + - [Update Book Cover Request](#update-book-cover-request) + - [Update Book Cover Response](#update-book-cover-response) - [Get Reading Availability](#get-reading-availability) - [Get Reading Availability Request](#get-reading-availability-request) - [Get Reading Availability Response](#get-reading-availability-response) @@ -321,9 +324,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&pe "format": "Paperback", "edition": "50th Anniversary Edition", "volumeNumber": 1, - "series": { - "title": "The Lord of the Rings" - }, + "series": null, "asin": "B007978NPG", "goodreadsId": "3", "lccn": "54009621", @@ -343,20 +344,30 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&pe "format": "Isbn13" } ], - "contributors": [], + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } + ], "ratings": [ { "source": "GoogleBooks", "value": 4.36, "maxValue": 5, "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 } ], "metadataStatus": "Pending", "lastMetadataUpdateUtc": null, "metadataProvider": null, "createdOnUtc": "2025-01-01T12:00:00.0000000Z", - "updatedOnUtc": null + "updatedOnUtc": null, + "coverPath": null } ], "currentPage": 1, @@ -371,7 +382,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&pe #### Get Books Lite Request ```js -GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite?currentPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&ignoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite?currentPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&shouldIgnoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending ``` | Query Parameter | Type | Description | @@ -380,7 +391,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite?currentPage | `perPage` | `int` | Optional. The maximum number of books to retrieve per page. | | `searchTerm` | `string` | Optional. The search term used to filter results. | | `filterAlphaKey` | `string` | Optional. Filters results by the first character of their title. A single ASCII letter (case-insensitive), `#` for titles starting with a digit, or `*` for titles starting with any other character. | -| `ignoreThePrefixForAlphaPicker` | `bool` | Whether the leading "The " prefix of a title should be ignored when computing the alpha key. | +| `shouldIgnoreThePrefixForAlphaPicker` | `bool` | Whether the leading "The " prefix of a title should be ignored when computing the alpha key. | | `sortBy` | `string` | Optional. The name of the field by which to sort the results. | | `sortOrder` | `string` | Optional. The direction in which to sort the results (`Ascending` or `Descending`). | @@ -612,6 +623,36 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId} } ``` +### Update Book Cover + +Updates the cover image of the book identified by `bookId` with the image uploaded in the multipart form of the request. The book must belong to the media library identified by `libraryId`, and the uploaded file must be an image. + +#### Update Book Cover Request + +```js +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/cover +Content-Type: multipart/form-data; boundary=LuminaBoundary + +--LuminaBoundary +Content-Disposition: form-data; name="cover"; filename="cover.jpg" +Content-Type: image/jpeg + +< ./cover.jpg +--LuminaBoundary-- +``` + +#### Update Book Cover Response + +```js +200 Ok +``` + +```json +{ + "coverPath": "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" +} +``` + ### Get Reading Availability #### Get Reading Availability Request diff --git a/docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http b/docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http index f8d5d229..48920207 100644 --- a/docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http +++ b/docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http @@ -1 +1,2 @@ -GET {{host}}/api/v1/books?libraryId={{$guid}} \ No newline at end of file +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&perPage=10&searchTerm=fellowship&sortBy=title&sortOrder=Ascending +Authorization: Bearer {{ACCESS_TOKEN}} \ No newline at end of file diff --git a/docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http b/docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http index 609dbb6f..7f67672b 100644 --- a/docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http +++ b/docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/books/lite?libraryId={{$guid}}¤tPage=1&perPage=10 +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite?currentPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&shouldIgnoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs new file mode 100644 index 00000000..9a2e1b96 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Lightweight read model of a book, containing only the fields needed to display the book in a card-based grid or a list. +/// +public sealed record BookLiteRow +{ + /// + /// Gets the Id of the book. + /// + public required Guid Id { get; init; } + + /// + /// Gets the title of the book. + /// + public required string Title { get; init; } + + /// + /// Gets the release year of the book (re-release year, if available, or original release year), if known. + /// + public int? ReleaseYear { get; init; } + + /// + /// Gets the path of the image representing the cover of the book, if available. + /// + public string? CoverPath { get; init; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllLiteRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllLiteRepositoryAction.cs new file mode 100644 index 00000000..98a5a7a2 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllLiteRepositoryAction.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; + +/// +/// Interface defining the "get all lite" action for interacting with a generic persistence medium. +/// It retrieves lightweight read models of the stored data, projecting only the fields needed to display +/// the data in grids or card-based navigation, without loading the full entities and their related data. +/// +/// The type stored in the persistence medium, which is projected into the lightweight read models. It should implement . +/// The type of the lightweight read models returned by the action. +public interface IGetAllLiteRepositoryAction where TModel : IStorageEntity +{ + /// + /// Gets the lightweight read models of type , projected from the data of type stored in the storage medium. + /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching data is returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. + /// Cancellation token that can be used to stop the execution. + /// An containing either a paginated result of type , or an error. + Task>> GetAllLiteAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool includeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto; +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index 7a502f5a..767494a0 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -256,46 +256,4 @@ public static class BookEntityMapping NumberOfPages = repositoryEntities.NumberOfPages }; } - - /// - /// Converts to . - /// - /// The repository entity to be converted. - /// The converted response entity. - public static BookLiteResponse ToLiteResponse(this BookEntity repositoryEntity) - { - return new BookLiteResponse( - repositoryEntity.Id, - repositoryEntity.Title, - repositoryEntity.ReReleaseYear ?? repositoryEntity.OriginalReleaseYear, - repositoryEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName - ); - } - - /// - /// Converts to a collection of . - /// - /// The repository entities to be converted. - /// The converted reponses. - public static IReadOnlyList ToLiteResponses(this IEnumerable repositoryEntities) - { - return [.. repositoryEntities.Select(repositoryEntity => repositoryEntity.ToLiteResponse())]; - } - - /// - /// Converts to a paginated collection of . - /// - /// The paginated repository entities to be converted. - /// The converted paginated responses. - public static PaginatedResponse ToLiteResponses(this PaginatedResultDto repositoryEntities) - { - return new PaginatedResponse - { - Data = repositoryEntities.Data.ToLiteResponses(), - CurrentPage = repositoryEntities.CurrentPage, - PerPage = repositoryEntities.PerPage, - Count = repositoryEntities.Count, - NumberOfPages = repositoryEntities.NumberOfPages - }; - } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMapping.cs new file mode 100644 index 00000000..4553d134 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMapping.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class BookLiteRowMapping +{ + /// + /// Converts to . + /// + /// The read model to be converted. + /// The converted response. + public static BookLiteResponse ToResponse(this BookLiteRow readModel) + { + return new BookLiteResponse( + readModel.Id, + readModel.Title, + readModel.ReleaseYear, + readModel.CoverPath); + } + + /// + /// Converts to a collection of . + /// + /// The read models to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable readModels) + { + return [.. readModels.Select(readModel => readModel.ToResponse())]; + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated read models to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto readModels) + { + return new PaginatedResponse + { + Data = readModels.Data.ToResponses(), + CurrentPage = readModels.CurrentPage, + PerPage = readModels.PerPage, + Count = readModels.Count, + NumberOfPages = readModels.NumberOfPages + }; + } +} 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 8635f179..8db47b81 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 @@ -16,26 +16,26 @@ public static class GetBooksLiteRequestMapping /// Converts to . /// /// The request to be converted. + /// The Id of the library whose books are retrieved, taken from the route. /// The converted query. - public static GetBooksLiteQuery ToQuery(this GetBooksLiteRequest request) + public static GetBooksLiteQuery ToQuery(this GetBooksLiteRequest request, string? libraryId) { PaginationDataDto? paginationData = null; if (request.CurrentPage is not null || request.PerPage is not null) - { paginationData = new PaginationDataDto { CurrentPage = request.CurrentPage ?? 1, PerPage = request.PerPage ?? 200 }; - } - LibraryFilterDto libraryFilter = new() - { - LibraryId = request.LibraryId, - SearchTerm = request.SearchTerm, - FilterAlphaKey = request.FilterAlphaKey, - ShouldIgnoreThePrefixForAlphaPicker = request.ShouldIgnoreThePrefixForAlphaPicker - }; - return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder); + return new GetBooksLiteQuery( + libraryId, + paginationData, + request.SearchTerm, + request.FilterAlphaKey, + request.ShouldIgnoreThePrefixForAlphaPicker, + request.SortBy, + request.SortOrder + ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs index a1f6b92f..be96f193 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -16,8 +15,9 @@ public static class GetBooksRequestMapping /// Converts to . /// /// The request to be converted. + /// The Id of the library whose books are retrieved, taken from the route. /// The converted query. - public static GetBooksQuery ToQuery(this GetBooksRequest request) + public static GetBooksQuery ToQuery(this GetBooksRequest request, string? libraryId) { PaginationDataDto? paginationData = null; if (request.CurrentPage is not null || request.PerPage is not null) @@ -27,12 +27,6 @@ public static class GetBooksRequestMapping PerPage = request.PerPage ?? 200 }; - LibraryFilterDto libraryFilter = new() - { - LibraryId = request.LibraryId, - SearchTerm = request.SearchTerm - }; - - return new GetBooksQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder); + return new GetBooksQuery(libraryId, paginationData, request.SearchTerm, request.SortBy, request.SortOrder); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs index 480017ba..624241ea 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Domain.SharedKernel.Common.Enums.Common; #endregion @@ -10,13 +9,15 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for getting all the books of a media library. /// +/// The unique identifier of the media library whose books are retrieved, taken from the route. /// The object containing the requested pagination data. -/// The object containing the criteria used to filter the results. +/// The search term used to filter results. /// The name of the field by which to sort the results. /// The direction in which to sort the results. public record GetBooksQuery( + string? LibraryId, PaginationDataDto? PaginationData, - LibraryFilterDto Filter, + string? SearchTerm, string? SortBy, SortOrder? SortOrder ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index c75ec08b..37e02511 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -16,6 +16,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; #endregion @@ -60,25 +61,34 @@ public class GetBooksQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can see all libraries; for everyone else, only the libraries they own + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see all libraries; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(query.Filter.LibraryId), cancellationToken).ConfigureAwait(false); + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return Errors.Authorization.NotAuthorized; - // get all books of the media library from the book repository - Result> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync( + // Get all books of the media library from the book repository. + LibraryFilterDto libraryFilter = new() + { + LibraryId = libraryId, + SearchTerm = query.SearchTerm + }; + Result> getBooksResult = await _unitOfWork.BookRepository.GetAllAsync( query.PaginationData, query.SortBy, query.SortOrder, - query.Filter, - cancellationToken).ConfigureAwait(false); + libraryFilter, + shouldTrackEntities: false, + cancellationToken: cancellationToken).ConfigureAwait(false); return getBooksResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs index d091269c..efa69a03 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs @@ -17,10 +17,14 @@ public class GetBooksQueryValidator : AbstractValidator /// public GetBooksQueryValidator() { - RuleFor(query => query.Filter.LibraryId) + // Validates the identifier of the media library whose books are retrieved, taken from the route. + RuleFor(query => query.LibraryId) .NotEmpty() - .WithError(Errors.Library.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) .WithError(Errors.Library.LibraryIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs index 87dd8ef0..8c5f420b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Domain.SharedKernel.Common.Enums.Common; #endregion @@ -10,13 +9,19 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for getting the lightweight details of all the books of a media library. /// +/// The unique identifier of the media library whose books are retrieved, taken from the route. /// The object containing the requested pagination data. -/// The object containing the criteria used to filter the results. +/// The search term used to filter results. +/// The alpha key used to filter results by the first character of their title. +/// 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. /// The direction in which to sort the results. public record GetBooksLiteQuery( + string? LibraryId, PaginationDataDto? PaginationData, - LibraryFilterDto Filter, + string? SearchTerm, + string? FilterAlphaKey, + bool ShouldIgnoreThePrefixForAlphaPicker, string? SortBy, SortOrder? SortOrder ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs index 79c58486..f3b734ae 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -16,6 +16,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; #endregion @@ -60,25 +61,37 @@ public class GetBooksLiteQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can see all libraries; for everyone else, only the libraries they own + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see all libraries; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(query.Filter.LibraryId), cancellationToken).ConfigureAwait(false); + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return Errors.Authorization.NotAuthorized; - // get all books of the media library from the book repository - Result> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync( + LibraryFilterDto libraryFilter = new() + { + LibraryId = libraryId, + SearchTerm = query.SearchTerm, + FilterAlphaKey = query.FilterAlphaKey, + ShouldIgnoreThePrefixForAlphaPicker = query.ShouldIgnoreThePrefixForAlphaPicker + }; + + // Get the lightweight read models of the books of the media library from the book repository, projecting only the fields needed for a grid or a list. + Result> getBooksResult = await _unitOfWork.BookRepository.GetAllLiteAsync( query.PaginationData, query.SortBy, query.SortOrder, - query.Filter, - cancellationToken).ConfigureAwait(false); - return getBooksResult.Match(value => Result.From(value.ToLiteResponses()), errors => errors); + libraryFilter, + shouldTrackEntities: false, + cancellationToken: cancellationToken).ConfigureAwait(false); + return getBooksResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs index ba7c48eb..0eff4157 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs @@ -18,15 +18,19 @@ public class GetBooksLiteQueryValidator : AbstractValidator /// public GetBooksLiteQueryValidator() { - RuleFor(query => query.Filter.LibraryId) + // Validates the identifier of the media library whose books are retrieved, taken from the route. + RuleFor(query => query.LibraryId) .NotEmpty() - .WithError(Errors.Library.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) .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) + RuleFor(query => query.FilterAlphaKey) .Must(alphaKey => alphaKey is null || alphaKey == LibraryItemAlphaKeys.NUMBER || alphaKey == LibraryItemAlphaKeys.SYMBOL 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 03b500ac..a49e34f4 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Diagnostics; #endregion @@ -9,7 +8,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// /// Represents a request to get the lightweight details of the books of a media library. /// -/// The Id of the media library whose books are retrieved. Required. /// 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. @@ -21,9 +19,8 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// 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}")] +[DebuggerDisplay("SearchTerm: {SearchTerm}")] public record GetBooksLiteRequest( - Guid LibraryId, int? CurrentPage, int? PerPage, string? SearchTerm, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs index 257a402b..d23a3a14 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Diagnostics; #endregion @@ -9,15 +8,13 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// /// Represents a request to get the books of a media library. /// -/// The Id of the media library whose books are retrieved. Required. /// 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 name of the field by which to sort the results. Optional. /// The direction in which to sort the results. Optional. -[DebuggerDisplay("LibraryId: {LibraryId}")] +[DebuggerDisplay("SearchTerm: {SearchTerm}")] public record GetBooksRequest( - Guid LibraryId, int? CurrentPage, int? PerPage, string? SearchTerm, diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index 03db98dd..9bd6f22e 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -105,7 +105,6 @@ internal sealed class BookRepository : IBookRepository return await query.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false); } - /// /// /// Gets paginated books, or all the books of the matching filters when the pagination data is . /// @@ -191,18 +190,32 @@ internal sealed class BookRepository : IBookRepository /// The name of the fields by which to sort the results. /// The direction in which to sort the results. /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. /// An containing either a , or an error. - public async Task>> GetAllLiteAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto + public async Task>> GetAllLiteAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool includeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { // Books should always be retrieved only per owning libraries. if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty) return Errors.Library.FilterMustIncludeLibraryId; - // The lightweight read models are always retrieved without tracking, because they are never modified by the caller. - IQueryable booksQuery = _luminaDbContext.Books - .AsNoTracking() - .Where(book => book.LibraryId == libraryFilter.LibraryId); + // The lightweight read models are retrieved without tracking by default, because they are never modified by the caller. + IQueryable booksQuery = _luminaDbContext.Books; + if (!shouldTrackEntities) + booksQuery = booksQuery.AsNoTracking(); + if (includeNavigationProperties) + { + booksQuery = booksQuery + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.BookContributors) + .Include(book => book.BookArtwork); + } + + booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId); FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter); if (filterSpecification is not null) diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs index 47183f75..bcd48163 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs @@ -18,7 +18,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; /// -/// API endpoint for the /books route. +/// API endpoint for the /{libraryId}/books route. /// public class GetBooksEndpoint : BaseEndpoint { @@ -45,13 +45,15 @@ public class GetBooksEndpoint : BaseEndpoint } /// - /// Gets the list of all the books of the media library identified by . + /// Gets the list of all the books of the media library identified by the libraryId route parameter. /// - /// The request containing the Id of the media library whose books are retrieved. + /// The request containing the filtering and pagination options of the books to be retrieved. /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBooksRequest request, CancellationToken cancellationToken) { - Result> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(libraryId), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs index 1d3841f1..c4421c7c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs @@ -27,25 +27,29 @@ public class GetBooksEndpointSummary : Summary public GetBooksEndpointSummary() { - Summary = "Retrieves the list of books."; - Description = "Returns the entire list of books."; + Summary = "Retrieves the list of books of a media library."; + Description = "Returns the paginated, filterable list of the books of the media library identified by the request, with the full details of each book. The page is returned to an Admin, who can see the books of all libraries, or to the owner of the library."; ExampleRequest = new GetBooksRequest( - LibraryId: Guid.NewGuid(), CurrentPage: 1, - PerPage: 48, + PerPage: 10, SearchTerm: "fellowship", SortBy: "title", SortOrder: SortOrder.Ascending ); - RequestParam(r => r.LibraryId, "The Id of the media library whose books are retrieved. Required."); RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional."); RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional."); RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); + ResponseParam>(r => r.Data, "The books on the current page, each with the full details of the book."); + ResponseParam>(r => r.CurrentPage, "The current page number."); + ResponseParam>(r => r.PerPage, "The number of books retrieved per page."); + ResponseParam>(r => r.Count, "The total number of books matching the request."); + ResponseParam>(r => r.NumberOfPages, "The total number of pages."); + Response(200, "The paginated list of books is returned.", example: new PaginatedResponse { @@ -93,9 +97,7 @@ public class GetBooksEndpointSummary : Summary { { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs index 51341186..7269c4a9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; /// -/// API endpoint for the /books/lite route. +/// API endpoint for the /{libraryId}/books/lite route. /// public class GetBooksLiteEndpoint : BaseEndpoint { @@ -44,13 +44,15 @@ public class GetBooksLiteEndpoint : BaseEndpoint } /// - /// Gets the lightweight details of all the books of the media library identified by . + /// Gets the lightweight details of all the books of the media library identified by the libraryId route parameter. /// - /// The request containing the Id of the media library whose books are retrieved. + /// The request containing the filtering and pagination options of the books to be retrieved. /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBooksLiteRequest request, CancellationToken cancellationToken) { - Result> result = await _getBooksLiteQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getBooksLiteQueryHandler.HandleAsync(request.ToQuery(libraryId), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs index 14be3df3..369ccea7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs @@ -22,13 +22,12 @@ public class GetBooksLiteEndpointSummary : Summary public GetBooksLiteEndpointSummary() { - Summary = "Retrieves the lightweight details of the list of books."; - Description = "Returns a paginated list of the lightweight details of the books of the media library, suitable for card-style navigation."; + Summary = "Retrieves the list of lightweight book details of a media library."; + Description = "Returns the paginated, filterable list of the lightweight details of the books of the media library identified by the request, suitable for card-style navigation. The page is returned to an Admin, who can see the books of all libraries, or to the owner of the library."; ExampleRequest = new GetBooksLiteRequest( - LibraryId: Guid.NewGuid(), CurrentPage: 1, - PerPage: 48, + PerPage: 10, SearchTerm: "fellowship", FilterAlphaKey: "f", ShouldIgnoreThePrefixForAlphaPicker: true, @@ -36,7 +35,6 @@ public class GetBooksLiteEndpointSummary : Summary r.LibraryId, "The Id of the media library whose books are retrieved. Required."); RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional."); RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); @@ -45,6 +43,12 @@ public class GetBooksLiteEndpointSummary : Summary r.SortBy, "The name of the field by which to sort the results. Optional."); RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); + ResponseParam>(r => r.Data, "The lightweight book details on the current page."); + ResponseParam>(r => r.CurrentPage, "The current page number."); + ResponseParam>(r => r.PerPage, "The number of books retrieved per page."); + ResponseParam>(r => r.Count, "The total number of books matching the request."); + ResponseParam>(r => r.NumberOfPages, "The total number of pages."); + Response(200, "The paginated list of lightweight book details is returned.", example: new PaginatedResponse { @@ -77,16 +81,16 @@ public class GetBooksLiteEndpointSummary : Summary { { diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs new file mode 100644 index 00000000..67048e20 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLiteRowFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the book. + /// Optional. The title of the book. + /// Optional. The release year of the book. + /// Optional. The path of the cover image of the book. + /// The created . + public BookLiteRow Create( + Guid? id = null, + string? title = null, + int? releaseYear = null, + string? coverPath = null) + { + return new BookLiteRow + { + Id = id ?? _faker.Random.Guid(), + Title = title ?? _faker.Lorem.Sentence(), + ReleaseYear = releaseYear, + CoverPath = coverPath + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs index c57cfff0..06ca5f2f 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -19,36 +18,32 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.Bo public class GetBooksQueryFixture { private readonly Faker _faker = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); /// /// Creates a random valid query to get books. /// - /// Optional. The Id of the media library whose books are retrieved. + /// Optional. The Id of the media library whose books are retrieved, taken from the route. /// Optional. The pagination data of the query. /// Optional. The search term used to filter results. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. + /// Whether the library Id should be included, or forced to . /// Whether the pagination data should be included, or forced to . /// The created query to get books. public GetBooksQuery Create( - Guid? libraryId = null, + string? libraryId = null, PaginationDataDto? paginationData = null, string? searchTerm = null, string? sortBy = null, SortOrder? sortOrder = null, + bool includeLibraryId = true, bool includePaginationData = true) { return new GetBooksQuery( - includePaginationData ? paginationData ?? new PaginationDataDto - { - CurrentPage = _faker.Random.Number(1, 100), - PerPage = _faker.Random.Number(1, 200) - } : null, - new LibraryFilterDto - { - LibraryId = libraryId ?? _faker.Random.Guid(), - SearchTerm = searchTerm - }, + includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null, + includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null, + searchTerm, sortBy, sortOrder ?? _faker.PickRandom() ); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs index 1f2fce3c..d07ad7b9 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -19,42 +18,38 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.Bo public class GetBooksLiteQueryFixture { private readonly Faker _faker = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); /// /// Creates a random valid query to get the lightweight details of books. /// - /// Optional. The Id of the media library whose books are retrieved. + /// Optional. The Id of the media library whose books are retrieved, taken from the route. /// 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. + /// Whether the library Id should be included, or forced to . /// Whether the pagination data should be included, or forced to . /// The created query to get the lightweight details of books. public GetBooksLiteQuery Create( - Guid? libraryId = null, + string? libraryId = null, PaginationDataDto? paginationData = null, string? searchTerm = null, string? filterAlphaKey = null, bool shouldIgnoreThePrefixForAlphaPicker = false, string? sortBy = null, SortOrder? sortOrder = null, + bool includeLibraryId = true, bool includePaginationData = true) { return new GetBooksLiteQuery( - includePaginationData ? paginationData ?? new PaginationDataDto - { - CurrentPage = _faker.Random.Number(1, 100), - PerPage = _faker.Random.Number(1, 200) - } : null, - new LibraryFilterDto - { - LibraryId = libraryId ?? _faker.Random.Guid(), - SearchTerm = searchTerm, - FilterAlphaKey = filterAlphaKey, - ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker - }, + includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null, + includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null, + searchTerm, + filterAlphaKey, + shouldIgnoreThePrefixForAlphaPicker, 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 d532e90d..c351b00d 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 @@ -2,7 +2,6 @@ using Bogus; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -21,7 +20,6 @@ public class GetBooksLiteRequestFixture /// /// Creates a with default or random values. /// - /// Optional. The Id of the media library whose books are retrieved. /// 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. @@ -33,7 +31,6 @@ public class GetBooksLiteRequestFixture /// Whether the per page count should be included, or forced to . /// The created . public GetBooksLiteRequest Create( - Guid? libraryId = null, int? currentPage = null, int? perPage = null, string? searchTerm = null, @@ -45,7 +42,6 @@ public class GetBooksLiteRequestFixture bool includePerPage = true) { return new GetBooksLiteRequest( - LibraryId: libraryId ?? _faker.Random.Guid(), CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null, SearchTerm: searchTerm ?? _faker.Lorem.Word(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs index db6b9fe0..6ec5c577 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs @@ -2,7 +2,6 @@ using Bogus; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -21,7 +20,6 @@ public class GetBooksRequestFixture /// /// Creates a with default or random values. /// - /// Optional. The Id of the media library whose books are retrieved. /// 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. @@ -31,7 +29,6 @@ public class GetBooksRequestFixture /// Whether the per page count should be included, or forced to . /// The created . public GetBooksRequest Create( - Guid? libraryId = null, int? currentPage = null, int? perPage = null, string? searchTerm = null, @@ -41,7 +38,6 @@ public class GetBooksRequestFixture bool includePerPage = true) { return new GetBooksRequest( - LibraryId: libraryId ?? _faker.Random.Guid(), CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null, SearchTerm: searchTerm ?? _faker.Lorem.Word(), diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index b774a3fc..cfea63fd 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -77,7 +77,7 @@ public class GetBooksEndpointTests : IClassFixture - await _client.GetAsync($"/api/v1/books?libraryId={libraryId}", cts.Token) + await _client.GetAsync($"/api/v1/libraries/{libraryId}/books", cts.Token) ); Assert.Null(exception); } @@ -190,7 +190,7 @@ public class GetBooksEndpointTests : IClassFixture { cts.Cancel(); - await _client.GetAsync($"/api/v1/books?libraryId={libraryId}", cts.Token); + await _client.GetAsync($"/api/v1/libraries/{libraryId}/books", cts.Token); }); Assert.IsType(exception); } @@ -205,7 +205,7 @@ public class GetBooksEndpointTests : IClassFixture? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(new[] { "Book A", "Book B", "Book C" }, paginatedBooks!.Data.Select(book => book.Metadata.Title)); + } + + [Fact] + public async Task GetBooks_WhenSortedByTitleDescending_ShouldReturnBooksInDescendingOrder() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book B"); + await SeedBookAsync(libraryId, "Book C"); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?sortBy=title&sortOrder=Descending"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(new[] { "Book C", "Book B", "Book A" }, paginatedBooks!.Data.Select(book => book.Metadata.Title)); + } + + [Fact] + public async Task GetBooks_WhenCurrentPageIsZero_ShouldReturnFirstPage() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book A"); + await SeedBookAsync(libraryId, "Book B"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?currentPage=0&perPage=1"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(1, paginatedBooks!.CurrentPage); + Assert.Equal(1, paginatedBooks.PerPage); + } + + [Fact] + public async Task GetBooks_WhenPerPageIsZero_ShouldClampItToOne() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book A"); + await SeedBookAsync(libraryId, "Book B"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?currentPage=1&perPage=0"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(1, paginatedBooks!.PerPage); + Assert.Equal(2, paginatedBooks.NumberOfPages); + Assert.Single(paginatedBooks.Data); + } + + [Fact] + public async Task GetBooks_WhenCurrentPageExceedsNumberOfPages_ShouldReturnLastPage() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book A"); + await SeedBookAsync(libraryId, "Book B"); + await SeedBookAsync(libraryId, "Book C"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?currentPage=99&perPage=2"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(2, paginatedBooks!.CurrentPage); + Assert.Equal(2, paginatedBooks.NumberOfPages); + } + + [Fact] + public async Task GetBooks_WhenSortByIsUnknown_ShouldFallBackToTitleOrder() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book B"); + await SeedBookAsync(libraryId, "Book C"); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?sortBy=unknownField&sortOrder=Ascending"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(new[] { "Book A", "Book B", "Book C" }, paginatedBooks!.Data.Select(book => book.Metadata.Title)); + } + + [Fact] + public async Task GetBooks_WhenSearchTermMatchesNoBooks_ShouldReturnEmptyPaginatedResponse() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book A"); + await SeedBookAsync(libraryId, "Book B"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?searchTerm=nonexistent"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Empty(paginatedBooks!.Data); + Assert.Equal(0, paginatedBooks.Count); + } + + [Fact] + public async Task GetBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{libraryId}/books"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + /// /// Seeds a belonging to the media library identified by . /// 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 09d95c44..43c7516e 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 @@ -18,6 +18,7 @@ using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading; using System.Threading.Tasks; #endregion @@ -69,7 +70,7 @@ public class GetBooksLiteEndpointTests : IClassFixture? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(new[] { "Book A", "Book B", "Book C" }, paginatedBooks!.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetBooksLite_WhenSortedByTitleDescending_ShouldReturnBooksInDescendingOrder() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book B"); + await SeedBookAsync(libraryId, "Book C"); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?sortBy=title&sortOrder=Descending"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(new[] { "Book C", "Book B", "Book A" }, paginatedBooks!.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetBooksLite_WhenSortByIsUnknown_ShouldFallBackToTitleOrder() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book B"); + await SeedBookAsync(libraryId, "Book C"); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?sortBy=unknownField&sortOrder=Ascending"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(new[] { "Book A", "Book B", "Book C" }, paginatedBooks!.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetBooksLite_WhenCurrentPageIsZero_ShouldReturnFirstPage() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book A"); + await SeedBookAsync(libraryId, "Book B"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?currentPage=0&perPage=1"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(1, paginatedBooks!.CurrentPage); + Assert.Equal(1, paginatedBooks.PerPage); + } + + [Fact] + public async Task GetBooksLite_WhenPerPageIsZero_ShouldClampItToOne() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book A"); + await SeedBookAsync(libraryId, "Book B"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?currentPage=1&perPage=0"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(1, paginatedBooks!.PerPage); + Assert.Equal(2, paginatedBooks.NumberOfPages); + Assert.Single(paginatedBooks.Data); + } + + [Fact] + public async Task GetBooksLite_WhenCurrentPageExceedsNumberOfPages_ShouldReturnLastPage() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book A"); + await SeedBookAsync(libraryId, "Book B"); + await SeedBookAsync(libraryId, "Book C"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?currentPage=99&perPage=2"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(2, paginatedBooks!.CurrentPage); + Assert.Equal(2, paginatedBooks.NumberOfPages); + } + + [Fact] + public async Task GetBooksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{libraryId}/books/lite"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task GetBooksLite_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act & Assert + Exception? exception = await Record.ExceptionAsync(async () => + await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite", cts.Token) + ); + Assert.Null(exception); + } + + [Fact] + public async Task GetBooksLite_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + using CancellationTokenSource cts = new(); + + // Act & Assert + Exception? exception = await Record.ExceptionAsync(async () => + { + cts.Cancel(); + await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite", cts.Token); + }); + Assert.IsType(exception); + } + /// /// Seeds a belonging to the media library identified by . /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 6e3132d7..f19f866d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -40,7 +40,7 @@ public class GetBooksEndpointTests : IClassFixture, IDisposabl public async Task GetBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Act - HttpResponseMessage response = await _client.GetAsync("/api/v1/books"); + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -52,7 +52,7 @@ public class GetBooksEndpointTests : IClassFixture, IDisposabl Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal("/api/v1/books", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books", problemDetails["instance"].GetProperty("value").GetString()); Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); } @@ -69,7 +69,7 @@ public class GetBooksEndpointTests : IClassFixture, IDisposabl await _apiFactory.SeedBookAsync(libraryId, "Book A"); // Act - HttpResponseMessage response = await client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); // Assert response.EnsureSuccessStatusCode(); @@ -84,6 +84,62 @@ public class GetBooksEndpointTests : IClassFixture, IDisposabl await _apiFactory.RemoveTestUserAsync(username); } + [Fact] + public async Task GetBooks_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetBooks_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books"); + + // Assert + // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the query + // validator, which reports it as a clean validation error. The response must not leak stack traces, database details, + // or the injected payload. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + await _apiFactory.RemoveTestUserAsync(username); + } + /// /// Disposes API factory resources. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index bf387226..0a97a383 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -41,7 +41,7 @@ public class GetBooksLiteEndpointTests : IClassFixture, IDispo public async Task GetBooksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Act - HttpResponseMessage response = await _client.GetAsync("/api/v1/books/lite"); + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -53,7 +53,7 @@ public class GetBooksLiteEndpointTests : IClassFixture, IDispo Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal("/api/v1/books/lite", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite", problemDetails["instance"].GetProperty("value").GetString()); Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); } @@ -70,7 +70,7 @@ public class GetBooksLiteEndpointTests : IClassFixture, IDispo await _apiFactory.SeedBookAsync(libraryId, "Book A"); // Act - HttpResponseMessage response = await client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); // Assert response.EnsureSuccessStatusCode(); @@ -85,6 +85,62 @@ public class GetBooksLiteEndpointTests : IClassFixture, IDispo await _apiFactory.RemoveTestUserAsync(username); } + [Fact] + public async Task GetBooksLite_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetBooksLite_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/lite"); + + // Assert + // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the query + // validator, which reports it as a clean validation error. The response must not leak stack traces, database details, + // or the injected payload. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + await _apiFactory.RemoveTestUserAsync(username); + } + /// /// Disposes API factory resources. /// diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs index 9847245b..4a75b578 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs @@ -365,73 +365,4 @@ public class BookEntityMappingTests Assert.Equal(paginatedBookEntities.Count, result.Count); Assert.Equal(paginatedBookEntities.NumberOfPages, result.NumberOfPages); } - - [Fact] - public void ToLiteResponse_WhenMappingBookEntity_ShouldMapIdTitleAndReleaseYear() - { - // Arrange - BookEntity bookEntity = _bookEntityFixture.Create(); - - // Act - BookLiteResponse result = bookEntity.ToLiteResponse(); - - // Assert - Assert.NotNull(result); - Assert.Equal(bookEntity.Id, result.Id); - Assert.Equal(bookEntity.Title, result.Title); - Assert.Equal(bookEntity.ReReleaseYear ?? bookEntity.OriginalReleaseYear, result.ReleaseYear); - Assert.Null(result.CoverPath); - } - - [Fact] - public void ToLiteResponse_WhenBookHasNoReReleaseYear_ShouldFallBackToOriginalReleaseYear() - { - // Arrange - BookEntity bookEntity = _bookEntityFixture.Create(); - bookEntity.ReReleaseYear = null; - - // Act - BookLiteResponse result = bookEntity.ToLiteResponse(); - - // Assert - Assert.Equal(bookEntity.OriginalReleaseYear, result.ReleaseYear); - } - - [Fact] - public void ToLiteResponses_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly() - { - // Arrange - List bookEntities = _bookEntityFixture.CreateMany(2); - - // Act - IReadOnlyList results = bookEntities.ToLiteResponses(); - - // Assert - Assert.NotNull(results); - Assert.Equal(bookEntities.Count, results.Count); - } - - [Fact] - public void ToLiteResponses_WhenMappingPaginatedBookEntities_ShouldMapAllPropertiesCorrectly() - { - // Arrange - List bookEntities = _bookEntityFixture.CreateMany(2); - PaginatedResultDto paginatedBookEntities = _paginatedResultDtoFixture.Create( - data: bookEntities, - currentPage: 1, - perPage: 10, - count: 2, - numberOfPages: 1); - - // Act - PaginatedResponse result = paginatedBookEntities.ToLiteResponses(); - - // Assert - Assert.NotNull(result); - Assert.Equal(paginatedBookEntities.Data.Count, result.Data.Count); - Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage); - Assert.Equal(paginatedBookEntities.PerPage, result.PerPage); - Assert.Equal(paginatedBookEntities.Count, result.Count); - Assert.Equal(paginatedBookEntities.NumberOfPages, result.NumberOfPages); - } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMappingTests.cs new file mode 100644 index 00000000..d061f80f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMappingTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLiteRowMappingTests +{ + private readonly BookLiteRowFixture _bookLiteRowFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + [Fact] + public void ToResponse_WhenMappingBookLiteRow_ShouldMapAllPropertiesCorrectly() + { + // Arrange + BookLiteRow readModel = _bookLiteRowFixture.Create(); + + // Act + BookLiteResponse result = readModel.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(readModel.Id, result.Id); + Assert.Equal(readModel.Title, result.Title); + Assert.Equal(readModel.ReleaseYear, result.ReleaseYear); + Assert.Equal(readModel.CoverPath, result.CoverPath); + } + + [Fact] + public void ToResponses_WhenMappingMultipleBookLiteRows_ShouldMapAllCorrectly() + { + // Arrange + List readModels = _bookLiteRowFixture.CreateMany(2); + + // Act + IReadOnlyList results = readModels.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(readModels.Count, results.Count); + Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id)); + } + + [Fact] + public void ToResponses_WhenMappingPaginatedBookLiteRows_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List readModels = _bookLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedReadModels = _paginatedResultDtoFixture.Create( + data: readModels, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + + // Act + PaginatedResponse result = paginatedReadModels.ToResponses(); + + // Assert + Assert.NotNull(result); + Assert.Equal(paginatedReadModels.Data.Count, result.Data.Count); + Assert.Equal(paginatedReadModels.CurrentPage, result.CurrentPage); + Assert.Equal(paginatedReadModels.PerPage, result.PerPage); + Assert.Equal(paginatedReadModels.Count, result.Count); + Assert.Equal(paginatedReadModels.NumberOfPages, result.NumberOfPages); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs index 9a603ef4..0f1f5b1e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,14 +22,17 @@ public class GetBooksLiteRequestMappingTests { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksLiteQuery result = request.ToQuery(); + GetBooksLiteQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.Filter.LibraryId); - Assert.Equal(request.SearchTerm, result.Filter.SearchTerm); + Assert.Equal(libraryId, result.LibraryId); + Assert.Equal(request.SearchTerm, result.SearchTerm); + Assert.Equal(request.FilterAlphaKey, result.FilterAlphaKey); + Assert.Equal(request.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); Assert.Equal(request.SortBy, result.SortBy); Assert.Equal(request.SortOrder, result.SortOrder); Assert.NotNull(result.PaginationData); @@ -36,19 +40,49 @@ public class GetBooksLiteRequestMappingTests Assert.Equal(request.PerPage, result.PaginationData.PerPage); } + [Fact] + public void ToQuery_WhenLibraryIdIsNotParseable_ShouldMapItAsIs() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + string libraryId = "not-a-library-guid"; + + // Act + GetBooksLiteQuery result = request.ToQuery(libraryId); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId, result.LibraryId); + } + + [Fact] + public void ToQuery_WhenLibraryIdIsNull_ShouldMapNullLibraryId() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + + // Act + GetBooksLiteQuery result = request.ToQuery(null); + + // Assert + Assert.NotNull(result); + Assert.Null(result.LibraryId); + } + [Fact] public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData() { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksLiteQuery result = request.ToQuery(); + GetBooksLiteQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result); Assert.Null(result.PaginationData); - Assert.Equal(request.LibraryId, result.Filter.LibraryId); + Assert.Equal(libraryId, result.LibraryId); } [Fact] @@ -56,9 +90,10 @@ public class GetBooksLiteRequestMappingTests { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(perPage: 25, includeCurrentPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksLiteQuery result = request.ToQuery(); + GetBooksLiteQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result.PaginationData); @@ -71,9 +106,10 @@ public class GetBooksLiteRequestMappingTests { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(currentPage: 3, includePerPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksLiteQuery result = request.ToQuery(); + GetBooksLiteQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result.PaginationData); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs index fffc881b..01134ff2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,14 +22,15 @@ public class GetBooksRequestMappingTests { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksQuery result = request.ToQuery(); + GetBooksQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.Filter.LibraryId); - Assert.Equal(request.SearchTerm, result.Filter.SearchTerm); + Assert.Equal(libraryId, result.LibraryId); + Assert.Equal(request.SearchTerm, result.SearchTerm); Assert.Equal(request.SortBy, result.SortBy); Assert.Equal(request.SortOrder, result.SortOrder); Assert.NotNull(result.PaginationData); @@ -36,19 +38,49 @@ public class GetBooksRequestMappingTests Assert.Equal(request.PerPage, result.PaginationData.PerPage); } + [Fact] + public void ToQuery_WhenLibraryIdIsNotParseable_ShouldMapItAsIs() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + string libraryId = "not-a-library-guid"; + + // Act + GetBooksQuery result = request.ToQuery(libraryId); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId, result.LibraryId); + } + + [Fact] + public void ToQuery_WhenLibraryIdIsNull_ShouldMapNullLibraryId() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + + // Act + GetBooksQuery result = request.ToQuery(null); + + // Assert + Assert.NotNull(result); + Assert.Null(result.LibraryId); + } + [Fact] public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData() { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksQuery result = request.ToQuery(); + GetBooksQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result); Assert.Null(result.PaginationData); - Assert.Equal(request.LibraryId, result.Filter.LibraryId); + Assert.Equal(libraryId, result.LibraryId); } [Fact] @@ -56,9 +88,10 @@ public class GetBooksRequestMappingTests { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(perPage: 25, includeCurrentPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksQuery result = request.ToQuery(); + GetBooksQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result.PaginationData); @@ -71,9 +104,10 @@ public class GetBooksRequestMappingTests { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(currentPage: 3, includePerPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksQuery result = request.ToQuery(); + GetBooksQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result.PaginationData); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs index b2c32756..463e367f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs @@ -52,6 +52,7 @@ public class GetBooksQueryHandlerTests { _mockBookRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -75,12 +76,13 @@ public class GetBooksQueryHandlerTests CancellationToken cancellationToken = CancellationToken.None; List bookEntities = _bookEntityFixture.CreateMany(2); PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: bookEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act @@ -101,12 +103,13 @@ public class GetBooksQueryHandlerTests // Arrange GetBooksQuery query = _getBooksQueryFixture.Create(); PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act @@ -122,12 +125,13 @@ public class GetBooksQueryHandlerTests { // Arrange GetBooksQuery query = _getBooksQueryFixture.Create(); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Errors.Library.FilterMustIncludeLibraryId); // Act @@ -145,51 +149,55 @@ public class GetBooksQueryHandlerTests GetBooksQuery query = _getBooksQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act await _sut.HandleAsync(query, cancellationToken); // Assert - await _mockBookRepository.Received(1).GetPaginatedAsync( + await _mockBookRepository.Received(1).GetAllAsync( Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), Arg.Is(query.SortBy), Arg.Is(query.SortOrder), - Arg.Is(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm), - Arg.Is(cancellationToken)); + Arg.Is(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && filter.SearchTerm == query.SearchTerm), + shouldTrackEntities: false, + cancellationToken: Arg.Is(cancellationToken)); } [Fact] public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() { // Arrange - GetBooksQuery query = _getBooksQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid(), sortOrder: SortOrder.Ascending); + GetBooksQuery query = _getBooksQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid().ToString(), sortOrder: SortOrder.Ascending); PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act await _sut.HandleAsync(query, CancellationToken.None); // Assert - await _mockBookRepository.Received(1).GetPaginatedAsync( + await _mockBookRepository.Received(1).GetAllAsync( Arg.Is(paginationData => paginationData == null), Arg.Is(query.SortBy), Arg.Is(query.SortOrder), - Arg.Is(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm), - Arg.Any()); + Arg.Is(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && filter.SearchTerm == query.SearchTerm), + shouldTrackEntities: false, + cancellationToken: Arg.Any()); } [Fact] @@ -207,8 +215,8 @@ public class GetBooksQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == query.Filter.LibraryId), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + _userId, Arg.Is(context => context.LibraryId == Guid.Parse(query.LibraryId!)), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); } [Fact] @@ -225,7 +233,7 @@ public class GetBooksQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); } [Fact] @@ -242,6 +250,6 @@ public class GetBooksQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs index 05f8e41e..8988d929 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs @@ -24,7 +24,59 @@ public class GetBooksQueryValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: Guid.Empty); + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsGuidEmpty_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAValidGuid_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: "not-a-library-guid"); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs index 645a651f..a495b3e3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; using Lumina.Contracts.Responses.Common; @@ -41,9 +41,9 @@ public class GetBooksLiteQueryHandlerTests private readonly IValidator _mockValidator; private readonly GetBooksLiteQueryHandler _sut; private readonly Guid _userId; - private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookLiteRowFixture _bookLiteRowFixture = new(); private readonly GetBooksLiteQueryFixture _getBooksLiteQueryFixture = new(); - private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -52,6 +52,7 @@ public class GetBooksLiteQueryHandlerTests { _mockBookRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -73,14 +74,14 @@ public class GetBooksLiteQueryHandlerTests // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - List bookEntities = _bookEntityFixture.CreateMany(2); - PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: bookEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); - _mockBookRepository.GetPaginatedAsync( + List bookLiteRows = _bookLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: bookLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act @@ -88,7 +89,7 @@ public class GetBooksLiteQueryHandlerTests // Assert Assert.False(result.IsFailure); - Assert.Equal(bookEntities.Count, result.Value.Data.Count); + Assert.Equal(bookLiteRows.Count, result.Value.Data.Count); Assert.Equal(paginatedBooks.CurrentPage, result.Value.CurrentPage); Assert.Equal(paginatedBooks.PerPage, result.Value.PerPage); Assert.Equal(paginatedBooks.Count, result.Value.Count); @@ -100,13 +101,13 @@ public class GetBooksLiteQueryHandlerTests { // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act @@ -122,12 +123,12 @@ public class GetBooksLiteQueryHandlerTests { // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Errors.Library.FilterMustIncludeLibraryId); // Act @@ -144,52 +145,58 @@ public class GetBooksLiteQueryHandlerTests // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act await _sut.HandleAsync(query, cancellationToken); // Assert - await _mockBookRepository.Received(1).GetPaginatedAsync( + await _mockBookRepository.Received(1).GetAllLiteAsync( Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), Arg.Is(query.SortBy), Arg.Is(query.SortOrder), - Arg.Is(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm), - Arg.Is(cancellationToken)); + Arg.Is(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && + filter.SearchTerm == query.SearchTerm && + filter.FilterAlphaKey == query.FilterAlphaKey && + filter.ShouldIgnoreThePrefixForAlphaPicker == query.ShouldIgnoreThePrefixForAlphaPicker), + cancellationToken: Arg.Is(cancellationToken)); } [Fact] public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() { // Arrange - GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid(), sortOrder: SortOrder.Ascending); - PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid().ToString(), sortOrder: SortOrder.Ascending); + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act await _sut.HandleAsync(query, CancellationToken.None); // Assert - await _mockBookRepository.Received(1).GetPaginatedAsync( + await _mockBookRepository.Received(1).GetAllLiteAsync( Arg.Is(paginationData => paginationData == null), Arg.Is(query.SortBy), Arg.Is(query.SortOrder), - Arg.Is(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm), - Arg.Any()); + Arg.Is(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && + filter.SearchTerm == query.SearchTerm && + filter.FilterAlphaKey == query.FilterAlphaKey && + filter.ShouldIgnoreThePrefixForAlphaPicker == query.ShouldIgnoreThePrefixForAlphaPicker), + cancellationToken: Arg.Any()); } [Fact] @@ -207,8 +214,8 @@ public class GetBooksLiteQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == query.Filter.LibraryId), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + _userId, Arg.Is(context => context.LibraryId == Guid.Parse(query.LibraryId!)), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -225,7 +232,7 @@ public class GetBooksLiteQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -242,6 +249,6 @@ public class GetBooksLiteQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs index 3d9e59d8..7e739bab 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs @@ -24,7 +24,59 @@ public class GetBooksLiteQueryValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: Guid.Empty); + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsGuidEmpty_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAValidGuid_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: "not-a-library-guid"); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs index ad60760c..a59c89dc 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs @@ -32,7 +32,6 @@ public class GetBooksLiteRequestTests // Assert Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); Assert.True(sut.CurrentPage.HasValue); Assert.True(sut.PerPage.HasValue); } @@ -72,10 +71,9 @@ public class GetBooksLiteRequestTests GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create(); // Act - (Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker, string? sortBy, SortOrder? sortOrder) = sut; + (int? currentPage, int? perPage, string? searchTerm, string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker, string? sortBy, SortOrder? sortOrder) = sut; // Assert - Assert.Equal(sut.LibraryId, libraryId); Assert.Equal(sut.CurrentPage, currentPage); Assert.Equal(sut.PerPage, perPage); Assert.Equal(sut.SearchTerm, searchTerm); @@ -84,4 +82,18 @@ public class GetBooksLiteRequestTests Assert.Equal(sut.SortBy, sortBy); Assert.Equal(sut.SortOrder, sortOrder); } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + GetBooksLiteRequest first = _getBooksLiteRequestFixture.Create(); + GetBooksLiteRequest second = first with { }; + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs index 1b573070..c6be33af 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs @@ -32,7 +32,6 @@ public class GetBooksRequestTests // Assert Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); Assert.True(sut.CurrentPage.HasValue); Assert.True(sut.PerPage.HasValue); } @@ -72,14 +71,27 @@ public class GetBooksRequestTests GetBooksRequest sut = _getBooksRequestFixture.Create(); // Act - (Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? sortBy, SortOrder? sortOrder) = sut; + (int? currentPage, int? perPage, string? searchTerm, string? sortBy, SortOrder? sortOrder) = sut; // Assert - Assert.Equal(sut.LibraryId, libraryId); Assert.Equal(sut.CurrentPage, currentPage); Assert.Equal(sut.PerPage, perPage); Assert.Equal(sut.SearchTerm, searchTerm); Assert.Equal(sut.SortBy, sortBy); Assert.Equal(sut.SortOrder, sortOrder); } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + GetBooksRequest first = _getBooksRequestFixture.Create(); + GetBooksRequest second = first with { }; + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index 0a159f5e..23b3f9e7 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; @@ -1086,4 +1087,273 @@ public class BookRepositoryTests Assert.Equal(["The Art of War", "Beneath the Surface"], result.Value.Data.Select(book => book.Title)); } + [Fact] + public async Task GetAllLiteAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedLiteRows() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List books = _bookEntityFixture.CreateMany(3); + foreach (BookEntity book in books) + book.LibraryId = libraryId; + _mockContext.Books.AddRange(books); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(3, result.Value.Count); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal(1, result.Value.CurrentPage); + Assert.Equal(10, result.Value.PerPage); + Assert.Equal(1, result.Value.NumberOfPages); + } + + [Fact] + public async Task GetAllLiteAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError() + { + // Arrange + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + BaseFilterDto filter = _baseFilterDtoFixture.Create(); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllLiteAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError() + { + // Arrange + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllLiteAsync_WhenPaginationDataIsNull_ShouldReturnAllLiteRows() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List books = _bookEntityFixture.CreateMany(3); + foreach (BookEntity book in books) + book.LibraryId = libraryId; + _mockContext.Books.AddRange(books); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(3, result.Value.Count); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal(1, result.Value.CurrentPage); + Assert.Equal(3, result.Value.PerPage); + Assert.Equal(1, result.Value.NumberOfPages); + } + + [Fact] + public async Task GetAllLiteAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingLiteRows() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity fellowshipBook = _bookEntityFixture.Create(); + fellowshipBook.LibraryId = libraryId; + fellowshipBook.Title = "The Fellowship of the Ring"; + BookEntity towersBook = _bookEntityFixture.Create(); + towersBook.LibraryId = libraryId; + towersBook.Title = "The Two Towers"; + _mockContext.Books.AddRange(fellowshipBook, towersBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship"); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal("The Fellowship of the Ring", row.Title); + Assert.Equal(1, result.Value.Count); + } + + [Fact] + public async Task GetAllLiteAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List books = _bookEntityFixture.CreateMany(5); + foreach (BookEntity book in books) + book.LibraryId = libraryId; + _mockContext.Books.AddRange(books); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 2, perPage: 2); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(5, result.Value.Count); + Assert.Equal(3, result.Value.NumberOfPages); + Assert.Equal(2, result.Value.CurrentPage); + Assert.Equal(2, result.Value.PerPage); + Assert.Equal(2, result.Value.Data.Count); + } + + [Fact] + public async Task GetAllLiteAsync_WhenSortByTitleDescending_ShouldReturnLiteRowsInDescendingOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity bookA = _bookEntityFixture.Create(); + bookA.LibraryId = libraryId; + bookA.Title = "Book A"; + BookEntity bookB = _bookEntityFixture.Create(); + bookB.LibraryId = libraryId; + bookB.Title = "Book B"; + _mockContext.Books.AddRange(bookA, bookB); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, "title", SortOrder.Descending, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["Book B", "Book A"], result.Value.Data.Select(row => row.Title)); + } + + [Fact] + public async Task GetAllLiteAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity beneathBook = _bookEntityFixture.Create(title: "Beneath the Surface", includeMetadata: false); + beneathBook.LibraryId = libraryId; + BookEntity artOfWarBook = _bookEntityFixture.Create(title: "The Art of War", includeMetadata: false); + artOfWarBook.LibraryId = libraryId; + _mockContext.Books.AddRange(beneathBook, artOfWarBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + // Without stripping the prefix, "The Art of War" would be sorted after "Beneath the Surface", since its sort key would start with "the" instead of "art". + Assert.Equal(["The Art of War", "Beneath the Surface"], result.Value.Data.Select(row => row.Title)); + } + + [Fact] + public async Task GetAllLiteAsync_WhenBookHasReReleaseYear_ShouldProjectReReleaseYearAsReleaseYear() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(book.ReReleaseYear, row.ReleaseYear); + } + + [Fact] + public async Task GetAllLiteAsync_WhenBookHasNoReReleaseYear_ShouldProjectOriginalReleaseYearAsReleaseYear() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.ReReleaseYear = null; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(book.OriginalReleaseYear, row.ReleaseYear); + } + + [Fact] + public async Task GetAllLiteAsync_WhenBookHasCoverArtwork_ShouldProjectTheCoverFileName() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")]; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal("cover.jpg", row.CoverPath); + } + + [Fact] + public async Task GetAllLiteAsync_WhenBookHasNoCoverArtwork_ShouldProjectNullCoverPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.BookArtwork = []; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Null(row.CoverPath); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 3d3dc530..3a5c902b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; @@ -63,12 +64,12 @@ public class GetBooksEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found."); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); @@ -77,19 +78,18 @@ public class GetBooksEndpointTests // Assert ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("Book.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The requested book was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(); @@ -118,18 +118,20 @@ public class GetBooksEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksQueryToSender() { // Arrange + Guid libraryId = Guid.NewGuid(); GetBooksRequest request = _getBooksRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync(Arg.Is(query => - query.Filter.LibraryId == request.LibraryId && - query.Filter.SearchTerm == request.SearchTerm && + query.LibraryId == libraryId.ToString() && + query.SearchTerm == request.SearchTerm && query.SortBy == request.SortBy && query.SortOrder == request.SortOrder && query.PaginationData != null && @@ -138,6 +140,44 @@ public class GetBooksEndpointTests Arg.Is(cancellationToken)); } + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null), + Arg.Is(cancellationToken)); + } + [Fact] public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index 77e5847c..a6e5cd32 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; @@ -63,12 +64,12 @@ public class GetBooksLiteEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found."); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); @@ -77,19 +78,18 @@ public class GetBooksLiteEndpointTests // Assert ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("Book.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The requested book was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); @@ -118,18 +118,22 @@ public class GetBooksLiteEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksLiteQueryToSender() { // Arrange + Guid libraryId = Guid.NewGuid(); GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync(Arg.Is(query => - query.Filter.LibraryId == request.LibraryId && - query.Filter.SearchTerm == request.SearchTerm && + query.LibraryId == libraryId.ToString() && + query.SearchTerm == request.SearchTerm && + query.FilterAlphaKey == request.FilterAlphaKey && + query.ShouldIgnoreThePrefixForAlphaPicker == request.ShouldIgnoreThePrefixForAlphaPicker && query.SortBy == request.SortBy && query.SortOrder == request.SortOrder && query.PaginationData != null && @@ -138,6 +142,44 @@ public class GetBooksLiteEndpointTests Arg.Is(cancellationToken)); } + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null), + Arg.Is(cancellationToken)); + } + [Fact] public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() {