diff --git a/src/Lumina.Application/Common/DTO/Filtering/BaseFilterDto.cs b/src/Lumina.Application/Common/DTO/Filtering/BaseFilterDto.cs new file mode 100644 index 00000000..84a7bb4b --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Filtering/BaseFilterDto.cs @@ -0,0 +1,12 @@ +namespace Lumina.Application.Common.DTO.Filtering; + +/// +/// Data transfer object that defines common filter properties used when querying paginated data. Implementations may add additional properties specific to their module or domain. +/// +public record BaseFilterDto +{ + /// + /// The search term used to filter results. + /// + public string? SearchTerm { get; init; } +} diff --git a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs new file mode 100644 index 00000000..d594dcc4 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.Filtering; + +/// +/// Data transfer object that represents the parameters required to filter by library data. +/// +public record LibraryFilterDto : BaseFilterDto +{ + /// + /// The Id of the media library used to filter data. + /// + public required Guid LibraryId { get; init; } +} diff --git a/src/Lumina.Application/Common/DTO/Pagination/PaginatedResultDto.cs b/src/Lumina.Application/Common/DTO/Pagination/PaginatedResultDto.cs new file mode 100644 index 00000000..e516aa2f --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Pagination/PaginatedResultDto.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.DTO.Pagination; + +/// +/// Represents a paginated result containing a subset of data and pagination metadata for the current page. +/// +/// The type of the data items contained in the paginated result. +public sealed record PaginatedResultDto +{ + /// + /// Gets the collection of data items associated with this instance. + /// + public required IReadOnlyList Data { get; init; } + + /// + /// Gets the current page number in a paginated collection. + /// + public required int CurrentPage { get; init; } + + /// + /// Gets or sets the number of items to include per page in paginated results. + /// + public required int PerPage { get; init; } + + /// + /// Gets the total number of elements available in the paginated result set. + /// + public required int Count { get; init; } + + /// + /// Gets the total number of pages based on elements available in the result set and per page. + /// + public required int NumberOfPages { get; init; } +} diff --git a/src/Lumina.Application/Common/DTO/Pagination/PaginationDataDto.cs b/src/Lumina.Application/Common/DTO/Pagination/PaginationDataDto.cs new file mode 100644 index 00000000..7c422d01 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Pagination/PaginationDataDto.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.Pagination; + +/// +/// Data transfer object for pagination metadata. +/// +public sealed record PaginationDataDto +{ + private int perPage = 200; + private int currentPage = 1; + + /// + /// Gets the current page number in a paginated collection. + /// + public int CurrentPage + { + get { return currentPage; } + set + { + currentPage = Math.Max(value, 1); + } + } + + /// + /// Gets or sets the number of items to include per page in paginated results. + /// + public int PerPage + { + get { return perPage; } + set + { + perPage = Math.Max(value, 1); + } + } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs index 893e7f40..9265254b 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs @@ -18,7 +18,8 @@ public interface IBookRepository : IRepository, IInsertRepositoryAction, IUpdateRepositoryAction, IGetByIdRepositoryAction, - IGetAllRepositoryAction + IGetAllRepositoryAction, + IGetPaginatedRepositoryAction { /// /// Gets all the books of the media library identified by . diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetPaginatedRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetPaginatedRepositoryAction.cs new file mode 100644 index 00000000..21ca90ce --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetPaginatedRepositoryAction.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Domain.Common.Primitives; +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 paginated" action for interacting with a generic persistence medium. +/// +/// The type used as a result for the "get paginated" action. It should implement . +public interface IGetPaginatedRepositoryAction where TModel : IStorageEntity +{ + /// + /// Gets paginated data of type from the storage medium. + /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes current page and 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 parameters used to filter results. + /// Cancellation token that can be used to stop the execution. + /// An containing either a paginated result of type , or an error. + Task>> GetPaginatedAsync(PaginationDataDto? paginationData, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, 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 1561d2cb..5fa6a3a7 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 @@ -1,19 +1,20 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; - +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Linq; @@ -225,8 +226,68 @@ public static class BookEntityMapping /// /// The repository entities to be converted. /// The converted reponses. - public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + public static IReadOnlyList ToResponses(this IEnumerable repositoryEntities) { - return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse()); + return [.. repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse())]; + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated repository entities to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto repositoryEntities) + { + return new PaginatedResponse + { + Data = repositoryEntities.Data.ToResponses(), + CurrentPage = repositoryEntities.CurrentPage, + PerPage = repositoryEntities.PerPage, + Count = repositoryEntities.Count, + 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, + // TODO: populate from the book cover when cover support is implemented + null + ); + } + + /// + /// 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/GetBooksLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs new file mode 100644 index 00000000..3e7a2c3e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class GetBooksLiteRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetBooksLiteQuery ToQuery(this GetBooksLiteRequest request) + { + 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 + }; + + return new GetBooksLiteQuery(paginationData, libraryFilter, 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 0bde6e3f..a3b3255a 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,4 +1,6 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; #endregion @@ -17,6 +19,20 @@ public static class GetBooksRequestMapping /// The converted query. public static GetBooksQuery ToQuery(this GetBooksRequest request) { - return new GetBooksQuery(request.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 + }; + + return new GetBooksQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder); } } diff --git a/src/Lumina.Application/Common/Specifications/AndFilterSpecification.cs b/src/Lumina.Application/Common/Specifications/AndFilterSpecification.cs new file mode 100644 index 00000000..9a9111d5 --- /dev/null +++ b/src/Lumina.Application/Common/Specifications/AndFilterSpecification.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.Common.Specifications; + +/// +/// Represents a filter specification that combines two filter specifications using a logical AND operation. +/// +/// The type of entity to which the filter specification is applied. +internal class AndFilterSpecification : FilterSpecification +{ + private readonly FilterSpecification _left; + private readonly FilterSpecification _right; + + /// + /// Overload C-tor. + /// + /// The first filter specification to combine. + /// The second filter specification to combine. + public AndFilterSpecification(FilterSpecification left, FilterSpecification right) + { + _left = left; + _right = right; + } + + /// + /// Creates a LINQ expression that represents the predicate defined by the current specification. + /// + /// An expression tree that can be used to evaluate whether an object of type satisfies the specification criteria. + public override Expression> ToExpression() + { + Expression> leftExpression = _left.ToExpression(); + Expression> rightExpression = _right.ToExpression(); + + ParameterExpression parameter = Expression.Parameter(typeof(T)); + BinaryExpression combined = Expression.AndAlso( + Expression.Invoke(leftExpression, parameter), + Expression.Invoke(rightExpression, parameter) + ); + + return Expression.Lambda>(combined, parameter); + } +} diff --git a/src/Lumina.Application/Common/Specifications/FilterSpecification.cs b/src/Lumina.Application/Common/Specifications/FilterSpecification.cs new file mode 100644 index 00000000..e1ea8f22 --- /dev/null +++ b/src/Lumina.Application/Common/Specifications/FilterSpecification.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.Common.Specifications; + +/// +/// Represents the abstract base for a filtering specification, enabling the encapsulation of business query logic as reusable objects. +/// +/// The type of entity to which the specification applies. +public abstract class FilterSpecification +{ + /// + /// Creates a LINQ expression that represents the predicate defined by the current specification. + /// + /// An expression tree that can be used to evaluate whether an object of type satisfies the specification criteria. + public abstract Expression> ToExpression(); + + /// + /// Determines whether the specified entity satisfies the criteria defined by the specification. + /// + /// The entity to evaluate against the specification criteria. + /// if the entity satisfies the specification; otherwise. + public bool IsSatisfiedBy(T entity) + { + Func predicate = ToExpression().Compile(); + return predicate(entity); + } + + /// + /// Combines the current filter specification with another specification using a logical AND operation. + /// + /// The filter specification to combine with the current specification. + /// A new filter specification that is satisfied if both the current specification and the specified specification is satisfied. + public FilterSpecification And(FilterSpecification specification) + { + return new AndFilterSpecification(this, specification); + } + + /// + /// Combines the current filter specification with another specification using a logical OR operation. + /// + /// The filter specification to combine with the current specification. + /// A new filter specification that is satisfied if either the current specification or the specified specification is satisfied. + public FilterSpecification Or(FilterSpecification specification) + { + return new OrFilterSpecification(this, specification); + } +} diff --git a/src/Lumina.Application/Common/Specifications/OrFilterSpecification.cs b/src/Lumina.Application/Common/Specifications/OrFilterSpecification.cs new file mode 100644 index 00000000..6aa04fd4 --- /dev/null +++ b/src/Lumina.Application/Common/Specifications/OrFilterSpecification.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.Common.Specifications; + +/// +/// Represents a filter specification that combines two filter specifications using a logical OR operation. +/// +/// The type of entity to which the filter specification is applied. +internal class OrFilterSpecification : FilterSpecification +{ + private readonly FilterSpecification _left; + private readonly FilterSpecification _right; + + /// + /// Overload C-tor. + /// + /// The first filter specification to combine. + /// The second filter specification to combine. + public OrFilterSpecification(FilterSpecification left, FilterSpecification right) + { + _left = left; + _right = right; + } + + /// + /// Creates a LINQ expression that represents the predicate defined by the current specification. + /// + /// An expression tree that can be used to evaluate whether an object of type satisfies the specification criteria. + public override Expression> ToExpression() + { + Expression> leftExpression = _left.ToExpression(); + Expression> rightExpression = _right.ToExpression(); + + ParameterExpression parameter = Expression.Parameter(typeof(T)); + BinaryExpression combined = Expression.OrElse( + Expression.Invoke(leftExpression, parameter), + Expression.Invoke(rightExpression, parameter) + ); + + return Expression.Lambda>(combined, parameter); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs index 6147d3de..5aef1242 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Domain.SharedKernel.Common.Enums.Common; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; @@ -8,7 +10,13 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar /// /// Query for getting all the books of a media library. /// -/// The Id of the media library whose books are retrieved. +/// The object containing the requested pagination data. +/// The object containing the criteria used to filter the results. +/// The name of the field by which to sort the results. +/// The direction in which to sort the results. public record GetBooksQuery( - Guid LibraryId + PaginationDataDto? PaginationData, + LibraryFilterDto Filter, + string? SortBy, + SortOrder? SortOrder ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 5cc1b35e..b2664baf 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -9,6 +9,13 @@ using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Lumina.Contracts.Responses.Common; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DTO.Pagination; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; @@ -16,17 +23,26 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar /// /// Handler for the query to get all books. /// -public class GetBooksQueryHandler : IQueryHandler>> +public class GetBooksQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - public GetBooksQueryHandler(IUnitOfWork unitOfWork) + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetBooksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; } /// @@ -37,10 +53,28 @@ public class GetBooksQueryHandler : IQueryHandler /// An containing either a collection of , or an error message. /// - public async Task>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken) + public async Task>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // check if the user has the rights to access the library they are requesting (admins can see all libraries) + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) // if its not an admin, then it must own the library + { + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Filter.LibraryId, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value?.UserId != _currentUserService.UserId) + return Errors.Authorization.NotAuthorized; + } + // get all books of the media library from the book repository - Result> getBooksResult = await _unitOfWork.BookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); - return getBooksResult.Match(result => Result.From(getBooksResult.Value.ToResponses()), errors => errors); + Result> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync( + query.PaginationData, + query.SortBy, + query.SortOrder, + query.Filter, + cancellationToken).ConfigureAwait(false); + return getBooksResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs new file mode 100644 index 00000000..576e755d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; + +/// +/// Validates the needed validation rules for . +/// +public class GetBooksQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetBooksQueryValidator() + { + RuleFor(query => query.Filter.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs new file mode 100644 index 00000000..0aec829f --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs @@ -0,0 +1,22 @@ +#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 + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; + +/// +/// Query for getting the lightweight details of all the books of a media library. +/// +/// The object containing the requested pagination data. +/// The object containing the criteria used to filter the results. +/// The name of the field by which to sort the results. +/// The direction in which to sort the results. +public record GetBooksLiteQuery( + PaginationDataDto? PaginationData, + LibraryFilterDto Filter, + string? SortBy, + SortOrder? SortOrder +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs new file mode 100644 index 00000000..5c54507c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs @@ -0,0 +1,80 @@ +#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.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Lumina.Contracts.Responses.Common; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DTO.Pagination; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; + +/// +/// Handler for the query to get the lightweight details of all books. +/// +public class GetBooksLiteQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetBooksLiteQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the lightweight details of all books. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error message. + /// + public async Task>> HandleAsync(GetBooksLiteQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // check if the user has the rights to access the library they are requesting (admins can see all libraries) + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) // if its not an admin, then it must own the library + { + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Filter.LibraryId, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value?.UserId != _currentUserService.UserId) + return Errors.Authorization.NotAuthorized; + } + + // get all books of the media library from the book repository + Result> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync( + query.PaginationData, + query.SortBy, + query.SortOrder, + query.Filter, + cancellationToken).ConfigureAwait(false); + return getBooksResult.Match(value => Result.From(value.ToLiteResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs new file mode 100644 index 00000000..78cb8a79 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; + +/// +/// Validates the needed validation rules for . +/// +public class GetBooksLiteQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetBooksLiteQueryValidator() + { + RuleFor(query => query.Filter.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj index 73963c32..3d18ba3c 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -25,8 +25,4 @@ - - - - diff --git a/src/Lumina.Contracts/DTO/Common/Filtering/BaseFilterDto.cs b/src/Lumina.Contracts/DTO/Common/Filtering/BaseFilterDto.cs new file mode 100644 index 00000000..89a34ecc --- /dev/null +++ b/src/Lumina.Contracts/DTO/Common/Filtering/BaseFilterDto.cs @@ -0,0 +1,12 @@ +namespace Lumina.Contracts.DTO.Common.Filtering; + +/// +/// Data transfer object that defines common filter properties used when quering paginated data. Implementations may add additional properties specific to their module or domain. +/// +public record BaseFilterDto +{ + /// + /// The search term used to filter results. + /// + public string? SearchTerm { get; init; } +} diff --git a/src/Lumina.Contracts/DTO/Common/Filtering/LibraryFilterDto.cs b/src/Lumina.Contracts/DTO/Common/Filtering/LibraryFilterDto.cs new file mode 100644 index 00000000..e1aabbf1 --- /dev/null +++ b/src/Lumina.Contracts/DTO/Common/Filtering/LibraryFilterDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.DTO.Common.Filtering; + +/// +/// Data transfer object that represents the parameters required to filter by library data. +/// +public record LibraryFilterDto : BaseFilterDto +{ + /// + /// The Id of the media library used to filter data. + /// + public required Guid LibraryId { get; init; } +} diff --git a/src/Lumina.Contracts/DTO/Common/Pagination/PaginationDataDto.cs b/src/Lumina.Contracts/DTO/Common/Pagination/PaginationDataDto.cs new file mode 100644 index 00000000..94f81b2b --- /dev/null +++ b/src/Lumina.Contracts/DTO/Common/Pagination/PaginationDataDto.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.DTO.Common.Pagination; + +/// +/// Data transfer object for pagination metadata. +/// +public sealed record PaginationDataDto +{ + private int perPage = 200; + private int currentPage = 1; + + /// + /// Gets the current page number in a paginated collection. + /// + public int CurrentPage + { + get { return currentPage; } + set + { + currentPage = Math.Max(value, 1); + } + } + + /// + /// Gets or sets the number of items to include per page in paginated results. + /// + public int PerPage + { + get { return perPage; } + set + { + perPage = Math.Max(value, 1); + } + } +} diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs new file mode 100644 index 00000000..4dbd3438 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// 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. +/// The name of the field by which to sort the results. Optional. +/// The direction in which to sort the results. Optional. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetBooksLiteRequest( + Guid LibraryId, + int? CurrentPage, + int? PerPage, + string? SearchTerm, + string? SortBy, + SortOrder? SortOrder +); 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 cbfb36f0..257a402b 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; using System.Diagnostics; #endregion @@ -9,7 +10,17 @@ 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}")] public record GetBooksRequest( - Guid LibraryId + Guid LibraryId, + int? CurrentPage, + int? PerPage, + string? SearchTerm, + string? SortBy, + SortOrder? SortOrder ); diff --git a/src/Lumina.Contracts/Responses/Common/PaginatedResponse.cs b/src/Lumina.Contracts/Responses/Common/PaginatedResponse.cs new file mode 100644 index 00000000..afb9debb --- /dev/null +++ b/src/Lumina.Contracts/Responses/Common/PaginatedResponse.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +#endregion + +namespace Lumina.Contracts.Responses.Common; + +/// +/// Represents a paginated response containing a subset of data and pagination metadata for the current page. +/// +/// The type of the data items contained in the paginated response. +public sealed record PaginatedResponse +{ + /// + /// Gets the collection of data items associated with this instance. + /// + public required IReadOnlyList Data { get; init; } + + /// + /// Gets the current page number in a paginated collection. + /// + public required int CurrentPage { get; init; } + + /// + /// Gets or sets the number of items to include per page in paginated results. + /// + public required int PerPage { get; init; } + + /// + /// Gets the total number of elements available in the paginated result set. + /// + public required int Count { get; init; } + + /// + /// Gets the total number of pages based on elements available in the result set and per page. + /// + public required int NumberOfPages { get; init; } +} diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponse.cs new file mode 100644 index 00000000..69472e61 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a lightweight book response, containing only the properties needed by the client for card-style navigation. +/// +/// The Id of the book. +/// The title of the book. +/// The release year of the book (re-release year, if available, or original release year), if known. +/// The path of the image representing the cover of the book, if available. +[DebuggerDisplay("Title: {Title}")] +public record BookLiteResponse( + Guid Id, + string Title, + int? ReleaseYear, + string? CoverPath +); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index f9ef8b27..91e237c0 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -1,11 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Specifications; +using Lumina.DataAccess.Core.Repositories.Books.Specifications; using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -54,8 +59,8 @@ internal sealed class BookRepository : IBookRepository .ToListAsync(cancellationToken).ConfigureAwait(false); // replace tags and genres in the book with existing ones - book.Tags = new HashSet(book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)); - book.Genres = new HashSet(book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)); + book.Tags = [.. book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)]; + book.Genres = [.. book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)]; _luminaDbContext.Books.Add(book); return Result.Created; @@ -90,6 +95,73 @@ internal sealed class BookRepository : IBookRepository .ToListAsync(cancellationToken).ConfigureAwait(false); } + /// + /// Gets paginated books. + /// + /// The type of the filter used for filtering the data. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching books are returned. + /// 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. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + public async Task>> GetPaginatedAsync(PaginationDataDto? paginationData, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto + { + IQueryable booksQuery = _luminaDbContext.Books + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .AsNoTracking(); + + // books should always be retrieved only per owning libraries + if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty) + return Errors.Library.FilterMustIncludeLibraryId; + + booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId); + + FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter.SearchTerm); + // apply filtering + if (filterSpecification is not null) + booksQuery = booksQuery.Where(filterSpecification.ToExpression()); + + // apply sorting based on the specified sortBy and sortOrder parameters + booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending); + + // if no pagination was requested, return all the books of the library + if (paginationData is null) + { + IReadOnlyList allBooks = await booksQuery.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allBooks, + CurrentPage = 1, + PerPage = allBooks.Count, + Count = allBooks.Count, + NumberOfPages = 1 + }; + } + + int count = await booksQuery.Select(book => book.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // make sure current page doesn't exceed maximum number of pages + + // apply pagination + IReadOnlyList paginatedResult = await booksQuery + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; + } + /// /// Gets all the books of the media library identified by . /// @@ -176,4 +248,45 @@ internal sealed class BookRepository : IBookRepository _luminaDbContext.Entry(foundBook).CurrentValues.SetValues(data); return Result.Updated; } + + /// + /// Sorts a books query by the given field name, defaulting to . + /// + /// The query to sort. + /// The field to sort by (case-insensitive). + /// The direction of the sorting. + private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder) + { + return sortBy?.ToLower() switch + { + "languagecode" => sortOrder == SortOrder.Descending + ? booksQuery.OrderByDescending(book => book.LanguageCode) + : booksQuery.OrderBy(book => book.LanguageCode), + "format" => sortOrder == SortOrder.Descending + ? booksQuery.OrderBy(book => book.Format == null).ThenByDescending(book => book.Format) + : booksQuery.OrderBy(book => book.Format == null).ThenBy(book => book.Format), + "metadataprovider" => sortOrder == SortOrder.Descending + ? booksQuery.OrderByDescending(book => book.MetadataProvider) + : booksQuery.OrderBy(book => book.MetadataProvider), + _ => sortOrder == SortOrder.Descending + ? booksQuery.OrderByDescending(book => book.Title) + : booksQuery.OrderBy(book => book.Title), + }; + } + + /// + /// Builds a filter specification for querying books. + /// + /// The search term used to filter results. + /// A filter specification that can be used to query books matching the provided criteria. + private static FilterSpecification? BuildFilterSpecification(string? searchTerm) + { + FilterSpecification? filterSpecification = null; + + // include the search term filter here, if provided + if (!string.IsNullOrWhiteSpace(searchTerm)) + filterSpecification = new BookSearchSpecification(searchTerm); + + return filterSpecification; + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookSearchSpecification.cs b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookSearchSpecification.cs new file mode 100644 index 00000000..18cb7e22 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookSearchSpecification.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Specifications; +using System; +using System.Linq.Expressions; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Books.Specifications; + +/// +/// Represents a filter specification for filtering or searching book entities based on a search term. +/// +internal sealed class BookSearchSpecification : FilterSpecification +{ + private readonly string _searchTerm; + + /// + /// Initializes a new instance of the class. + /// + /// The term to use when filtering or searching for books. + public BookSearchSpecification(string searchTerm) + { + _searchTerm = searchTerm; + } + + /// + /// Creates a LINQ expression that represents the predicate defined by the current specification. + /// + /// An expression tree that can be used to evaluate whether a satisfies the specification criteria. + public override Expression> ToExpression() + { + return book => book.Title.Contains(_searchTerm) || (book.OriginalTitle != null && book.OriginalTitle.Contains(_searchTerm)); + } +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Common/SortOrder.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Common/SortOrder.cs new file mode 100644 index 00000000..e8024a7b --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Common/SortOrder.cs @@ -0,0 +1,17 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Common; + +/// +/// Enumeration for the sort order +/// +public enum SortOrder +{ + /// + /// Ascending order. + /// + Ascending, + + /// + /// Descending order. + /// + Descending +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs index 51a7d7dd..88aca409 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -14,6 +14,7 @@ public static partial class Errors public static Error CannotScanLockedLibrary => Error.Forbidden(description: nameof(CannotScanLockedLibrary)); public static Error CannotScanDisabledLibrary => Error.Forbidden(description: nameof(CannotScanDisabledLibrary)); public static Error LibraryIdCannotBeEmpty => Error.Validation(description: nameof(LibraryIdCannotBeEmpty)); + public static Error FilterMustIncludeLibraryId => Error.Validation(description: nameof(FilterMustIncludeLibraryId)); public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists)); public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound)); public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull)); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs index 4c356ef1..6c91fe79 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs @@ -12,6 +12,7 @@ public static partial class ApiRoutes { public const string GET_BOOK_BY_ID = "/books/{id}"; public const string GET_BOOKS = "/books"; + public const string GET_BOOKS_LITE = "/books/lite"; public const string ADD_BOOK = "/books"; } } 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 ad4d2407..4b2c139e 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 @@ -4,6 +4,7 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; @@ -21,13 +22,13 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// public class GetBooksEndpoint : BaseEndpoint { - private readonly IQueryHandler>> _getBooksQueryHandler; + private readonly IQueryHandler>> _getBooksQueryHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling get books queries. - public GetBooksEndpoint(IQueryHandler>> getBooksQueryHandler) + public GetBooksEndpoint(IQueryHandler>> getBooksQueryHandler) { _getBooksQueryHandler = getBooksQueryHandler; } @@ -50,7 +51,7 @@ public class GetBooksEndpoint : BaseEndpoint /// 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); + Result> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(), 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 534cb7b4..5555d764 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 @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; @@ -27,221 +28,228 @@ public class GetBooksEndpointSummary : Summary Description = "Returns the entire list of books."; - Response(200, "The list of books is returned.", - example: new BookResponse[] { - new( - Id: Guid.NewGuid(), - LibraryId: Guid.NewGuid(), - Path: "/books/the-fellowship-of-the-ring.epub", - Metadata: new( - Title: "The Fellowship of the Ring", - OriginalTitle: "The Fellowship of the Ring", - Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", - ReleaseInfo: new( - OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null), - OriginalReleaseYear: 1954, - ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null), - ReReleaseYear: 2001, - ReleaseCountry: "uk", - ReleaseVersion: "50th Anniversary Edition" - ), - Genres: new List() { - { new(Name: "fantasy") }, - { new(Name: "adventure") }, - { new(Name: "classic") } - }, - Tags: new List() { - { new(Name: "epic fantasy") }, - { new(Name: "quest") }, - { new(Name: "middle-earth") } - }, - Language: new( - LanguageCode: "en", - LanguageName: "English", - NativeName: "English" - ), - OriginalLanguage: new( - LanguageCode: "en", - LanguageName: "English", - NativeName: "English" - ), - Publisher: "Houghton Mifflin", - PageCount: 398 + Response(200, "The paginated list of books is returned.", + example: new PaginatedResponse + { + Data = [ + new( + Id: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/books/the-fellowship-of-the-ring.epub", + Metadata: new( + Title: "The Fellowship of the Ring", + OriginalTitle: "The Fellowship of the Ring", + Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + ReleaseInfo: new( + OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null), + OriginalReleaseYear: 1954, + ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null), + ReReleaseYear: 2001, + ReleaseCountry: "uk", + ReleaseVersion: "50th Anniversary Edition" + ), + Genres: new List() { + { new(Name: "fantasy") }, + { new(Name: "adventure") }, + { new(Name: "classic") } + }, + Tags: new List() { + { new(Name: "epic fantasy") }, + { new(Name: "quest") }, + { new(Name: "middle-earth") } + }, + Language: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Publisher: "Houghton Mifflin", + PageCount: 398 - ), - Format: BookFormat.Paperback, - Edition: "50th Anniversary Edition", - VolumeNumber: 1, - Series: new BookSeriesDto( - Title: "The Lord of the Rings" - ), - ASIN: "B007978NPG", - GoodreadsId: "3", - LCCN: "54009621", - OCLCNumber: "ocm00012345", - OpenLibraryId: "OL7603910M", - LibraryThingId: "3203347", - GoogleBooksId: "aWZzLPhY4o0C", - BarnesAndNobleId: "1100307790", - AppleBooksId: "id395211", - ISBNs: [ - new( - Value: "0395272238", - Format: IsbnFormat.Isbn10 ), - new( - Value: "9780395272237", - Format: IsbnFormat.Isbn13 - ) - ], - Contributors: [ - new( - Name: new MediaContributorNameDto( - DisplayName: "J.R.R. Tolkien", - LegalName: "John Ronald Reuel Tolkien" + Format: BookFormat.Paperback, + Edition: "50th Anniversary Edition", + VolumeNumber: 1, + Series: new BookSeriesDto( + Title: "The Lord of the Rings" + ), + ASIN: "B007978NPG", + GoodreadsId: "3", + LCCN: "54009621", + OCLCNumber: "ocm00012345", + OpenLibraryId: "OL7603910M", + LibraryThingId: "3203347", + GoogleBooksId: "aWZzLPhY4o0C", + BarnesAndNobleId: "1100307790", + AppleBooksId: "id395211", + ISBNs: [ + new( + Value: "0395272238", + Format: IsbnFormat.Isbn10 ), - Role: new MediaContributorRoleDto( - Name: "author", - Category: "book" + new( + Value: "9780395272237", + Format: IsbnFormat.Isbn13 ) - ), - new( - Name: new MediaContributorNameDto( - DisplayName: "Alan Lee", - LegalName: "Alan Lee" + ], + Contributors: [ + new( + Name: new MediaContributorNameDto( + DisplayName: "J.R.R. Tolkien", + LegalName: "John Ronald Reuel Tolkien" + ), + Role: new MediaContributorRoleDto( + Name: "author", + Category: "book" + ) ), - Role: new MediaContributorRoleDto( - Name: "illustrator", - Category: "book" + new( + Name: new MediaContributorNameDto( + DisplayName: "Alan Lee", + LegalName: "Alan Lee" + ), + Role: new MediaContributorRoleDto( + Name: "illustrator", + Category: "book" + ) ) - ) - ], - Ratings: [ - new( - Source: BookRatingSource.GoogleBooks, - Value: 4.36M, - MaxValue: 5, - VoteCount: 2345678 - ), - new( - Source: BookRatingSource.Amazon, - Value: 4.7M, - MaxValue: 5, - VoteCount: 87654 - ) - ], - MetadataStatus: MetadataStatus.Pending, - LastMetadataUpdateUtc: default, - MetadataProvider: default, - CreatedOnUtc: DateTime.UtcNow, - UpdatedOnUtc: default - ), - new( - Id: Guid.NewGuid(), - LibraryId: Guid.NewGuid(), - Path: "/books/the-two-towers.epub", - Metadata: new( - Title: "The Two Towers", - OriginalTitle: "The Two Towers", - Description: "The second part of J.R.R. Tolkien's epic adventure The Lord of the Rings. The Fellowship is scattered, and the quest to destroy the One Ring continues. Aragorn, Legolas, and Gimli search for Merry and Pippin, while Frodo and Sam take the Ring closer to Mordor under the guidance of the mysterious Gollum.", - ReleaseInfo: new( - OriginalReleaseDate: DateOnly.ParseExact("1954-11-11", "yyyy-MM-dd", null), - OriginalReleaseYear: 1954, - ReReleaseDate: DateOnly.ParseExact("2001-11-08", "yyyy-MM-dd", null), - ReReleaseYear: 2001, - ReleaseCountry: "uk", - ReleaseVersion: "50th Anniversary Edition" - ), - Genres: new List() { - { new(Name: "fantasy") }, - { new(Name: "adventure") }, - { new(Name: "classic") } - }, - Tags: new List() { - { new(Name: "epic fantasy") }, - { new(Name: "quest") }, - { new(Name: "middle-earth") } - }, - Language: new( - LanguageCode: "en", - LanguageName: "English", - NativeName: "English" - ), - OriginalLanguage: new( - LanguageCode: "en", - LanguageName: "English", - NativeName: "English" - ), - Publisher: "Houghton Mifflin", - PageCount: 352 + ], + Ratings: [ + new( + Source: BookRatingSource.GoogleBooks, + Value: 4.36M, + MaxValue: 5, + VoteCount: 2345678 + ), + new( + Source: BookRatingSource.Amazon, + Value: 4.7M, + MaxValue: 5, + VoteCount: 87654 + ) + ], + MetadataStatus: MetadataStatus.Pending, + LastMetadataUpdateUtc: default, + MetadataProvider: default, + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: default ), - Format: BookFormat.Hardcover, - Edition: "50th Anniversary Edition", - VolumeNumber: 2, - Series: new BookSeriesDto( - Title: "The Lord of the Rings" - ), - ASIN: "B007978NPZ", - GoodreadsId: "33", - LCCN: "54009622", - OCLCNumber: "ocm00067890", - OpenLibraryId: "OL7603911M", - LibraryThingId: "3203348", - GoogleBooksId: "aWZzLPhY4o1D", - BarnesAndNobleId: "1100307791", - AppleBooksId: "id395212", - ISBNs: [ - new( - Value: "0395272246", - Format: IsbnFormat.Isbn10 - ), - new( - Value: "9780395272244", - Format: IsbnFormat.Isbn13 - ) - ], - Contributors: [ - new( - Name: new MediaContributorNameDto( - DisplayName: "J.R.R. Tolkien", - LegalName: "John Ronald Reuel Tolkien" + new( + Id: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/books/the-two-towers.epub", + Metadata: new( + Title: "The Two Towers", + OriginalTitle: "The Two Towers", + Description: "The second part of J.R.R. Tolkien's epic adventure The Lord of the Rings. The Fellowship is scattered, and the quest to destroy the One Ring continues. Aragorn, Legolas, and Gimli search for Merry and Pippin, while Frodo and Sam take the Ring closer to Mordor under the guidance of the mysterious Gollum.", + ReleaseInfo: new( + OriginalReleaseDate: DateOnly.ParseExact("1954-11-11", "yyyy-MM-dd", null), + OriginalReleaseYear: 1954, + ReReleaseDate: DateOnly.ParseExact("2001-11-08", "yyyy-MM-dd", null), + ReReleaseYear: 2001, + ReleaseCountry: "uk", + ReleaseVersion: "50th Anniversary Edition" ), - Role: new MediaContributorRoleDto( - Name: "author", - Category: "book" - ) - ), - new( - Name: new MediaContributorNameDto( - DisplayName: "Alan Lee", - LegalName: "Alan Lee" + Genres: new List() { + { new(Name: "fantasy") }, + { new(Name: "adventure") }, + { new(Name: "classic") } + }, + Tags: new List() { + { new(Name: "epic fantasy") }, + { new(Name: "quest") }, + { new(Name: "middle-earth") } + }, + Language: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" ), - Role: new MediaContributorRoleDto( - Name: "illustrator", - Category: "book" - ) - ) - ], - Ratings: [ - new( - Source: BookRatingSource.GoogleBooks, - Value: 4.4M, - MaxValue: 5, - VoteCount: 2340000 + OriginalLanguage: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Publisher: "Houghton Mifflin", + PageCount: 352 ), - new( - Source: BookRatingSource.Amazon, - Value: 4.8M, - MaxValue: 5, - VoteCount: 90000 - ) - ], - MetadataStatus: MetadataStatus.Pending, - LastMetadataUpdateUtc: default, - MetadataProvider: default, - CreatedOnUtc: DateTime.UtcNow, - UpdatedOnUtc: default - ) + Format: BookFormat.Hardcover, + Edition: "50th Anniversary Edition", + VolumeNumber: 2, + Series: new BookSeriesDto( + Title: "The Lord of the Rings" + ), + ASIN: "B007978NPZ", + GoodreadsId: "33", + LCCN: "54009622", + OCLCNumber: "ocm00067890", + OpenLibraryId: "OL7603911M", + LibraryThingId: "3203348", + GoogleBooksId: "aWZzLPhY4o1D", + BarnesAndNobleId: "1100307791", + AppleBooksId: "id395212", + ISBNs: [ + new( + Value: "0395272246", + Format: IsbnFormat.Isbn10 + ), + new( + Value: "9780395272244", + Format: IsbnFormat.Isbn13 + ) + ], + Contributors: [ + new( + Name: new MediaContributorNameDto( + DisplayName: "J.R.R. Tolkien", + LegalName: "John Ronald Reuel Tolkien" + ), + Role: new MediaContributorRoleDto( + Name: "author", + Category: "book" + ) + ), + new( + Name: new MediaContributorNameDto( + DisplayName: "Alan Lee", + LegalName: "Alan Lee" + ), + Role: new MediaContributorRoleDto( + Name: "illustrator", + Category: "book" + ) + ) + ], + Ratings: [ + new( + Source: BookRatingSource.GoogleBooks, + Value: 4.4M, + MaxValue: 5, + VoteCount: 2340000 + ), + new( + Source: BookRatingSource.Amazon, + Value: 4.8M, + MaxValue: 5, + VoteCount: 90000 + ) + ], + MetadataStatus: MetadataStatus.Pending, + LastMetadataUpdateUtc: default, + MetadataProvider: default, + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: default + ) + ], + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 } ); @@ -275,5 +283,26 @@ public class GetBooksEndpointSummary : Summary } } ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); } } 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 new file mode 100644 index 00000000..31b17ea6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; + +/// +/// API endpoint for the /books/lite route. +/// +public class GetBooksLiteEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getBooksLiteQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get books lite queries. + public GetBooksLiteEndpoint(IQueryHandler>> getBooksLiteQueryHandler) + { + _getBooksLiteQueryHandler = getBooksLiteQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Books.GET_BOOKS_LITE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the lightweight details of all the books of the media library identified by . + /// + /// The request containing the Id of the media library whose books are 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); + 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 new file mode 100644 index 00000000..b8dfb1fe --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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."; + + Response(200, "The paginated list of lightweight book details is returned.", + example: new PaginatedResponse + { + Data = [ + new( + Id: Guid.NewGuid(), + Title: "The Fellowship of the Ring", + ReleaseYear: 1954, + CoverPath: null + ), + new( + Id: Guid.NewGuid(), + Title: "The Two Towers", + ReleaseYear: 1954, + CoverPath: null + ) + ], + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/books/lite" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/books/lite" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/books/lite" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books/lite", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Specifications/AlwaysFalseFilterSpecificationFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Specifications/AlwaysFalseFilterSpecificationFixture.cs new file mode 100644 index 00000000..9261fdb0 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Specifications/AlwaysFalseFilterSpecificationFixture.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Specifications; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.Fixtures.Common.Specifications; + +/// +/// Fixture class for generating a instance that is never satisfied, regardless of the entity being evaluated. +/// +/// The type of entity to which the specification applies. +[ExcludeFromCodeCoverage] +public sealed class AlwaysFalseFilterSpecificationFixture : FilterSpecification +{ + /// + /// Creates a LINQ expression that always evaluates to . + /// + /// An expression tree that always evaluates to . + public override Expression> ToExpression() + { + return entity => false; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Specifications/AlwaysTrueFilterSpecificationFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Specifications/AlwaysTrueFilterSpecificationFixture.cs new file mode 100644 index 00000000..cfa8d7da --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Specifications/AlwaysTrueFilterSpecificationFixture.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Specifications; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.Fixtures.Common.Specifications; + +/// +/// Fixture class for generating a instance that is always satisfied, regardless of the entity being evaluated. +/// +/// The type of entity to which the specification applies. +[ExcludeFromCodeCoverage] +public sealed class AlwaysTrueFilterSpecificationFixture : FilterSpecification +{ + /// + /// Creates a LINQ expression that always evaluates to . + /// + /// An expression tree that always evaluates to . + public override Expression> ToExpression() + { + return entity => true; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Specifications/GreaterThanFilterSpecificationFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Specifications/GreaterThanFilterSpecificationFixture.cs new file mode 100644 index 00000000..b1e2d388 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Specifications/GreaterThanFilterSpecificationFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Specifications; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.Fixtures.Common.Specifications; + +/// +/// Fixture class for generating a instance that is satisfied when an integer value exceeds a configured threshold. +/// +[ExcludeFromCodeCoverage] +public sealed class GreaterThanFilterSpecificationFixture : FilterSpecification +{ + private readonly int _threshold; + + /// + /// Initializes a new instance of the class. + /// + /// The threshold value that an entity must exceed to satisfy the specification. + public GreaterThanFilterSpecificationFixture(int threshold) + { + _threshold = threshold; + } + + /// + /// Creates a LINQ expression that evaluates whether a value is greater than the configured threshold. + /// + /// An expression tree that evaluates to when the value exceeds the threshold. + public override Expression> ToExpression() + { + int threshold = _threshold; + return value => value > threshold; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs new file mode 100644 index 00000000..caa8d830 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksQueryFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid query to get books. + /// + /// Optional. The Id of the media library whose books are retrieved. + /// Optional. The pagination data of the query. + /// Optional. The search term used to filter results. + /// Optional. The name of the field by which to sort the results. + /// Optional. The direction in which to sort the results. + /// The created query to get books. + public GetBooksQuery Create( + Guid? libraryId = null, + PaginationDataDto? paginationData = null, + string? searchTerm = null, + string? sortBy = null, + SortOrder? sortOrder = null) + { + return new GetBooksQuery( + paginationData ?? new PaginationDataDto + { + CurrentPage = _faker.Random.Number(1, 100), + PerPage = _faker.Random.Number(1, 200) + }, + new LibraryFilterDto + { + LibraryId = libraryId ?? _faker.Random.Guid(), + SearchTerm = searchTerm + }, + sortBy, + sortOrder ?? _faker.PickRandom() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs new file mode 100644 index 00000000..c23b0a8b --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteQueryFixture +{ + private readonly Faker _faker = 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 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. + /// The created query to get the lightweight details of books. + public GetBooksLiteQuery Create( + Guid? libraryId = null, + PaginationDataDto? paginationData = null, + string? searchTerm = null, + string? sortBy = null, + SortOrder? sortOrder = null) + { + return new GetBooksLiteQuery( + paginationData ?? new PaginationDataDto + { + CurrentPage = _faker.Random.Number(1, 100), + PerPage = _faker.Random.Number(1, 200) + }, + new LibraryFilterDto + { + LibraryId = libraryId ?? _faker.Random.Guid(), + SearchTerm = searchTerm + }, + sortBy, + sortOrder ?? _faker.PickRandom() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} 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 new file mode 100644 index 00000000..1d943636 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +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; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// 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. + /// Optional. The name of the field by which to sort the results. + /// Optional. The direction in which to sort the results. + /// The created . + public GetBooksLiteRequest Create( + Guid? libraryId = null, + int? currentPage = null, + int? perPage = null, + string? searchTerm = null, + string? sortBy = null, + SortOrder? sortOrder = null) + { + return new GetBooksLiteRequest( + LibraryId: libraryId ?? _faker.Random.Guid(), + CurrentPage: currentPage ?? _faker.Random.Number(1, 100), + PerPage: perPage ?? _faker.Random.Number(1, 200), + SearchTerm: searchTerm ?? _faker.Lorem.Word(), + SortBy: sortBy ?? _faker.Lorem.Word(), + SortOrder: sortOrder ?? _faker.PickRandom() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} 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 new file mode 100644 index 00000000..cd898891 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +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; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetBooksRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// 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. + /// Optional. The name of the field by which to sort the results. + /// Optional. The direction in which to sort the results. + /// The created . + public GetBooksRequest Create( + Guid? libraryId = null, + int? currentPage = null, + int? perPage = null, + string? searchTerm = null, + string? sortBy = null, + SortOrder? sortOrder = null) + { + return new GetBooksRequest( + LibraryId: libraryId ?? _faker.Random.Guid(), + CurrentPage: currentPage ?? _faker.Random.Number(1, 100), + PerPage: perPage ?? _faker.Random.Number(1, 200), + SearchTerm: searchTerm ?? _faker.Lorem.Word(), + SortBy: sortBy ?? _faker.Lorem.Word(), + SortOrder: sortOrder ?? _faker.PickRandom() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} 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 260e1779..ab76cfd6 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 @@ -1,9 +1,19 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -25,7 +35,6 @@ public class GetBooksEndpointTests : IClassFixture(_jsonOptions); - Assert.NotNull(bookResponse); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(2, paginatedBooks!.Count); + Assert.Equal(2, paginatedBooks.Data.Count); + Assert.Equal(1, paginatedBooks.CurrentPage); + Assert.Equal(2, paginatedBooks.PerPage); + Assert.Equal(1, paginatedBooks.NumberOfPages); + Assert.Contains(paginatedBooks.Data, book => book.Metadata.Title == "Book A"); + Assert.Contains(paginatedBooks.Data, book => book.Metadata.Title == "Book B"); + } + + [Fact] + public async Task GetBooks_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingBooks() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "The Fellowship of the Ring"); + await SeedBookAsync(libraryId, "The Two Towers"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString("Fellowship")}"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + BookResponse book = Assert.Single(paginatedBooks!.Data); + Assert.Equal("The Fellowship of the Ring", book.Metadata.Title); + Assert.Equal(1, paginatedBooks.Count); + } + + [Fact] + public async Task GetBooks_WhenCalledWithPaginationData_ShouldReturnRequestedPage() + { + // 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/books?libraryId={libraryId}¤tPage=2&perPage=2"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(3, paginatedBooks!.Count); + Assert.Equal(2, paginatedBooks.NumberOfPages); + Assert.Equal(2, paginatedBooks.CurrentPage); + Assert.Equal(2, paginatedBooks.PerPage); + BookResponse book = Assert.Single(paginatedBooks.Data); + Assert.Equal("Book C", book.Metadata.Title); + } + + [Fact] + public async Task GetBooks_WhenNoBooksExist_ShouldReturnEmptyPaginatedResponse() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Empty(paginatedBooks!.Data); + Assert.Equal(0, paginatedBooks.Count); } [Fact] public async Task GetBooks_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/books", cts.Token) + await _client.GetAsync($"/api/v1/books?libraryId={libraryId}", cts.Token) ); Assert.Null(exception); } @@ -81,17 +172,183 @@ public class GetBooksEndpointTests : IClassFixture { cts.Cancel(); - await _client.GetAsync($"/api/v1/books", cts.Token); + await _client.GetAsync($"/api/v1/books?libraryId={libraryId}", cts.Token); }); Assert.IsType(exception); } + [Fact] + public async Task GetBooks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden() + { + // Arrange + Guid otherUserId = await SeedUserAsync(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, otherUserId); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task GetBooks_WhenLibraryDoesNotExist_ShouldReturnForbidden() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task GetBooks_WhenCalledByAdmin_ShouldReturnBooksOfAnyLibrary() + { + // Arrange + HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync(); + Guid otherUserId = await SeedUserAsync(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, otherUserId); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/books?libraryId={libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(1, paginatedBooks!.Count); + } + + [Fact] + public async Task GetBooks_WhenBooksHaveTagsGenresIsbnsAndRatings_ShouldReturnThemInTheResponse() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + BookEntity seededBook = await SeedBookAsync(libraryId, "Tags And Ratings Book"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + BookResponse book = Assert.Single(paginatedBooks!.Data); + Assert.Equal(seededBook.Title, book.Metadata.Title); + Assert.Equal(seededBook.Tags.Select(tag => tag.Name), book.Metadata.Tags.Select(tag => tag.Name)); + Assert.Equal(seededBook.Genres.Select(genre => genre.Name), book.Metadata.Genres.Select(genre => genre.Name)); + Assert.Equal(seededBook.ISBNs.Select(isbn => isbn.Value), book.ISBNs.Select(isbn => isbn.Value)); + Assert.Equal(seededBook.Ratings.Select(rating => rating.Value), book.Ratings.Select(rating => rating.Value)); + Assert.Equal(seededBook.Ratings.Single().Source, book.Ratings.Single().Source); + } + + /// + /// Seeds a belonging to the media library identified by . + /// + /// The Id of the media library the book belongs to. + /// The title of the book. + /// The seeded book entity. + private async Task SeedBookAsync(Guid libraryId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookEntity book = new() + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + Path = $"/books/{Guid.NewGuid()}.epub", + Title = title, + Tags = [new TagEntity($"Tag-{Guid.NewGuid()}")], + Genres = [new GenreEntity($"Genre-{Guid.NewGuid()}")], + ISBNs = [new IsbnEntity("9780395272237", IsbnFormat.Isbn13)], + Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)], + CreatedBy = Guid.NewGuid(), + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }; + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return book; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = "Test Library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(new UserEntity + { + Id = userId, + Username = $"otheruser_{Guid.NewGuid()}", + Password = "TestPass123!", + Libraries = [], + UserPermissions = [], + UserRole = null, + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow + }); + await dbContext.SaveChangesAsync(); + return userId; + } + /// /// Disposes API factory resources. /// 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 new file mode 100644 index 00000000..6b39fd29 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -0,0 +1,293 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +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; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetBooksLiteEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetBooksLite_WhenCalledWithoutPaginationData_ShouldReturnAllBooks() + { + // 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/books/lite?libraryId={libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(2, paginatedBooks!.Count); + Assert.Equal(2, paginatedBooks.Data.Count()); + Assert.Equal(1, paginatedBooks.CurrentPage); + Assert.Equal(2, paginatedBooks.PerPage); + Assert.Equal(1, paginatedBooks.NumberOfPages); + Assert.Contains(paginatedBooks.Data, book => book.Title == "Book A"); + Assert.Contains(paginatedBooks.Data, book => book.Title == "Book B"); + } + + [Fact] + public async Task GetBooksLite_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingBooks() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "The Fellowship of the Ring"); + await SeedBookAsync(libraryId, "The Two Towers"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString("Fellowship")}"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + BookLiteResponse book = Assert.Single(paginatedBooks!.Data); + Assert.Equal("The Fellowship of the Ring", book.Title); + Assert.Equal(1, paginatedBooks.Count); + } + + [Fact] + public async Task GetBooksLite_WhenCalledWithPaginationData_ShouldReturnRequestedPage() + { + // 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/books/lite?libraryId={libraryId}¤tPage=2&perPage=2"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(3, paginatedBooks!.Count); + Assert.Equal(2, paginatedBooks.NumberOfPages); + Assert.Equal(2, paginatedBooks.CurrentPage); + Assert.Equal(2, paginatedBooks.PerPage); + BookLiteResponse book = Assert.Single(paginatedBooks.Data); + Assert.Equal("Book C", book.Title); + } + + [Fact] + public async Task GetBooksLite_WhenNoBooksExist_ShouldReturnEmptyPaginatedResponse() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Empty(paginatedBooks!.Data); + Assert.Equal(0, paginatedBooks.Count); + } + + [Fact] + public async Task GetBooksLite_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden() + { + // Arrange + Guid otherUserId = await SeedUserAsync(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, otherUserId); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task GetBooksLite_WhenLibraryDoesNotExist_ShouldReturnForbidden() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task GetBooksLite_WhenCalledByAdmin_ShouldReturnBooksOfAnyLibrary() + { + // Arrange + HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync(); + Guid otherUserId = await SeedUserAsync(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, otherUserId); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/books/lite?libraryId={libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + PaginatedResponse? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Equal(1, paginatedBooks!.Count); + } + + /// + /// Seeds a belonging to the media library identified by . + /// + /// The Id of the media library the book belongs to. + /// The title of the book. + /// A task representing the asynchronous operation. + private async Task SeedBookAsync(Guid libraryId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Books.Add(new BookEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + Path = $"/books/{Guid.NewGuid()}.epub", + Title = title, + CreatedBy = Guid.NewGuid(), + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + await dbContext.SaveChangesAsync(); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = "Test Library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(new UserEntity + { + Id = userId, + Username = $"otheruser_{Guid.NewGuid()}", + Password = "TestPass123!", + Libraries = [], + UserPermissions = [], + UserRole = null, + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow + }); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } +} 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 new file mode 100644 index 00000000..801cc034 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -0,0 +1,169 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; + +/// +/// Contains security tests for the /books route. +/// +[ExcludeFromCodeCoverage] +public class GetBooksEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly PasswordHashService _hashService = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetBooksEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/books"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Books--")] // destructive injection + public async Task GetBooks_WhenSearchTermContainsSqlInjection_ShouldNotLeakOrError(string maliciousSearchTerm) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + await SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Creates a test user, authenticates it on , and returns its Id. + /// + /// The HTTP client to authenticate. + /// The Id of the created test user. + private async Task CreateAndAuthenticateUserAsync(HttpClient client) + { + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"testuser_{Guid.NewGuid()}"; + dbContext.Users.Add(new UserEntity + { + Id = userId, + Username = username, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + UserPermissions = [], + UserRole = null, + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow + }); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + string content = await loginResponse.Content.ReadAsStringAsync(); + LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); + + return userId; + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = "Test Library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a belonging to the media library identified by . + /// + /// The Id of the media library the book belongs to. + /// The title of the book. + /// A task representing the asynchronous operation. + private async Task SeedBookAsync(Guid libraryId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Books.Add(new BookEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + Path = $"/books/{Guid.NewGuid()}.epub", + Title = title, + CreatedBy = Guid.NewGuid(), + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + await dbContext.SaveChangesAsync(); + } +} 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 new file mode 100644 index 00000000..c9a61386 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; + +/// +/// Contains security tests for the /books/lite route. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetBooksLiteEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetBooksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/books/lite"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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("Authentication failed", problemDetails["detail"].GetString()); + } +} 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 7dcbadc5..c74035c2 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 @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; @@ -335,4 +337,101 @@ public class BookEntityMappingTests Assert.NotNull(results); Assert.Equal(bookEntities.Count, results.Count()); } + + [Fact] + public void ToResponses_WhenMappingPaginatedBookEntities_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List bookEntities = _bookEntityFixture.CreateMany(2); + PaginatedResultDto paginatedBookEntities = new() + { + Data = bookEntities, + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 + }; + + // Act + PaginatedResponse result = paginatedBookEntities.ToResponses(); + + // 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); + } + + [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 = new() + { + 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/GetBooksLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs new file mode 100644 index 00000000..5e1719ba --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteRequestMappingTests +{ + private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingGetBooksLiteRequest_ShouldMapCorrectly() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + + // Act + GetBooksLiteQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryId, result.Filter.LibraryId); + Assert.Equal(request.SearchTerm, result.Filter.SearchTerm); + Assert.Equal(request.SortBy, result.SortBy); + Assert.Equal(request.SortOrder, result.SortOrder); + Assert.NotNull(result.PaginationData); + Assert.Equal(request.CurrentPage, result.PaginationData!.CurrentPage); + Assert.Equal(request.PerPage, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + request = request with { CurrentPage = null, PerPage = null }; + + // Act + GetBooksLiteQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Null(result.PaginationData); + Assert.Equal(request.LibraryId, result.Filter.LibraryId); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + request = request with { CurrentPage = null, PerPage = 25 }; + + // Act + GetBooksLiteQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData!.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + request = request with { CurrentPage = 3, PerPage = null }; + + // Act + GetBooksLiteQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData!.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } +} 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 new file mode 100644 index 00000000..684fd2e0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksRequestMappingTests +{ + private readonly GetBooksRequestFixture _getBooksRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingGetBooksRequest_ShouldMapCorrectly() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + + // Act + GetBooksQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryId, result.Filter.LibraryId); + Assert.Equal(request.SearchTerm, result.Filter.SearchTerm); + Assert.Equal(request.SortBy, result.SortBy); + Assert.Equal(request.SortOrder, result.SortOrder); + Assert.NotNull(result.PaginationData); + Assert.Equal(request.CurrentPage, result.PaginationData!.CurrentPage); + Assert.Equal(request.PerPage, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + request = request with { CurrentPage = null, PerPage = null }; + + // Act + GetBooksQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Null(result.PaginationData); + Assert.Equal(request.LibraryId, result.Filter.LibraryId); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + request = request with { CurrentPage = null, PerPage = 25 }; + + // Act + GetBooksQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData!.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + request = request with { CurrentPage = 3, PerPage = null }; + + // Act + GetBooksQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData!.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/AndFilterSpecificationTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/AndFilterSpecificationTests.cs new file mode 100644 index 00000000..4a6d30f9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/AndFilterSpecificationTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Specifications; +using Lumina.Application.Fixtures.Common.Specifications; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.UnitTests.Common.Specifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AndFilterSpecificationTests +{ + [Fact] + public void ToExpression_WhenBothSpecificationsSatisfyCriteria_ShouldReturnExpressionThatEvaluatesToTrue() + { + // Arrange + GreaterThanFilterSpecificationFixture left = new(5); + GreaterThanFilterSpecificationFixture right = new(10); + AndFilterSpecification specification = new(left, right); + + // Act + Expression> expression = specification.ToExpression(); + Func predicate = expression.Compile(); + + // Assert + Assert.True(predicate(20)); + } + + [Fact] + public void ToExpression_WhenOnlyLeftSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToFalse() + { + // Arrange + GreaterThanFilterSpecificationFixture left = new(5); + GreaterThanFilterSpecificationFixture right = new(10); + AndFilterSpecification specification = new(left, right); + + // Act + Expression> expression = specification.ToExpression(); + Func predicate = expression.Compile(); + + // Assert + Assert.False(predicate(8)); + } + + [Fact] + public void ToExpression_WhenNeitherSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToFalse() + { + // Arrange + GreaterThanFilterSpecificationFixture left = new(5); + GreaterThanFilterSpecificationFixture right = new(10); + AndFilterSpecification specification = new(left, right); + + // Act + Expression> expression = specification.ToExpression(); + Func predicate = expression.Compile(); + + // Assert + Assert.False(predicate(2)); + } + + [Fact] + public void IsSatisfiedBy_WhenBothSpecificationsAreSatisfied_ShouldReturnTrue() + { + // Arrange + AlwaysTrueFilterSpecificationFixture left = new(); + AlwaysTrueFilterSpecificationFixture right = new(); + AndFilterSpecification specification = new(left, right); + + // Act + bool result = specification.IsSatisfiedBy(0); + + // Assert + Assert.True(result); + } + + [Fact] + public void IsSatisfiedBy_WhenEitherSpecificationIsNotSatisfied_ShouldReturnFalse() + { + // Arrange + AlwaysTrueFilterSpecificationFixture left = new(); + AlwaysFalseFilterSpecificationFixture right = new(); + AndFilterSpecification specification = new(left, right); + + // Act + bool result = specification.IsSatisfiedBy(0); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/FilterSpecificationTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/FilterSpecificationTests.cs new file mode 100644 index 00000000..81994500 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/FilterSpecificationTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Specifications; +using Lumina.Application.Fixtures.Common.Specifications; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.UnitTests.Common.Specifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FilterSpecificationTests +{ + [Fact] + public void ToExpression_WhenCalledOnConcreteSpecification_ShouldReturnExpressionMatchingCriteria() + { + // Arrange + GreaterThanFilterSpecificationFixture specification = new(10); + + // Act + Expression> expression = specification.ToExpression(); + Func predicate = expression.Compile(); + + // Assert + Assert.True(predicate(15)); + Assert.False(predicate(5)); + } + + [Fact] + public void IsSatisfiedBy_WhenEntitySatisfiesCriteria_ShouldReturnTrue() + { + // Arrange + GreaterThanFilterSpecificationFixture specification = new(10); + int entity = 20; + + // Act + bool result = specification.IsSatisfiedBy(entity); + + // Assert + Assert.True(result); + } + + [Fact] + public void IsSatisfiedBy_WhenEntityDoesNotSatisfyCriteria_ShouldReturnFalse() + { + // Arrange + GreaterThanFilterSpecificationFixture specification = new(10); + int entity = 5; + + // Act + bool result = specification.IsSatisfiedBy(entity); + + // Assert + Assert.False(result); + } + + [Fact] + public void And_WhenBothSpecificationsAreSatisfied_ShouldReturnSpecificationSatisfiedByEntity() + { + // Arrange + AlwaysTrueFilterSpecificationFixture left = new(); + AlwaysTrueFilterSpecificationFixture right = new(); + + // Act + FilterSpecification combined = left.And(right); + + // Assert + Assert.IsType>(combined); + Assert.True(combined.IsSatisfiedBy(0)); + } + + [Fact] + public void And_WhenOneSpecificationIsNotSatisfied_ShouldReturnSpecificationNotSatisfiedByEntity() + { + // Arrange + AlwaysTrueFilterSpecificationFixture left = new(); + AlwaysFalseFilterSpecificationFixture right = new(); + + // Act + FilterSpecification combined = left.And(right); + + // Assert + Assert.False(combined.IsSatisfiedBy(0)); + } + + [Fact] + public void And_WhenBothSpecificationsAreNotSatisfied_ShouldReturnSpecificationNotSatisfiedByEntity() + { + // Arrange + AlwaysFalseFilterSpecificationFixture left = new(); + AlwaysFalseFilterSpecificationFixture right = new(); + + // Act + FilterSpecification combined = left.And(right); + + // Assert + Assert.False(combined.IsSatisfiedBy(0)); + } + + [Fact] + public void Or_WhenAtLeastOneSpecificationIsSatisfied_ShouldReturnSpecificationSatisfiedByEntity() + { + // Arrange + AlwaysTrueFilterSpecificationFixture left = new(); + AlwaysFalseFilterSpecificationFixture right = new(); + + // Act + FilterSpecification combined = left.Or(right); + + // Assert + Assert.True(combined.IsSatisfiedBy(0)); + } + + [Fact] + public void Or_WhenNeitherSpecificationIsSatisfied_ShouldReturnSpecificationNotSatisfiedByEntity() + { + // Arrange + AlwaysFalseFilterSpecificationFixture left = new(); + AlwaysFalseFilterSpecificationFixture right = new(); + + // Act + FilterSpecification combined = left.Or(right); + + // Assert + Assert.False(combined.IsSatisfiedBy(0)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/OrFilterSpecificationTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/OrFilterSpecificationTests.cs new file mode 100644 index 00000000..317e74f7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Specifications/OrFilterSpecificationTests.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Specifications; +using Lumina.Application.Fixtures.Common.Specifications; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq.Expressions; +#endregion + +namespace Lumina.Application.UnitTests.Common.Specifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OrFilterSpecificationTests +{ + [Fact] + public void ToExpression_WhenOnlyLeftSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToTrue() + { + // Arrange + GreaterThanFilterSpecificationFixture left = new(5); + GreaterThanFilterSpecificationFixture right = new(10); + OrFilterSpecification specification = new(left, right); + + // Act + Expression> expression = specification.ToExpression(); + Func predicate = expression.Compile(); + + // Assert + Assert.True(predicate(8)); + } + + [Fact] + public void ToExpression_WhenOnlyRightSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToTrue() + { + // Arrange + GreaterThanFilterSpecificationFixture left = new(10); + GreaterThanFilterSpecificationFixture right = new(5); + OrFilterSpecification specification = new(left, right); + + // Act + Expression> expression = specification.ToExpression(); + Func predicate = expression.Compile(); + + // Assert + Assert.True(predicate(8)); + } + + [Fact] + public void ToExpression_WhenBothSpecificationsSatisfyCriteria_ShouldReturnExpressionThatEvaluatesToTrue() + { + // Arrange + GreaterThanFilterSpecificationFixture left = new(5); + GreaterThanFilterSpecificationFixture right = new(10); + OrFilterSpecification specification = new(left, right); + + // Act + Expression> expression = specification.ToExpression(); + Func predicate = expression.Compile(); + + // Assert + Assert.True(predicate(20)); + } + + [Fact] + public void ToExpression_WhenNeitherSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToFalse() + { + // Arrange + GreaterThanFilterSpecificationFixture left = new(5); + GreaterThanFilterSpecificationFixture right = new(10); + OrFilterSpecification specification = new(left, right); + + // Act + Expression> expression = specification.ToExpression(); + Func predicate = expression.Compile(); + + // Assert + Assert.False(predicate(2)); + } + + [Fact] + public void IsSatisfiedBy_WhenAtLeastOneSpecificationIsSatisfied_ShouldReturnTrue() + { + // Arrange + AlwaysTrueFilterSpecificationFixture left = new(); + AlwaysFalseFilterSpecificationFixture right = new(); + OrFilterSpecification specification = new(left, right); + + // Act + bool result = specification.IsSatisfiedBy(0); + + // Assert + Assert.True(result); + } + + [Fact] + public void IsSatisfiedBy_WhenNeitherSpecificationIsSatisfied_ShouldReturnFalse() + { + // Arrange + AlwaysFalseFilterSpecificationFixture left = new(); + AlwaysFalseFilterSpecificationFixture right = new(); + OrFilterSpecification specification = new(left, right); + + // Act + bool result = specification.IsSatisfiedBy(0); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs new file mode 100644 index 00000000..a77328a9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs @@ -0,0 +1,334 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetBooksQueryHandler _sut; + private readonly Guid _userId; + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly GetBooksQueryFixture _getBooksQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetBooksQueryHandlerTests() + { + _mockBookRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is not an admin, but owns the requested library + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((LibraryEntity?)new LibraryEntity + { + Id = Guid.NewGuid(), + UserId = _userId, + Title = "Test Library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = _userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + })); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetBooksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsPaginatedBooks_ShouldReturnMappedPaginatedResponses() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List bookEntities = _bookEntityFixture.CreateMany(2); + PaginatedResultDto paginatedBooks = new() + { + Data = bookEntities, + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + Result> result = await _sut.HandleAsync(query, cancellationToken); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(bookEntities.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); + Assert.Equal(paginatedBooks.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsEmptyPage_ShouldReturnEmptyPaginatedResponses() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + PaginatedResultDto paginatedBooks = new() + { + Data = [], + CurrentPage = 1, + PerPage = 10, + Count = 0, + NumberOfPages = 0 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Data); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Errors.Library.FilterMustIncludeLibraryId); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldQueryRepositoryWithMappedFilterAndPagination() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResultDto paginatedBooks = new() + { + Data = [], + CurrentPage = 1, + PerPage = 10, + Count = 0, + NumberOfPages = 0 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockBookRepository.Received(1).GetPaginatedAsync( + 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)); + } + + [Fact] + public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() + { + // Arrange + GetBooksQuery query = new( + PaginationData: null, + Filter: new LibraryFilterDto { LibraryId = Guid.NewGuid() }, + SortBy: null, + SortOrder: SortOrder.Ascending + ); + PaginatedResultDto paginatedBooks = new() + { + Data = [], + CurrentPage = 1, + PerPage = 10, + Count = 0, + NumberOfPages = 0 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + await _mockBookRepository.Received(1).GetPaginatedAsync( + 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()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsAdmin_ShouldBypassLibraryOwnershipCheck() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + PaginatedResultDto paginatedBooks = new() + { + Data = [], + CurrentPage = 1, + PerPage = 10, + Count = 0, + NumberOfPages = 0 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockUnitOfWork.LibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + Guid otherUserId = Guid.NewGuid(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((LibraryEntity?)new LibraryEntity + { + Id = Guid.NewGuid(), + UserId = otherUserId, + Title = "Someone else's library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = otherUserId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + })); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotAuthorizedError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs new file mode 100644 index 00000000..7751e3f0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksQueryValidatorTests +{ + private readonly GetBooksQueryValidator _validator = new(); + private readonly GetBooksQueryFixture _getBooksQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + query = query with { Filter = query.Filter with { LibraryId = Guid.Empty } }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs new file mode 100644 index 00000000..16c1ef31 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs @@ -0,0 +1,334 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetBooksLiteQueryHandler _sut; + private readonly Guid _userId; + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly GetBooksLiteQueryFixture _getBooksLiteQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetBooksLiteQueryHandlerTests() + { + _mockBookRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is not an admin, but owns the requested library + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((LibraryEntity?)new LibraryEntity + { + Id = Guid.NewGuid(), + UserId = _userId, + Title = "Test Library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = _userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + })); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetBooksLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsPaginatedBooks_ShouldReturnMappedPaginatedResponses() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List bookEntities = _bookEntityFixture.CreateMany(2); + PaginatedResultDto paginatedBooks = new() + { + Data = bookEntities, + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + Result> result = await _sut.HandleAsync(query, cancellationToken); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(bookEntities.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); + Assert.Equal(paginatedBooks.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsEmptyPage_ShouldReturnEmptyPaginatedResponses() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + PaginatedResultDto paginatedBooks = new() + { + Data = [], + CurrentPage = 1, + PerPage = 10, + Count = 0, + NumberOfPages = 0 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Data); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Errors.Library.FilterMustIncludeLibraryId); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldQueryRepositoryWithMappedFilterAndPagination() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResultDto paginatedBooks = new() + { + Data = [], + CurrentPage = 1, + PerPage = 10, + Count = 0, + NumberOfPages = 0 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockBookRepository.Received(1).GetPaginatedAsync( + 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)); + } + + [Fact] + public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() + { + // Arrange + GetBooksLiteQuery query = new( + PaginationData: null, + Filter: new LibraryFilterDto { LibraryId = Guid.NewGuid() }, + SortBy: null, + SortOrder: SortOrder.Ascending + ); + PaginatedResultDto paginatedBooks = new() + { + Data = [], + CurrentPage = 1, + PerPage = 10, + Count = 0, + NumberOfPages = 0 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + await _mockBookRepository.Received(1).GetPaginatedAsync( + 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()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsAdmin_ShouldBypassLibraryOwnershipCheck() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + PaginatedResultDto paginatedBooks = new() + { + Data = [], + CurrentPage = 1, + PerPage = 10, + Count = 0, + NumberOfPages = 0 + }; + _mockBookRepository.GetPaginatedAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(Result.From(paginatedBooks)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockUnitOfWork.LibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + Guid otherUserId = Guid.NewGuid(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((LibraryEntity?)new LibraryEntity + { + Id = Guid.NewGuid(), + UserId = otherUserId, + Title = "Someone else's library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = otherUserId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + })); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotAuthorizedError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs new file mode 100644 index 00000000..6055ca7d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteQueryValidatorTests +{ + private readonly GetBooksLiteQueryValidator _validator = new(); + private readonly GetBooksLiteQueryFixture _getBooksLiteQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + query = query with { Filter = query.Filter with { LibraryId = Guid.Empty } }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} 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 a5d2b1ab..f3a7b9b9 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -2,12 +2,15 @@ using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -326,4 +329,193 @@ public class BookRepositoryTests Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); } + + [Fact] + public async Task GetPaginatedAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks() + { + // 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 = new() { CurrentPage = 1, PerPage = 10 }; + LibraryFilterDto filter = new() { LibraryId = libraryId }; + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, 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 GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError() + { + // Arrange + PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; + BaseFilterDto filter = new(); + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError() + { + // Arrange + PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; + LibraryFilterDto filter = new() { LibraryId = Guid.Empty }; + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetPaginatedAsync_WhenPaginationDataIsNull_ShouldReturnAllBooks() + { + // 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 = new() { LibraryId = libraryId }; + + // Act + Result> result = await _sut.GetPaginatedAsync(null, null, null, filter, 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 GetPaginatedAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingBooks() + { + // 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 = new() { CurrentPage = 1, PerPage = 10 }; + LibraryFilterDto filter = new() { LibraryId = libraryId, SearchTerm = "Fellowship" }; + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookEntity book = Assert.Single(result.Value.Data); + Assert.Equal("The Fellowship of the Ring", book.Title); + Assert.Equal(1, result.Value.Count); + } + + [Fact] + public async Task GetPaginatedAsync_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 = new() { CurrentPage = 2, PerPage = 2 }; + LibraryFilterDto filter = new() { LibraryId = libraryId }; + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, 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 GetPaginatedAsync_WhenSortByTitleDescending_ShouldReturnBooksInDescendingOrder() + { + // 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 = new() { CurrentPage = 1, PerPage = 10 }; + LibraryFilterDto filter = new() { LibraryId = libraryId }; + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["Book B", "Book A"], result.Value.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetPaginatedAsync_WhenCalled_ShouldIncludeRelatedEntities() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")]; + book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")]; + book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)]; + book.Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)]; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; + LibraryFilterDto filter = new() { LibraryId = libraryId }; + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookEntity retrievedBook = Assert.Single(result.Value.Data); + Assert.Equal(2, retrievedBook.Tags.Count); + Assert.Equal(2, retrievedBook.Genres.Count); + Assert.Equal(2, retrievedBook.ISBNs.Count); + Assert.Single(retrievedBook.Ratings); + Assert.Equal(4.5M, retrievedBook.Ratings.First().Value); + } } 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 new file mode 100644 index 00000000..8e223f1a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -0,0 +1,233 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetBooksEndpoint _sut; + private readonly GetBooksRequestFixture _getBooksRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetBooksEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedBookResponses() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(bookCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, 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"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksQueryToSender() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + + // 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.SortBy == request.SortBy && + query.SortOrder == request.SortOrder && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(CreatePaginatedResponse(bookCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of books. + /// + /// The number of book responses to include in the data collection. + /// A configured paginated response instance. + private static PaginatedResponse CreatePaginatedResponse(int bookCount) + { + List books = []; + for (int index = 0; index < bookCount; index++) + books.Add(CreateBookResponse()); + + return new PaginatedResponse + { + Data = books, + CurrentPage = 1, + PerPage = 10, + Count = bookCount, + NumberOfPages = bookCount > 0 ? 1 : 0 + }; + } + + /// + /// Creates a minimal valid . + /// + /// A configured book response instance. + private static BookResponse CreateBookResponse() + { + return new BookResponse( + Id: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/books/test.epub", + Metadata: new WrittenContentMetadataDto( + Title: "Test Book", + OriginalTitle: null, + Description: null, + ReleaseInfo: null, + Genres: null, + Tags: null, + Language: null, + OriginalLanguage: null, + Publisher: null, + PageCount: null + ), + Format: null, + Edition: null, + VolumeNumber: null, + Series: null, + ASIN: null, + GoodreadsId: null, + LCCN: null, + OCLCNumber: null, + OpenLibraryId: null, + LibraryThingId: null, + GoogleBooksId: null, + BarnesAndNobleId: null, + AppleBooksId: null, + ISBNs: null, + Contributors: null, + Ratings: null, + MetadataStatus: MetadataStatus.Pending, + LastMetadataUpdateUtc: null, + MetadataProvider: null, + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: null + ); + } +} 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 new file mode 100644 index 00000000..3a2a43c7 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -0,0 +1,190 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetBooksLiteEndpoint _sut; + private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetBooksLiteEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedBookLiteResponses() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(bookCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, 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"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksLiteQueryToSender() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + + // 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.SortBy == request.SortBy && + query.SortOrder == request.SortOrder && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(CreatePaginatedResponse(bookCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of books. + /// + /// The number of book responses to include in the data collection. + /// A configured paginated response instance. + private static PaginatedResponse CreatePaginatedResponse(int bookCount) + { + List books = []; + for (int index = 0; index < bookCount; index++) + books.Add(new BookLiteResponse( + Id: Guid.NewGuid(), + Title: "Test Book", + ReleaseYear: 2001, + CoverPath: null + )); + + return new PaginatedResponse + { + Data = books, + CurrentPage = 1, + PerPage = 10, + Count = bookCount, + NumberOfPages = bookCount > 0 ? 1 : 0 + }; + } +}