diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs new file mode 100644 index 00000000..768de9e8 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.UsersManagement; + +/// +/// Repository entity for the settings of a user. +/// +[DebuggerDisplay("Id: {Id}; UserId: {UserId}")] +public class UserSettingsEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of these user settings. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the user that owns these settings. + /// + public required Guid UserId { get; init; } + + /// + /// Gets or sets whether pagination is enabled for the user, or not. + /// + public bool IsPaginationEnabled { get; set; } + + /// + /// Gets or sets the number of library items displayed per page when pagination is enabled. + /// + public int ItemsPerPage { get; set; } + + /// + /// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// + public bool IgnoreThePrefixForAlphaPicker { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserSettingsRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserSettingsRepository.cs new file mode 100644 index 00000000..be63a6c6 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserSettingsRepository.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Users; + +/// +/// Interface for the repository for user settings. +/// +public interface IUserSettingsRepository : IRepository, + IGetByIdRepositoryAction, + IInsertRepositoryAction, + IUpdateRepositoryAction +{ + /// + /// Gets the settings of the user identified by , if they exist. + /// + /// The Id of the user whose settings are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the of the user, or an error. + Task> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index 9d2b4442..f8717656 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -80,6 +80,11 @@ public interface IUnitOfWork /// IUserRepository UserRepository { get; } + /// + /// Gets the user settings repository. + /// + IUserSettingsRepository UserSettingsRepository { get; } + /// /// Saves all changes made to the database. /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs index 6738c03b..1a61e61c 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs @@ -4,7 +4,6 @@ using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using System; -using System.Linq; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -41,8 +40,8 @@ public static class BookMapping OriginalLanguageCode = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.LanguageCode : null, OriginalLanguageName = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.LanguageName : null, OriginalLanguageNativeName = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.NativeName.Value : null, - Tags = domainEntity.Metadata.Tags.ToRepositoryEntities().ToHashSet(), - Genres = domainEntity.Metadata.Genres.ToRepositoryEntities().ToHashSet(), + Tags = [.. domainEntity.Metadata.Tags.ToRepositoryEntities()], + Genres = [.. domainEntity.Metadata.Genres.ToRepositoryEntities()], Publisher = domainEntity.Metadata.Publisher.HasValue ? domainEntity.Metadata.Publisher.Value : null, PageCount = domainEntity.Metadata.PageCount.HasValue ? domainEntity.Metadata.PageCount.Value : null, Format = domainEntity.Format.HasValue ? domainEntity.Format.Value : null, @@ -57,8 +56,8 @@ public static class BookMapping GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null, BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null, AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null, - ISBNs = domainEntity.ISBNs.ToRepositoryEntities().ToList(), - Ratings = domainEntity.Ratings.ToRepositoryEntities().ToList(), + ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()], + Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], MetadataStatus = domainEntity.MetadataStatus, LastMetadataUpdateUtc = domainEntity.LastMetadataUpdateUtc.HasValue ? domainEntity.LastMetadataUpdateUtc.Value : null, MetadataProvider = domainEntity.MetadataProvider.HasValue ? domainEntity.MetadataProvider.Value : null, diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs new file mode 100644 index 00000000..8eee0bcb --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Contracts.Requests.UsersManagement.Settings; +#endregion + +namespace Lumina.Application.Common.Mapping.UsersManagement.Users; + +/// +/// Extension methods for converting . +/// +public static class UpdateUserSettingsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static UpdateUserSettingsCommand ToCommand(this UpdateUserSettingsRequest request) + { + return new UpdateUserSettingsCommand( + request.IsPaginationEnabled, + request.ItemsPerPage, + request.IgnoreThePrefixForAlphaPicker); + } +} diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs new file mode 100644 index 00000000..a109efca --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.UsersManagement.Users; + +/// +/// Extension methods for converting . +/// +public static class UserSettingsEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this UserSettingsEntity repositoryEntity) + { + return UserSettings.Create( + UserSettingsId.Create(repositoryEntity.Id), + UserId.Create(repositoryEntity.UserId), + repositoryEntity.IsPaginationEnabled, + repositoryEntity.ItemsPerPage, + repositoryEntity.IgnoreThePrefixForAlphaPicker); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + public static UserSettingsResponse ToResponse(this UserSettingsEntity repositoryEntity) + { + return new UserSettingsResponse( + repositoryEntity.UserId, + repositoryEntity.IsPaginationEnabled, + repositoryEntity.ItemsPerPage, + repositoryEntity.IgnoreThePrefixForAlphaPicker); + } +} diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs new file mode 100644 index 00000000..45764c56 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +#endregion + +namespace Lumina.Application.Common.Mapping.UsersManagement.Users; + +/// +/// Extension methods for converting . +/// +public static class UserSettingsMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static UserSettingsEntity ToRepositoryEntity(this UserSettings domainEntity) + { + return new UserSettingsEntity + { + Id = domainEntity.Id.Value, + UserId = domainEntity.UserId.Value, + IsPaginationEnabled = domainEntity.IsPaginationEnabled, + ItemsPerPage = domainEntity.ItemsPerPage, + IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker + }; + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted response. + public static UserSettingsResponse ToResponse(this UserSettings domainEntity) + { + return new UserSettingsResponse( + domainEntity.UserId.Value, + domainEntity.IsPaginationEnabled, + domainEntity.ItemsPerPage, + domainEntity.IgnoreThePrefixForAlphaPicker); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs new file mode 100644 index 00000000..a7f081cf --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; + +/// +/// Command for updating the settings of the current user. +/// +/// Whether pagination is enabled for the user, or not. +/// The number of library items displayed per page when pagination is enabled. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. +public record UpdateUserSettingsCommand( + bool IsPaginationEnabled, + int ItemsPerPage, + bool IgnoreThePrefixForAlphaPicker +) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs new file mode 100644 index 00000000..4070ab3a --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; + +/// +/// Handler for the command to update the settings of the current user. +/// +public class UpdateUserSettingsCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public UpdateUserSettingsCommandHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to update the settings of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful update, or an error message. + /// + public async Task> HandleAsync(UpdateUserSettingsCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // an authenticated request must always carry a user identity + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return Errors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // get the existing settings of the current user, if any + Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + + if (getSettingsResult.Value is null) + { + // create the settings of the current user, since they are not stored yet + Result createSettingsResult = UserSettings.Create( + UserId.Create(userId), + command.IsPaginationEnabled, + command.ItemsPerPage, + command.IgnoreThePrefixForAlphaPicker); + if (createSettingsResult.IsFailure) + return createSettingsResult.Errors; + + Result insertResult = await _unitOfWork.UserSettingsRepository.InsertAsync(createSettingsResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + return insertResult.Errors; + } + else + { + // update the stored settings of the current user + Result toDomainEntityResult = getSettingsResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + + Result updateSettingsResult = toDomainEntityResult.Value.UpdateSettings( + command.IsPaginationEnabled, + command.ItemsPerPage, + command.IgnoreThePrefixForAlphaPicker); + if (updateSettingsResult.IsFailure) + return updateSettingsResult.Errors; + + Result updateResult = await _unitOfWork.UserSettingsRepository.UpdateAsync(toDomainEntityResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs new file mode 100644 index 00000000..ba8ff630 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateUserSettingsCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateUserSettingsCommandValidator() + { + RuleFor(command => command.ItemsPerPage) + .GreaterThan(0) + .WithError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQuery.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQuery.cs new file mode 100644 index 00000000..5982664d --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQuery.cs @@ -0,0 +1,10 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; + +/// +/// Query for getting the settings of the current user. +/// +public record GetUserSettingsQuery : IQuery; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs new file mode 100644 index 00000000..0d40b9df --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; + +/// +/// Handler for the query to get the settings of the current user. +/// +public class GetUserSettingsQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetUserSettingsQueryHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get the settings of the current user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully retrieved , or an error message. + /// + public async Task> HandleAsync(GetUserSettingsQuery query, CancellationToken cancellationToken) + { + // an authenticated request must always carry a user identity + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return Errors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // get the settings of the current user from the repository + Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + + // when no settings are stored for the current user yet, return the default settings + if (getSettingsResult.Value is null) + { + Result defaultSettingsResult = UserSettings.Create(); + if (defaultSettingsResult.IsFailure) + return defaultSettingsResult.Errors; + return defaultSettingsResult.Value.ToResponse(); + } + + return getSettingsResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs new file mode 100644 index 00000000..eb76b7ad --- /dev/null +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.UsersManagement.Settings; + +/// +/// Represents a request to update the settings of the current user. +/// +/// Whether pagination is enabled for the user, or not. Required. +/// The number of library items displayed per page when pagination is enabled. Required. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required. +[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] +public sealed record UpdateUserSettingsRequest( + bool IsPaginationEnabled, + int ItemsPerPage, + bool IgnoreThePrefixForAlphaPicker +); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs new file mode 100644 index 00000000..2e29dd70 --- /dev/null +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.UsersManagement.Settings; + +/// +/// Represents the settings of a user. +/// +/// The unique identifier of the user that owns these settings. +/// Whether pagination is enabled for the user, or not. +/// The number of library items displayed per page when pagination is enabled. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. +[DebuggerDisplay("UserId: {UserId}")] +public sealed record UserSettingsResponse( + Guid UserId, + bool IsPaginationEnabled, + int ItemsPerPage, + bool IgnoreThePrefixForAlphaPicker +); diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs new file mode 100644 index 00000000..a24022a1 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class UserSettingsConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("UserSettings"); + builder.HasKey(settings => settings.Id); + builder.Property(settings => settings.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + + // one user with one set of settings + builder.HasOne() + .WithOne() + .HasForeignKey(settings => settings.UserId) + .IsRequired() + .OnDelete(DeleteBehavior.Cascade); + + builder.Property(settings => settings.UserId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(settings => settings.IsPaginationEnabled) + .IsRequired() + .HasColumnOrder(2); + + builder.Property(settings => settings.ItemsPerPage) + .IsRequired() + .HasColumnOrder(3); + + builder.Property(settings => settings.IgnoreThePrefixForAlphaPicker) + .IsRequired() + .HasColumnOrder(4); + + // audit + builder.Property(settings => settings.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(settings => settings.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(settings => settings.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(settings => settings.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + // one user can have at most one set of settings + builder.HasIndex(settings => settings.UserId) + .IsUnique(); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260816142229_AddsUserSettingsTable.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260816142229_AddsUserSettingsTable.Designer.cs new file mode 100644 index 00000000..26f7c642 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260816142229_AddsUserSettingsTable.Designer.cs @@ -0,0 +1,1214 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260816142229_AddsUserSettingsTable")] + partial class AddsUserSettingsTable + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("DownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260816142229_AddsUserSettingsTable.cs b/src/Lumina.DataAccess/Common/Migrations/20260816142229_AddsUserSettingsTable.cs new file mode 100644 index 00000000..466e9817 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260816142229_AddsUserSettingsTable.cs @@ -0,0 +1,53 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsUserSettingsTable : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "UserSettings", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + IsPaginationEnabled = table.Column(type: "INTEGER", nullable: false), + ItemsPerPage = table.Column(type: "INTEGER", nullable: false), + IgnoreThePrefixForAlphaPicker = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserSettings", x => x.Id); + table.ForeignKey( + name: "FK_UserSettings_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserSettings_UserId", + table: "UserSettings", + column: "UserId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserSettings"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index ad67b50f..fc0c29c7 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -862,6 +862,52 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Users", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + modelBuilder.Entity("BookGenres", b => { b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) @@ -1116,6 +1162,15 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("Ratings"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => { b.Navigation("RolePermissions"); diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs new file mode 100644 index 00000000..03094365 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Users; + +/// +/// Repository for user settings. +/// +internal sealed class UserSettingsRepository : IUserSettingsRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public UserSettingsRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds the settings of a user. + /// + /// The user settings to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(UserSettingsEntity data, CancellationToken cancellationToken) + { + bool settingsExists = await _luminaDbContext.UserSettings.AnyAsync(settings => settings.UserId == data.UserId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (settingsExists) + return Errors.UserSettings.UserSettingsAlreadyExists; + + _luminaDbContext.UserSettings.Add(data); + return Result.Created; + } + + /// + /// Gets the settings identified by , if they exist. + /// + /// The Id of the user settings to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + { + return await _luminaDbContext.UserSettings + .FirstOrDefaultAsync(settings => settings.Id == id, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets the settings of the user identified by , if they exist. + /// + /// The Id of the user whose settings are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the of the user, or an error. + public async Task> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken) + { + return await _luminaDbContext.UserSettings + .FirstOrDefaultAsync(settings => settings.UserId == userId, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Updates the settings of a user. + /// + /// The user settings to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(UserSettingsEntity data, CancellationToken cancellationToken) + { + UserSettingsEntity? foundSettings = await _luminaDbContext.UserSettings + .FirstOrDefaultAsync(settings => settings.Id == data.Id, cancellationToken) + .ConfigureAwait(false); + if (foundSettings is null) + return Errors.UserSettings.UserSettingsNotFound; + + _luminaDbContext.Entry(foundSettings).CurrentValues.SetValues(data); + return Result.Updated; + } +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 2b902024..1de516e3 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -18,6 +18,7 @@ public class LuminaDbContext : DbContext { public virtual DbSet Books { get; set; } = null!; public virtual DbSet Users { get; set; } = null!; + public virtual DbSet UserSettings { get; set; } = null!; public virtual DbSet Libraries { get; set; } = null!; public virtual DbSet LibraryScans { get; set; } = null!; public virtual DbSet LibraryScanResults { get; set; } = null!; diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index 1af080f0..4fd25021 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -39,6 +39,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository; private IPluginRepository? _pluginRepository; private IUserRepository? _userRepository; + private IUserSettingsRepository? _userSettingsRepository; /// /// Gets the permission repository. @@ -196,6 +197,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + /// + /// Gets the user settings repository. + /// + public IUserSettingsRepository UserSettingsRepository + { + get + { + _userSettingsRepository ??= new UserSettingsRepository(_luminaDbContext); + return _userSettingsRepository; + } + } + /// /// Initializes a new instance of the class. /// diff --git a/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs b/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs new file mode 100644 index 00000000..4778b3f2 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// User settings error types. +/// +public static partial class Errors +{ + public static class UserSettings + { + public static Error UserSettingsAlreadyExists => Error.Conflict(description: nameof(UserSettingsAlreadyExists)); + public static Error UserSettingsNotFound => Error.NotFound(description: nameof(UserSettingsNotFound)); + public static Error ItemsPerPageMustBeGreaterThanZero => Error.Validation(description: nameof(ItemsPerPageMustBeGreaterThanZero)); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs new file mode 100644 index 00000000..46f5d0df --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs @@ -0,0 +1,158 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; + +/// +/// Aggregate root for the settings of a user. +/// +[DebuggerDisplay("Id: {Id}; UserId: {UserId}")] +public class UserSettings : AggregateRoot +{ + private const bool DEFAULT_IS_PAGINATION_ENABLED = true; + private const int DEFAULT_ITEMS_PER_PAGE = 48; + private const bool DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER = false; + + /// + /// Gets the object representing the unique identifier of the user that owns these settings. + /// + public UserId UserId { get; private set; } + + /// + /// Gets whether pagination is enabled for the user, or not. + /// + public bool IsPaginationEnabled { get; private set; } + + /// + /// Gets the number of library items displayed per page when pagination is enabled. + /// + public int ItemsPerPage { get; private set; } + + /// + /// Gets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// + public bool IgnoreThePrefixForAlphaPicker { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of these settings. + /// The object representing the unique identifier of the user that owns these settings. + /// Whether pagination is enabled for the user, or not. + /// The number of library items displayed per page when pagination is enabled. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + private UserSettings( + UserSettingsId id, + UserId userId, + bool isPaginationEnabled, + int itemsPerPage, + bool ignoreThePrefixForAlphaPicker) : base(id) + { + UserId = userId; + IsPaginationEnabled = isPaginationEnabled; + ItemsPerPage = itemsPerPage; + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + } + + /// + /// Creates a new instance of the class, with the default settings. + /// + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create() + { + return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER); + } + + /// + /// Creates a new instance of the class, with the default settings. + /// + /// The object representing the unique identifier of the user that owns these settings. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(UserId userId) + { + return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER); + } + + /// + /// Creates a new instance of the class. + /// + /// The object representing the unique identifier of the user that owns these settings. + /// Whether pagination is enabled for the user, or not. + /// The number of library items displayed per page when pagination is enabled. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + UserId userId, + bool isPaginationEnabled, + int itemsPerPage, + bool ignoreThePrefixForAlphaPicker) + { + if (itemsPerPage <= 0) + return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; + + return new UserSettings( + UserSettingsId.CreateUnique(), + userId, + isPaginationEnabled, + itemsPerPage, + ignoreThePrefixForAlphaPicker); + } + + /// + /// Creates a new instance of the class, with a pre-existing . + /// + /// The object representing the unique identifier of these settings. + /// The object representing the unique identifier of the user that owns these settings. + /// Whether pagination is enabled for the user, or not. + /// The number of library items displayed per page when pagination is enabled. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + UserSettingsId id, + UserId userId, + bool isPaginationEnabled, + int itemsPerPage, + bool ignoreThePrefixForAlphaPicker) + { + if (itemsPerPage <= 0) + return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; + + return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, ignoreThePrefixForAlphaPicker); + } + + /// + /// Updates the settings of the user. + /// + /// Whether pagination is enabled for the user, or not. + /// The number of library items displayed per page when pagination is enabled. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// An representing either a successful update, or an error. + public Result UpdateSettings( + bool isPaginationEnabled, + int itemsPerPage, + bool ignoreThePrefixForAlphaPicker) + { + if (itemsPerPage <= 0) + return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; + + IsPaginationEnabled = isPaginationEnabled; + ItemsPerPage = itemsPerPage; + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + return Result.Updated; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsId.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsId.cs new file mode 100644 index 00000000..0be71a4a --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; + +/// +/// Value Object for the Id of a set of user settings. +/// +[DebuggerDisplay("{Value}")] +public sealed class UserSettingsId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private UserSettingsId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static UserSettingsId CreateUnique() + { + return new UserSettingsId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static UserSettingsId Create(Guid value) + { + return new UserSettingsId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs index 44c772ed..2dfccb20 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; using System; using System.Collections.Generic; @@ -117,7 +116,7 @@ public class AuthorizationService : IAuthorizationService .ToHashSet(); // combine all permissions - HashSet allPermissions = rolePermissions is not null ? directPermissions.Union(rolePermissions).ToHashSet() : directPermissions; + HashSet allPermissions = rolePermissions is not null ? [.. directPermissions.Union(rolePermissions)] : directPermissions; return new UserAuthorizationEntity { diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs index c06527fd..1be6e11b 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs @@ -11,5 +11,7 @@ public static partial class ApiRoutes public static class Users { public const string GET_USER_BY_ID = "/users/{id}"; + public const string GET_USER_SETTINGS = "/users/me/settings"; // uses "me" because it is always for the currently authenticated user + public const string UPDATE_USER_SETTINGS = "/users/me/settings"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpoint.cs new file mode 100644 index 00000000..ccb607ce --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +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.UsersManagement.Settings.GetUserSettings; + +/// +/// API endpoint for the /users/me/settings route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetUserSettingsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getUserSettingsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get user settings queries. + public GetUserSettingsEndpoint(IQueryHandler> getUserSettingsQueryHandler) + { + _getUserSettingsQueryHandler = getUserSettingsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Users.GET_USER_SETTINGS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the settings of the current user. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + Result result = await _getUserSettingsQueryHandler.HandleAsync(new GetUserSettingsQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs new file mode 100644 index 00000000..a8446d03 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetUserSettings; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserSettingsEndpointSummary() + { + Summary = "Retrieves the settings of the current user."; + Description = "Retrieves the settings of the current user. When no settings are stored for the user yet, the default settings are returned."; + + Response(200, "The settings of the current user are returned.", + example: new UserSettingsResponse( + UserId: Guid.NewGuid(), + IsPaginationEnabled: true, + ItemsPerPage: 48, + IgnoreThePrefixForAlphaPicker: false + )); + + 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/users/me/settings" + }, + 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/users/me/settings" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/settings" + } + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs new file mode 100644 index 00000000..3f66c7bd --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +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.UsersManagement.Settings.UpdateUserSettings; + +/// +/// API endpoint for the /users/me/settings route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class UpdateUserSettingsEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updateUserSettingsCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update user settings commands. + public UpdateUserSettingsEndpoint(ICommandHandler> updateUserSettingsCommandHandler) + { + _updateUserSettingsCommandHandler = updateUserSettingsCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Users.UPDATE_USER_SETTINGS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the settings of the current user. + /// + /// The request containing the new settings of the current user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateUserSettingsRequest request, CancellationToken cancellationToken) + { + Result result = await _updateUserSettingsCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs new file mode 100644 index 00000000..d2916198 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateUserSettingsEndpointSummary() + { + Summary = "Updates the settings of the current user."; + Description = "Updates the settings of the current user. When no settings are stored for the user yet, they are created with the provided values."; + + ExampleRequest = new UpdateUserSettingsRequest( + IsPaginationEnabled: true, + ItemsPerPage: 48, + IgnoreThePrefixForAlphaPicker: false + ); + + Response(200, "The settings of the current user were successfully updated."); + + 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/users/me/settings" + }, + 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/users/me/settings" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/settings" + } + } + ); + + 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/users/me/settings", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ItemsPerPageMustBeGreaterThanZero" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserSettingsModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserSettingsModel.cs new file mode 100644 index 00000000..e72cc0d8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserSettingsModel.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the settings of a user. +/// +[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] +public class UserSettingsModel +{ + /// + /// Gets or sets the unique identifier of the user that owns these settings. + /// + public Guid? UserId { get; set; } + + /// + /// Gets or sets whether pagination is enabled for the user, or not. + /// + public bool IsPaginationEnabled { get; set; } = true; + + /// + /// Gets or sets the number of library items displayed per page when pagination is enabled. + /// + public int ItemsPerPage { get; set; } = 48; + + /// + /// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// + public bool IgnoreThePrefixForAlphaPicker { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Controllers/Tools/SettingsController.cs b/src/Lumina.Presentation.Web/Controllers/Tools/SettingsController.cs new file mode 100644 index 00000000..c61b2196 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/Tools/SettingsController.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Models.Common; +using Lumina.Presentation.Web.Common.Models.UsersManagement; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers.Tools; + +/// +/// Controller for the settings of the current user. +/// +[Authorize] +[Route("{culture}/tools/settings")] +public class SettingsController : Controller +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public SettingsController(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Displays the view for editing the settings of the current user. + /// + [HttpGet("")] + public IActionResult Index() + { + UserSettingsModel settings = new(); + return View("/Views/Tools/Settings.cshtml", settings); + } + + /// + /// Gets the settings of the current user. + /// + /// Cancellation token that can be used to stop the execution. + [HttpGet("api-get-user-settings")] + public async Task GetUserSettings(CancellationToken cancellationToken = default) + { + UserSettingsModel response = await _apiHttpClient.GetAsync("users/me/settings", cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = response }); + } + + /// + /// Updates the settings of the current user. + /// + /// The model containing the new settings of the current user. + /// Cancellation token that can be used to stop the execution. + [ValidateAntiForgeryToken] + [HttpPost("api-update-user-settings")] + public async Task UpdateUserSettings([FromBody] UserSettingsModel data, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync("users/me/settings", data, cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = new { isUpdated = true } }); + } +} diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx index 2ec1dc87..03c1b8ff 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx @@ -177,8 +177,8 @@ Musik - - Optionen + + Einstellungen Profil diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx index 6e8d0e44..97405612 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx @@ -177,8 +177,8 @@ Music - - Options + + Settings Profile diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx index b43fcde1..f4a8dc79 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx @@ -177,8 +177,8 @@ Música - - Opciones + + Configuración Perfil diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx index d6353ea2..7b2508f7 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx @@ -177,8 +177,8 @@ Musique - - Options + + Paramètres Profil diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx index b69913b9..da66d075 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx @@ -177,8 +177,8 @@ Musica - - Opzioni + + Impostazioni Profilo diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx index cd0bf62b..aa2febca 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx @@ -177,8 +177,8 @@ 音楽 - - オプション + + 設定 プロフィール diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx index 6e8d0e44..97405612 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx @@ -177,8 +177,8 @@ Music - - Options + + Settings Profile diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx index d0a5ffdb..37ac6ac7 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx @@ -177,8 +177,8 @@ Muzică - - Opțiuni + + Setări Profil diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx index 2d527db2..07c3cce4 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx @@ -177,7 +177,7 @@ Музыка - + Настройки diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx index d6ef6898..f9ca0bee 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx @@ -177,8 +177,8 @@ 音乐 - - 选项 + + 设置 个人资料 diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.de-DE.resx new file mode 100644 index 00000000..7f312406 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.de-DE.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Einstellungen + + + Seitennummerierung aktivieren + + + Elemente pro Seite + + + "The"-Präfix für die Alpha-Auswahl ignorieren + + + Speichern + + + Einstellungen gespeichert + + + Steuert, ob die Bibliothekselemente in Seiten aufgeteilt werden. + + + Die Anzahl der Bibliothekselemente, die bei aktivierter Seitennummerierung auf jeder Seite angezeigt werden. + + + Wenn aktiviert, werden Bibliothekselemente, deren Titel mit "The" beginnt, in der Alpha-Auswahl unter dem ersten Buchstaben des folgenden Wortes gruppiert, z. B. wird "The Rasmus" unter R aufgeführt. + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.en-US.resx new file mode 100644 index 00000000..d7ecb8c2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.en-US.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Settings + + + Enable pagination + + + Items per page + + + Ignore "The" prefix for the alpha picker + + + Save + + + Settings saved + + + Controls whether library items are split into pages. + + + The number of library items displayed on each page when pagination is enabled. + + + When enabled, library items whose title begins with "The" are grouped under the first letter of the following word in the alpha picker, e.g. "The Rasmus" is listed under R. + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.es-ES.resx new file mode 100644 index 00000000..46197a4f --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.es-ES.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Configuración + + + Habilitar paginación + + + Elementos por página + + + Ignorar el prefijo "The" en el selector alfabético + + + Guardar + + + Configuración guardada + + + Controla si los elementos de la biblioteca se dividen en páginas. + + + El número de elementos de la biblioteca mostrados en cada página cuando la paginación está habilitada. + + + Cuando está habilitado, los elementos de la biblioteca cuyo título comienza con "The" se agrupan bajo la primera letra de la palabra siguiente en el selector alfabético, por ejemplo, "The Rasmus" se lista bajo R. + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.fr-FR.resx new file mode 100644 index 00000000..0d086bdd --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.fr-FR.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Paramètres + + + Activer la pagination + + + Éléments par page + + + Ignorer le préfixe "The" dans le sélecteur alphabétique + + + Enregistrer + + + Paramètres enregistrés + + + Contrôle si les éléments de la bibliothèque sont répartis en pages. + + + Le nombre d'éléments de la bibliothèque affichés sur chaque page lorsque la pagination est activée. + + + Lorsque cette option est activée, les éléments de la bibliothèque dont le titre commence par "The" sont regroupés sous la première lettre du mot suivant dans le sélecteur alphabétique, par exemple "The Rasmus" est répertorié sous R. + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.it-IT.resx new file mode 100644 index 00000000..f88da291 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.it-IT.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Impostazioni + + + Abilita paginazione + + + Elementi per pagina + + + Ignora il prefisso "The" nel selettore alfabetico + + + Salva + + + Impostazioni salvate + + + Controlla se gli elementi della libreria vengono suddivisi in pagine. + + + Il numero di elementi della libreria visualizzati su ogni pagina quando la paginazione è abilitata. + + + Se abilitato, gli elementi della libreria il cui titolo inizia con "The" vengono raggruppati sotto la prima lettera della parola successiva nel selettore alfabetico, ad esempio "The Rasmus" è elencato sotto R. + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ja-JP.resx new file mode 100644 index 00000000..78c7e46f --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ja-JP.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 設定 + + + ページネーションを有効にする + + + ページあたりの項目数 + + + アルファピッカーで「The」の接頭辞を無視する + + + 保存 + + + 設定を保存しました + + + ライブラリの項目をページに分割するかどうかを制御します。 + + + ページネーションが有効な場合に各ページに表示されるライブラリの項目数。 + + + 有効にすると、タイトルが「The」で始まるライブラリの項目は、アルファピッカーで次の単語の最初の文字の下にグループ化されます。たとえば「The Rasmus」は「R」の下に表示されます。 + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.resx new file mode 100644 index 00000000..d7ecb8c2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Settings + + + Enable pagination + + + Items per page + + + Ignore "The" prefix for the alpha picker + + + Save + + + Settings saved + + + Controls whether library items are split into pages. + + + The number of library items displayed on each page when pagination is enabled. + + + When enabled, library items whose title begins with "The" are grouped under the first letter of the following word in the alpha picker, e.g. "The Rasmus" is listed under R. + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ro-RO.resx new file mode 100644 index 00000000..add6888f --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ro-RO.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Setări + + + Activați paginarea + + + Elemente pe pagină + + + Ignorați prefixul "The" pentru selectorul alfabetic + + + Salvați + + + Setările au fost salvate + + + Controlează dacă elementele bibliotecii sunt împărțite în pagini. + + + Numărul de elemente ale bibliotecii afișate pe fiecare pagină atunci când paginarea este activată. + + + Când este activată, elementele bibliotecii al căror titlu începe cu "The" sunt grupate sub prima literă a cuvântului următor în selectorul alfabetic, de exemplu "The Rasmus" este listat sub R. + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ru-RU.resx new file mode 100644 index 00000000..5657d5a6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ru-RU.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Настройки + + + Включить разбиение на страницы + + + Элементов на странице + + + Игнорировать префикс "The" в алфавитном указателе + + + Сохранить + + + Настройки сохранены + + + Управляет разделением элементов библиотеки на страницы. + + + Количество элементов библиотеки, отображаемых на каждой странице при включенной разбивке на страницы. + + + При включении элементы библиотеки, название которых начинается с "The", группируются в алфавитном указателе под первой буквой следующего слова, например "The Rasmus" отображается под буквой R. + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.zh-CN.resx new file mode 100644 index 00000000..00301a1b --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.zh-CN.resx @@ -0,0 +1,42 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 设置 + + + 启用分页 + + + 每页项目数 + + + 在字母选择器中忽略“The”前缀 + + + 保存 + + + 设置已保存 + + + 控制是否将库项目分页显示。 + + + 启用分页时每页显示的库项目数。 + + + 启用后,标题以"The"开头的库项目将在字母选择器中按后一个词的首字母分组,例如"The Rasmus"会列在R下。 + + diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml index c03f5074..e7f6b6e1 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml @@ -106,7 +106,7 @@ @_localizer["Tools"] }
@@ -211,7 +211,7 @@ @if (User?.Identity?.IsAuthenticated == true) { -
  • @_localizer["Options"]
  • +
  • @_localizer["Settings"]
  • } diff --git a/src/Lumina.Presentation.Web/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Views/Tools/Settings.cshtml new file mode 100644 index 00000000..09304622 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Tools/Settings.cshtml @@ -0,0 +1,152 @@ +@* +/tools/settings +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization + +@{ + // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); +} + +@inject IUrlService _urlService +@inject IViewLocalizer _localizer + +@model UserSettingsModel + +
    +
    +
    +
    +
    + @Html.AntiForgeryToken() +
    +

    + @_localizer["Settings"] +

    +
    +
    + +
    +
    + : +
    +
    + +
    + @_localizer["DescriptionEnablePagination"] +
    + +
    +
    + + *: +
    +
    + +
    + @_localizer["DescriptionItemsPerPage"] +
    + +
    +
    + : +
    +
    + +
    + @_localizer["DescriptionIgnoreThePrefixForAlphaPicker"] +
    +
    + +
    +
    +
    +
    +
    +@section Scripts { + +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs new file mode 100644 index 00000000..d11a1fdc --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsEntityFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user settings. + /// Optional. The Id of the user that owns these settings. + /// Optional. Whether pagination is enabled for the user, or not. + /// Optional. The number of library items displayed per page when pagination is enabled. + /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. + /// The created user settings entity. + public UserSettingsEntity Create( + Guid? id = null, + Guid? userId = null, + bool? isPaginationEnabled = null, + int? itemsPerPage = null, + bool? ignoreThePrefixForAlphaPicker = null) + { + return new Faker() + .CustomInstantiator(f => new UserSettingsEntity + { + Id = id ?? Guid.NewGuid(), + UserId = userId ?? Guid.NewGuid(), + IsPaginationEnabled = isPaginationEnabled ?? f.Random.Bool(), + ItemsPerPage = itemsPerPage ?? f.Random.Int(1, 100), + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? f.Random.Bool() + }) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs new file mode 100644 index 00000000..7fc9e855 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdateUserSettings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsCommandFixture +{ + /// + /// Creates a random valid command to update the settings of the current user. + /// + /// Optional. Whether pagination is enabled for the user, or not. + /// Optional. The number of library items displayed per page when pagination is enabled. + /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. + /// The created command. + public UpdateUserSettingsCommand Create( + bool? isPaginationEnabled = null, + int? itemsPerPage = null, + bool? ignoreThePrefixForAlphaPicker = null) + { + return new Faker() + .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default)) + .RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool()) + .RuleFor(x => x.ItemsPerPage, f => itemsPerPage ?? f.Random.Int(1, 100)) + .RuleFor(x => x.IgnoreThePrefixForAlphaPicker, f => ignoreThePrefixForAlphaPicker ?? f.Random.Bool()) + .Generate(); + } + + /// + /// 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/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..50301fd3 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.GetUserSettings; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests : 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 GetUserSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetUserSettings_WhenSettingsExist_ShouldReturnStoredSettings() + { + // Arrange + UserSettingsEntity storedSettings = await CreateTestUserSettings(); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + UserSettingsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + Assert.NotNull(result); + Assert.Equal(storedSettings.UserId, result!.UserId); + Assert.Equal(storedSettings.IsPaginationEnabled, result.IsPaginationEnabled); + Assert.Equal(storedSettings.ItemsPerPage, result.ItemsPerPage); + Assert.Equal(storedSettings.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public async Task GetUserSettings_WhenSettingsDoNotExist_ShouldReturnDefaultSettings() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + UserSettingsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + Assert.NotNull(result); + Assert.True(result!.IsPaginationEnabled); + Assert.Equal(48, result.ItemsPerPage); + Assert.False(result.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public async Task GetUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/users/me/settings"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + private async Task CreateTestUserSettings() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id; + UserSettingsEntity settings = new() + { + Id = Guid.NewGuid(), + UserId = userId, + IsPaginationEnabled = false, + ItemsPerPage = 24, + IgnoreThePrefixForAlphaPicker = true + }; + + dbContext.UserSettings.Add(settings); + await dbContext.SaveChangesAsync(); + return settings; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..34faea2e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +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.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests : 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 UpdateUserSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdateUserSettings_WhenCalledWithValidRequest_ShouldUpdateSettings() + { + // Arrange + UpdateUserSettingsRequest request = new( + IsPaginationEnabled: false, + ItemsPerPage: 24, + IgnoreThePrefixForAlphaPicker: true + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id; + UserSettingsEntity? storedSettings = await dbContext.UserSettings.FirstOrDefaultAsync(settings => settings.UserId == userId); + Assert.NotNull(storedSettings); + Assert.False(storedSettings.IsPaginationEnabled); + Assert.Equal(24, storedSettings.ItemsPerPage); + Assert.True(storedSettings.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public async Task UpdateUserSettings_WhenItemsPerPageIsNotPositive_ShouldReturnValidationError() + { + // Arrange + UpdateUserSettingsRequest request = new( + IsPaginationEnabled: true, + ItemsPerPage: 0, + IgnoreThePrefixForAlphaPicker: false + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/users/me/settings", problemDetails["instance"].GetString()); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains("ItemsPerPageMustBeGreaterThanZero", errors["General.Validation"]); + } + + [Fact] + public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + UpdateUserSettingsRequest request = new( + IsPaginationEnabled: true, + ItemsPerPage: 48, + IgnoreThePrefixForAlphaPicker: false + ); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync("/api/v1/users/me/settings", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..9baeba1c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.GetUserSettings; + +/// +/// Contains security tests for the /users/me/settings route. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests : 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 GetUserSettingsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings"); + + // 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/users/me/settings", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetUserSettings_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync("/api/v1/users/me/settings"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// A task representing the asynchronous operation. + 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); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..73537ded --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,150 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; + +/// +/// Contains security tests for the /users/me/settings route. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests : 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 UpdateUserSettingsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + UpdateUserSettingsRequest request = new( + IsPaginationEnabled: true, + ItemsPerPage: 48, + IgnoreThePrefixForAlphaPicker: false + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request); + + // 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/users/me/settings", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task UpdateUserSettings_WhenItemsPerPageIsAtIntMaxValue_ShouldNotCrash() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = new( + IsPaginationEnabled: true, + ItemsPerPage: int.MaxValue, + IgnoreThePrefixForAlphaPicker: false + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task UpdateUserSettings_WhenItemsPerPageIsAtIntMinValue_ShouldReturnValidationErrorWithoutCrashing() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = new( + IsPaginationEnabled: true, + ItemsPerPage: int.MinValue, + IgnoreThePrefixForAlphaPicker: false + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// A task representing the asynchronous operation. + 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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs new file mode 100644 index 00000000..f33a2666 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs @@ -0,0 +1,169 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Commands.UpdateUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly IValidator _mockValidator; + private readonly UpdateUserSettingsCommandHandler _sut; + private readonly UpdateUserSettingsCommandFixture _updateUserSettingsCommandFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateUserSettingsCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + _mockCurrentUserService.UserId.Returns(_userId); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) + .Returns([]); + + _sut = new UpdateUserSettingsCommandHandler(_mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenSettingsDoNotExist_ShouldInsertSettingsAndReturnUpdated() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + _mockUserSettingsRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockUserSettingsRepository.Received(1).InsertAsync( + Arg.Is(settings => + settings.UserId == _userId && + settings.IsPaginationEnabled == command.IsPaginationEnabled && + settings.ItemsPerPage == command.ItemsPerPage && + settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker), + Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSettingsExist_ShouldUpdateSettingsAndReturnUpdated() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(); + UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(existingSettings)); + _mockUserSettingsRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockUserSettingsRepository.Received(1).UpdateAsync( + Arg.Is(settings => + settings.UserId == _userId && + settings.IsPaginationEnabled == command.IsPaginationEnabled && + settings.ItemsPerPage == command.ItemsPerPage && + settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker), + Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); + await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotPersist() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByUserIdReturnsError_ShouldReturnError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to retrieve user settings"); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidatorTests.cs new file mode 100644 index 00000000..4466be33 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Commands.UpdateUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsCommandValidatorTests +{ + private readonly UpdateUserSettingsCommandValidator _validator = new(); + private readonly UpdateUserSettingsCommandFixture _updateUserSettingsCommandFixture = new(); + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(-100)] + public void Validate_WhenItemsPerPageIsNotPositive_ShouldHaveValidationError(int itemsPerPage) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(itemsPerPage: itemsPerPage); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero); + } + + [Theory] + [InlineData(1)] + [InlineData(48)] + [InlineData(1000000)] + public void Validate_WhenItemsPerPageIsPositive_ShouldNotHaveValidationError(int itemsPerPage) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(itemsPerPage: itemsPerPage); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs new file mode 100644 index 00000000..ce16f758 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Queries.GetUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly GetUserSettingsQueryHandler _sut; + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public GetUserSettingsQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + _mockCurrentUserService.UserId.Returns(_userId); + + _sut = new GetUserSettingsQueryHandler(_mockCurrentUserService, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenSettingsExist_ShouldReturnStoredSettings() + { + // Arrange + GetUserSettingsQuery query = new(); + UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: _userId); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(storedSettings)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(storedSettings.UserId, result.Value.UserId); + Assert.Equal(storedSettings.IsPaginationEnabled, result.Value.IsPaginationEnabled); + Assert.Equal(storedSettings.ItemsPerPage, result.Value.ItemsPerPage); + Assert.Equal(storedSettings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnDefaultSettings() + { + // Arrange + GetUserSettingsQuery query = new(); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotEqual(Guid.Empty, result.Value.UserId); + Assert.True(result.Value.IsPaginationEnabled); + Assert.Equal(48, result.Value.ItemsPerPage); + Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + GetUserSettingsQuery query = new(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); + await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError() + { + // Arrange + GetUserSettingsQuery query = new(); + Error error = Error.Failure("Database.Error", "Failed to retrieve user settings"); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs new file mode 100644 index 00000000..cdb0aca5 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs @@ -0,0 +1,179 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.Repositories.Users; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly UserSettingsRepository _sut; + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UserSettingsRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new UserSettingsRepository(_mockContext); + } + + [Fact] + public async Task InsertAsync_WhenSettingsDoNotExist_ShouldAddSettingsToContextAndReturnCreated() + { + // Arrange + UserSettingsEntity settings = _userSettingsEntityFixture.Create(); + + // Act + Result result = await _sut.InsertAsync(settings, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedSettings = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == settings.Id); + Assert.NotNull(addedSettings); + Assert.Equal(settings.UserId, addedSettings.Entity.UserId); + } + + [Fact] + public async Task InsertAsync_WhenSettingsForUserAlreadyExist_ShouldReturnError() + { + // Arrange + UserSettingsEntity settings = _userSettingsEntityFixture.Create(); + _mockContext.UserSettings.Add(settings); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.InsertAsync(settings, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.UserSettings.UserSettingsAlreadyExists, result.FirstError); + Assert.Single(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetByIdAsync_WhenSettingsExist_ShouldReturnSettings() + { + // Arrange + UserSettingsEntity settings = _userSettingsEntityFixture.Create(); + _mockContext.UserSettings.Add(settings); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(settings.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(settings.Id, result.Value.Id); + Assert.Equal(settings.UserId, result.Value.UserId); + } + + [Fact] + public async Task GetByIdAsync_WhenSettingsDoNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByUserIdAsync_WhenSettingsExist_ShouldReturnSettings() + { + // Arrange + UserSettingsEntity settings = _userSettingsEntityFixture.Create(); + _mockContext.UserSettings.Add(settings); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByUserIdAsync(settings.UserId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(settings.Id, result.Value.Id); + Assert.Equal(settings.UserId, result.Value.UserId); + Assert.Equal(settings.IsPaginationEnabled, result.Value.IsPaginationEnabled); + Assert.Equal(settings.ItemsPerPage, result.Value.ItemsPerPage); + Assert.Equal(settings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public async Task GetByUserIdAsync_WhenSettingsDoNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByUserIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task UpdateAsync_WhenSettingsExist_ShouldUpdateSettingsAndReturnUpdated() + { + // Arrange + UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(); + _mockContext.UserSettings.Add(existingSettings); + await _mockContext.SaveChangesAsync(); + + UserSettingsEntity updatedSettings = _userSettingsEntityFixture.Create( + id: existingSettings.Id, + userId: existingSettings.UserId, + isPaginationEnabled: false, + itemsPerPage: 12, + ignoreThePrefixForAlphaPicker: true); + + // Act + Result result = await _sut.UpdateAsync(updatedSettings, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + UserSettingsEntity? modifiedSettings = await _mockContext.UserSettings.FirstOrDefaultAsync(settings => settings.Id == existingSettings.Id); + Assert.NotNull(modifiedSettings); + Assert.Equal(existingSettings.UserId, modifiedSettings.UserId); + Assert.False(modifiedSettings.IsPaginationEnabled); + Assert.Equal(12, modifiedSettings.ItemsPerPage); + Assert.True(modifiedSettings.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public async Task UpdateAsync_WhenSettingsDoNotExist_ShouldReturnError() + { + // Arrange + UserSettingsEntity settings = _userSettingsEntityFixture.Create(); + + // Act + Result result = await _sut.UpdateAsync(settings, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.UserSettings.UserSettingsNotFound, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs new file mode 100644 index 00000000..7212fa13 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsTests +{ + [Fact] + public void Create_WhenCalledWithoutValues_ShouldCreateSettingsWithDefaultValues() + { + // Arrange + UserId userId = UserId.CreateUnique(); + + // Act + Result result = UserSettings.Create(userId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(userId, result.Value.UserId); + Assert.True(result.Value.IsPaginationEnabled); + Assert.Equal(48, result.Value.ItemsPerPage); + Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public void Create_WhenCalledWithoutUserId_ShouldCreateSettingsWithDefaultValuesAndGeneratedUserId() + { + // Act + Result result = UserSettings.Create(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value.UserId); + Assert.True(result.Value.IsPaginationEnabled); + Assert.Equal(48, result.Value.ItemsPerPage); + Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public void Create_WhenCalledTwice_ShouldGenerateDistinctIds() + { + // Act + Result firstResult = UserSettings.Create(); + Result secondResult = UserSettings.Create(); + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + Assert.NotEqual(firstResult.Value.UserId.Value, secondResult.Value.UserId.Value); + Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value); + } + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateSettings() + { + // Arrange + UserId userId = UserId.CreateUnique(); + + // Act + Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(userId, result.Value.UserId); + Assert.False(result.Value.IsPaginationEnabled); + Assert.Equal(24, result.Value.ItemsPerPage); + Assert.True(result.Value.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldGenerateDistinctSettingsIdFromUserId() + { + // Arrange + UserId userId = UserId.CreateUnique(); + + // Act + Result result = UserSettings.Create(userId); + + // Assert + Assert.False(result.IsFailure); + Assert.NotEqual(result.Value.Id.Value, result.Value.UserId.Value); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void Create_WhenItemsPerPageIsNotPositive_ShouldReturnError(int itemsPerPage) + { + // Arrange + UserId userId = UserId.CreateUnique(); + + // Act + Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); + } + + [Fact] + public void UpdateSettings_WhenCalledWithValidValues_ShouldUpdateSettings() + { + // Arrange + Result createResult = UserSettings.Create(UserId.CreateUnique()); + + // Act + Result result = createResult.Value.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true); + + // Assert + Assert.False(result.IsFailure); + Assert.False(createResult.Value.IsPaginationEnabled); + Assert.Equal(12, createResult.Value.ItemsPerPage); + Assert.True(createResult.Value.IgnoreThePrefixForAlphaPicker); + } + + [Theory] + [InlineData(0)] + [InlineData(-5)] + public void UpdateSettings_WhenItemsPerPageIsNotPositive_ShouldReturnError(int itemsPerPage) + { + // Arrange + Result createResult = UserSettings.Create(UserId.CreateUnique()); + + // Act + Result result = createResult.Value.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..580fedb9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetUserSettings; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Settings.GetUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetUserSettingsEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public GetUserSettingsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUserSettingsResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + UserSettingsResponse expectedResponse = new(Guid.NewGuid(), true, 48, false); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("General.Failure", "An error has occurred."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.IsType(problemResult.ProblemDetails); + Assert.Equal("General.Failure", problemResult.ProblemDetails.Title); + Assert.Equal("An error has occurred.", problemResult.ProblemDetails.Detail); + Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetUserSettingsQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false))); + + // Act + await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false)); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..03c65397 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,122 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdateUserSettingsEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public UpdateUserSettingsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker() + { + // Arrange + UpdateUserSettingsRequest request = new(true, 48, false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Updated, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + UpdateUserSettingsRequest request = new(true, 0, false); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("UserSettings.ItemsPerPageMustBeGreaterThanZero", "ItemsPerPage must be greater than zero."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.IsType(problemResult.ProblemDetails); + Assert.Equal("General.Validation", problemResult.ProblemDetails.Title); + Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToHandler() + { + // Arrange + UpdateUserSettingsRequest request = new(true, 24, true); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.IsPaginationEnabled == request.IsPaginationEnabled && + command.ItemsPerPage == request.ItemsPerPage && + command.IgnoreThePrefixForAlphaPicker == request.IgnoreThePrefixForAlphaPicker), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Updated); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false), cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +}