mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #151 from BinaryAlley/feature/user-settings-aggregate
Adds user settings management
This commit is contained in:
67 files changed
+4718
-30
No files matched your search
+59
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for the settings of a user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}; UserId: {UserId}")]
|
||||
public class UserSettingsEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of these user settings.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the user that owns these settings.
|
||||
/// </summary>
|
||||
public required Guid UserId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether pagination is enabled for the user, or not.
|
||||
/// </summary>
|
||||
public bool IsPaginationEnabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of library items displayed per page when pagination is enabled.
|
||||
/// </summary>
|
||||
public int ItemsPerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
|
||||
/// </summary>
|
||||
public bool IgnoreThePrefixForAlphaPicker { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+28
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for user settings.
|
||||
/// </summary>
|
||||
public interface IUserSettingsRepository : IRepository<UserSettingsEntity>,
|
||||
IGetByIdRepositoryAction<UserSettingsEntity, Guid>,
|
||||
IInsertRepositoryAction<UserSettingsEntity>,
|
||||
IUpdateRepositoryAction<UserSettingsEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the settings of the user identified by <paramref name="userId"/>, if they exist.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose settings are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="UserSettingsEntity"/> of the user, or an error.</returns>
|
||||
Task<Result<UserSettingsEntity?>> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -80,6 +80,11 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
IUserRepository UserRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user settings repository.
|
||||
/// </summary>
|
||||
IUserSettingsRepository UserSettingsRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Saves all changes made to the database.
|
||||
/// </summary>
|
||||
|
||||
+4
-5
@@ -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,
|
||||
|
||||
+25
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="UpdateUserSettingsRequest"/>.
|
||||
/// </summary>
|
||||
public static class UpdateUserSettingsRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="UpdateUserSettingsCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static UpdateUserSettingsCommand ToCommand(this UpdateUserSettingsRequest request)
|
||||
{
|
||||
return new UpdateUserSettingsCommand(
|
||||
request.IsPaginationEnabled,
|
||||
request.ItemsPerPage,
|
||||
request.IgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
}
|
||||
+47
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="UserSettingsEntity"/>.
|
||||
/// </summary>
|
||||
public static class UserSettingsEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="UserSettings"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="UserSettings"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<UserSettings> ToDomainEntity(this UserSettingsEntity repositoryEntity)
|
||||
{
|
||||
return UserSettings.Create(
|
||||
UserSettingsId.Create(repositoryEntity.Id),
|
||||
UserId.Create(repositoryEntity.UserId),
|
||||
repositoryEntity.IsPaginationEnabled,
|
||||
repositoryEntity.ItemsPerPage,
|
||||
repositoryEntity.IgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="UserSettingsResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static UserSettingsResponse ToResponse(this UserSettingsEntity repositoryEntity)
|
||||
{
|
||||
return new UserSettingsResponse(
|
||||
repositoryEntity.UserId,
|
||||
repositoryEntity.IsPaginationEnabled,
|
||||
repositoryEntity.ItemsPerPage,
|
||||
repositoryEntity.IgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="UserSettings"/>.
|
||||
/// </summary>
|
||||
public static class UserSettingsMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="UserSettingsEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="UserSettingsResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static UserSettingsResponse ToResponse(this UserSettings domainEntity)
|
||||
{
|
||||
return new UserSettingsResponse(
|
||||
domainEntity.UserId.Value,
|
||||
domainEntity.IsPaginationEnabled,
|
||||
domainEntity.ItemsPerPage,
|
||||
domainEntity.IgnoreThePrefixForAlphaPicker);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Command for updating the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
public record UpdateUserSettingsCommand(
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool IgnoreThePrefixForAlphaPicker
|
||||
) : ICommand;
|
||||
+105
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to update the settings of the current user.
|
||||
/// </summary>
|
||||
public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettingsCommand, Result<Updated>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<UpdateUserSettingsCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public UpdateUserSettingsCommandHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<UpdateUserSettingsCommand> validator)
|
||||
{
|
||||
_currentUserService = currentUserService;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to update the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> representing either a successful update, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<Updated>> HandleAsync(UpdateUserSettingsCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<UserSettingsEntity?> 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<UserSettings> createSettingsResult = UserSettings.Create(
|
||||
UserId.Create(userId),
|
||||
command.IsPaginationEnabled,
|
||||
command.ItemsPerPage,
|
||||
command.IgnoreThePrefixForAlphaPicker);
|
||||
if (createSettingsResult.IsFailure)
|
||||
return createSettingsResult.Errors;
|
||||
|
||||
Result<Created> 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<UserSettings> toDomainEntityResult = getSettingsResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
|
||||
Result<Updated> updateSettingsResult = toDomainEntityResult.Value.UpdateSettings(
|
||||
command.IsPaginationEnabled,
|
||||
command.ItemsPerPage,
|
||||
command.IgnoreThePrefixForAlphaPicker);
|
||||
if (updateSettingsResult.IsFailure)
|
||||
return updateSettingsResult.Errors;
|
||||
|
||||
Result<Updated> 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;
|
||||
}
|
||||
}
|
||||
+23
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="UpdateUserSettingsCommand"/>.
|
||||
/// </summary>
|
||||
public class UpdateUserSettingsCommandValidator : AbstractValidator<UpdateUserSettingsCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public UpdateUserSettingsCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.ItemsPerPage)
|
||||
.GreaterThan(0)
|
||||
.WithError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the settings of the current user.
|
||||
/// </summary>
|
||||
public record GetUserSettingsQuery : IQuery;
|
||||
+71
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the settings of the current user.
|
||||
/// </summary>
|
||||
public class GetUserSettingsQueryHandler : IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public GetUserSettingsQueryHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_currentUserService = currentUserService;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully retrieved <see cref="UserSettingsResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<UserSettingsResponse>> 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<UserSettingsEntity?> 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<UserSettings> defaultSettingsResult = UserSettings.Create();
|
||||
if (defaultSettingsResult.IsFailure)
|
||||
return defaultSettingsResult.Errors;
|
||||
return defaultSettingsResult.Value.ToResponse();
|
||||
}
|
||||
|
||||
return getSettingsResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to update the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not. Required.</param>
|
||||
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled. Required.</param>
|
||||
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.</param>
|
||||
[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")]
|
||||
public sealed record UpdateUserSettingsRequest(
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool IgnoreThePrefixForAlphaPicker
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the settings of a user.
|
||||
/// </summary>
|
||||
/// <param name="UserId">The unique identifier of the user that owns these settings.</param>
|
||||
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
[DebuggerDisplay("UserId: {UserId}")]
|
||||
public sealed record UserSettingsResponse(
|
||||
Guid UserId,
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool IgnoreThePrefixForAlphaPicker
|
||||
);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="UserSettingsEntity"/> entity.
|
||||
/// </summary>
|
||||
public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="UserSettingsEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<UserSettingsEntity> 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<UserEntity>()
|
||||
.WithOne()
|
||||
.HasForeignKey<UserSettingsEntity>(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();
|
||||
}
|
||||
}
|
||||
+1214
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsUserSettingsTable : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "UserSettings",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
IsPaginationEnabled = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
ItemsPerPage = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
IgnoreThePrefixForAlphaPicker = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "UserSettings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<bool>("IgnoreThePrefixForAlphaPicker")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<bool>("IsPaginationEnabled")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<int>("ItemsPerPage")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<Guid>("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");
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for user settings.
|
||||
/// </summary>
|
||||
internal sealed class UserSettingsRepository : IUserSettingsRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserSettingsRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public UserSettingsRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the settings of a user.
|
||||
/// </summary>
|
||||
/// <param name="data">The user settings to add.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Created>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings identified by <paramref name="id"/>, if they exist.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the user settings to get.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="UserSettingsEntity"/> identified by <paramref name="id"/>, or an error.</returns>
|
||||
public async Task<Result<UserSettingsEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.UserSettings
|
||||
.FirstOrDefaultAsync(settings => settings.Id == id, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings of the user identified by <paramref name="userId"/>, if they exist.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose settings are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="UserSettingsEntity"/> of the user, or an error.</returns>
|
||||
public async Task<Result<UserSettingsEntity?>> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.UserSettings
|
||||
.FirstOrDefaultAsync(settings => settings.UserId == userId, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the settings of a user.
|
||||
/// </summary>
|
||||
/// <param name="data">The user settings to update.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> 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;
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ public class LuminaDbContext : DbContext
|
||||
{
|
||||
public virtual DbSet<BookEntity> Books { get; set; } = null!;
|
||||
public virtual DbSet<UserEntity> Users { get; set; } = null!;
|
||||
public virtual DbSet<UserSettingsEntity> UserSettings { get; set; } = null!;
|
||||
public virtual DbSet<LibraryEntity> Libraries { get; set; } = null!;
|
||||
public virtual DbSet<LibraryScanEntity> LibraryScans { get; set; } = null!;
|
||||
public virtual DbSet<LibraryScanResultEntity> LibraryScanResults { get; set; } = null!;
|
||||
|
||||
@@ -39,6 +39,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository;
|
||||
private IPluginRepository? _pluginRepository;
|
||||
private IUserRepository? _userRepository;
|
||||
private IUserSettingsRepository? _userSettingsRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the permission repository.
|
||||
@@ -196,6 +197,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user settings repository.
|
||||
/// </summary>
|
||||
public IUserSettingsRepository UserSettingsRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_userSettingsRepository ??= new UserSettingsRepository(_luminaDbContext);
|
||||
return _userSettingsRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Common.Errors;
|
||||
|
||||
/// <summary>
|
||||
/// User settings error types.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
+158
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Aggregate root for the settings of a user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}; UserId: {UserId}")]
|
||||
public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
{
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the object representing the unique identifier of the user that owns these settings.
|
||||
/// </summary>
|
||||
public UserId UserId { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether pagination is enabled for the user, or not.
|
||||
/// </summary>
|
||||
public bool IsPaginationEnabled { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of library items displayed per page when pagination is enabled.
|
||||
/// </summary>
|
||||
public int ItemsPerPage { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
|
||||
/// </summary>
|
||||
public bool IgnoreThePrefixForAlphaPicker { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserSettings"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">The object representing the unique identifier of these settings.</param>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns these settings.</param>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
private UserSettings(
|
||||
UserSettingsId id,
|
||||
UserId userId,
|
||||
bool isPaginationEnabled,
|
||||
int itemsPerPage,
|
||||
bool ignoreThePrefixForAlphaPicker) : base(id)
|
||||
{
|
||||
UserId = userId;
|
||||
IsPaginationEnabled = isPaginationEnabled;
|
||||
ItemsPerPage = itemsPerPage;
|
||||
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserSettings"/> class, with the default settings.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="UserSettings"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<UserSettings> Create()
|
||||
{
|
||||
return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserSettings"/> class, with the default settings.
|
||||
/// </summary>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns these settings.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="UserSettings"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<UserSettings> Create(UserId userId)
|
||||
{
|
||||
return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserSettings"/> class.
|
||||
/// </summary>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns these settings.</param>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="UserSettings"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<UserSettings> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserSettings"/> class, with a pre-existing <paramref name="id"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">The object representing the unique identifier of these settings.</param>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns these settings.</param>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="UserSettings"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<UserSettings> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the settings of the user.
|
||||
/// </summary>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
|
||||
public Result<Updated> UpdateSettings(
|
||||
bool isPaginationEnabled,
|
||||
int itemsPerPage,
|
||||
bool ignoreThePrefixForAlphaPicker)
|
||||
{
|
||||
if (itemsPerPage <= 0)
|
||||
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
|
||||
|
||||
IsPaginationEnabled = isPaginationEnabled;
|
||||
ItemsPerPage = itemsPerPage;
|
||||
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
+51
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the Id of a set of user settings.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Value}")]
|
||||
public sealed class UserSettingsId : EntityId<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserSettingsId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The value representing this object.</param>
|
||||
private UserSettingsId(Guid value) : base(value)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserSettingsId"/> class.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="UserSettingsId"/> instance.</returns>
|
||||
public static UserSettingsId CreateUnique()
|
||||
{
|
||||
return new UserSettingsId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserSettingsId"/> class, from a pre-existing <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The value used to create the <see cref="UserSettingsId"/> instance.</param>
|
||||
/// <returns>The created <see cref="UserSettingsId"/> instance.</returns>
|
||||
public static UserSettingsId Create(Guid value)
|
||||
{
|
||||
return new UserSettingsId(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of items that define equality of the object.
|
||||
/// </summary>
|
||||
/// <returns>A list of items defining the equality.</returns>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Value;
|
||||
}
|
||||
}
|
||||
@@ -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<AuthorizationPermission> allPermissions = rolePermissions is not null ? directPermissions.Union(rolePermissions).ToHashSet() : directPermissions;
|
||||
HashSet<AuthorizationPermission> allPermissions = rolePermissions is not null ? [.. directPermissions.Union(rolePermissions)] : directPermissions;
|
||||
|
||||
return new UserAuthorizationEntity
|
||||
{
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
+55
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/settings</c> route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class GetUserSettingsEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>> _getUserSettingsQueryHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="getUserSettingsQueryHandler">Injected service for handling get user settings queries.</param>
|
||||
public GetUserSettingsEndpoint(IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>> getUserSettingsQueryHandler)
|
||||
{
|
||||
_getUserSettingsQueryHandler = getUserSettingsQueryHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(Http.GET);
|
||||
Routes(ApiRoutes.Users.GET_USER_SETTINGS);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<UserSettingsResponse> result = await _getUserSettingsQueryHandler.HandleAsync(new GetUserSettingsQuery(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+62
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetUserSettingsEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointSummary : Summary<GetUserSettingsEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
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"
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+56
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/settings</c> route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class UpdateUserSettingsEndpoint : BaseEndpoint<UpdateUserSettingsRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<UpdateUserSettingsCommand, Result<Updated>> _updateUserSettingsCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="updateUserSettingsCommandHandler">Injected service for handling update user settings commands.</param>
|
||||
public UpdateUserSettingsEndpoint(ICommandHandler<UpdateUserSettingsCommand, Result<Updated>> updateUserSettingsCommandHandler)
|
||||
{
|
||||
_updateUserSettingsCommandHandler = updateUserSettingsCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.PUT);
|
||||
Routes(ApiRoutes.Users.UPDATE_USER_SETTINGS);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the new settings of the current user.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(UpdateUserSettingsRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<Updated> result = await _updateUserSettingsCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+83
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="UpdateUserSettingsEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointSummary : Summary<UpdateUserSettingsEndpoint, UpdateUserSettingsRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
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<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"ItemsPerPageMustBeGreaterThanZero"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the settings of a user.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")]
|
||||
public class UserSettingsModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the unique identifier of the user that owns these settings.
|
||||
/// </summary>
|
||||
public Guid? UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether pagination is enabled for the user, or not.
|
||||
/// </summary>
|
||||
public bool IsPaginationEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of library items displayed per page when pagination is enabled.
|
||||
/// </summary>
|
||||
public int ItemsPerPage { get; set; } = 48;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
|
||||
/// </summary>
|
||||
public bool IgnoreThePrefixForAlphaPicker { get; set; }
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Controller for the settings of the current user.
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[Route("{culture}/tools/settings")]
|
||||
public class SettingsController : Controller
|
||||
{
|
||||
private readonly IApiHttpClient _apiHttpClient;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SettingsController"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
|
||||
public SettingsController(IApiHttpClient apiHttpClient)
|
||||
{
|
||||
_apiHttpClient = apiHttpClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Displays the view for editing the settings of the current user.
|
||||
/// </summary>
|
||||
[HttpGet("")]
|
||||
public IActionResult Index()
|
||||
{
|
||||
UserSettingsModel settings = new();
|
||||
return View("/Views/Tools/Settings.cshtml", settings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
[HttpGet("api-get-user-settings")]
|
||||
public async Task<IActionResult> GetUserSettings(CancellationToken cancellationToken = default)
|
||||
{
|
||||
UserSettingsModel response = await _apiHttpClient.GetAsync<UserSettingsModel>("users/me/settings", cancellationToken).ConfigureAwait(false);
|
||||
return Json(new { success = true, data = response });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="data">The model containing the new settings of the current user.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
[ValidateAntiForgeryToken]
|
||||
[HttpPost("api-update-user-settings")]
|
||||
public async Task<IActionResult> UpdateUserSettings([FromBody] UserSettingsModel data, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<EmptyModel, UserSettingsModel>("users/me/settings", data, cancellationToken).ConfigureAwait(false);
|
||||
return Json(new { success = true, data = new { isUpdated = true } });
|
||||
}
|
||||
}
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>Musik</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>Optionen</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Einstellungen</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>Profil</value>
|
||||
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>Music</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>Options</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>Profile</value>
|
||||
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>Música</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>Opciones</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Configuración</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>Perfil</value>
|
||||
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>Musique</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>Options</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Paramètres</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>Profil</value>
|
||||
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>Musica</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>Opzioni</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Impostazioni</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>Profilo</value>
|
||||
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>音楽</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>オプション</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>設定</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>プロフィール</value>
|
||||
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>Music</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>Options</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>Profile</value>
|
||||
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>Muzică</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>Opțiuni</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Setări</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>Profil</value>
|
||||
|
||||
@@ -177,7 +177,7 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>Музыка</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Настройки</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
|
||||
@@ -177,8 +177,8 @@
|
||||
<data name="Music" xml:space="preserve">
|
||||
<value>音乐</value>
|
||||
</data>
|
||||
<data name="Options" xml:space="preserve">
|
||||
<value>选项</value>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>设置</value>
|
||||
</data>
|
||||
<data name="Profile" xml:space="preserve">
|
||||
<value>个人资料</value>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Einstellungen</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>Seitennummerierung aktivieren</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>Elemente pro Seite</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>"The"-Präfix für die Alpha-Auswahl ignorieren</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>Speichern</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>Einstellungen gespeichert</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>Steuert, ob die Bibliothekselemente in Seiten aufgeteilt werden.</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>Die Anzahl der Bibliothekselemente, die bei aktivierter Seitennummerierung auf jeder Seite angezeigt werden.</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>Enable pagination</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>Items per page</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>Ignore "The" prefix for the alpha picker</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>Save</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>Settings saved</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>Controls whether library items are split into pages.</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>The number of library items displayed on each page when pagination is enabled.</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Configuración</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>Habilitar paginación</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>Elementos por página</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>Ignorar el prefijo "The" en el selector alfabético</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>Guardar</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>Configuración guardada</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>Controla si los elementos de la biblioteca se dividen en páginas.</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>El número de elementos de la biblioteca mostrados en cada página cuando la paginación está habilitada.</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Paramètres</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>Activer la pagination</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>Éléments par page</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>Ignorer le préfixe "The" dans le sélecteur alphabétique</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>Enregistrer</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>Paramètres enregistrés</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>Contrôle si les éléments de la bibliothèque sont répartis en pages.</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>Le nombre d'éléments de la bibliothèque affichés sur chaque page lorsque la pagination est activée.</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Impostazioni</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>Abilita paginazione</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>Elementi per pagina</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>Ignora il prefisso "The" nel selettore alfabetico</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>Salva</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>Impostazioni salvate</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>Controlla se gli elementi della libreria vengono suddivisi in pagine.</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>Il numero di elementi della libreria visualizzati su ogni pagina quando la paginazione è abilitata.</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>設定</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>ページネーションを有効にする</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>ページあたりの項目数</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>アルファピッカーで「The」の接頭辞を無視する</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>保存</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>設定を保存しました</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>ライブラリの項目をページに分割するかどうかを制御します。</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>ページネーションが有効な場合に各ページに表示されるライブラリの項目数。</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>有効にすると、タイトルが「The」で始まるライブラリの項目は、アルファピッカーで次の単語の最初の文字の下にグループ化されます。たとえば「The Rasmus」は「R」の下に表示されます。</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>Enable pagination</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>Items per page</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>Ignore "The" prefix for the alpha picker</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>Save</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>Settings saved</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>Controls whether library items are split into pages.</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>The number of library items displayed on each page when pagination is enabled.</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Setări</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>Activați paginarea</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>Elemente pe pagină</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>Ignorați prefixul "The" pentru selectorul alfabetic</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>Salvați</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>Setările au fost salvate</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>Controlează dacă elementele bibliotecii sunt împărțite în pagini.</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>Numărul de elemente ale bibliotecii afișate pe fiecare pagină atunci când paginarea este activată.</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>Настройки</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>Включить разбиение на страницы</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>Элементов на странице</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>Игнорировать префикс "The" в алфавитном указателе</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>Сохранить</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>Настройки сохранены</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>Управляет разделением элементов библиотеки на страницы.</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>Количество элементов библиотеки, отображаемых на каждой странице при включенной разбивке на страницы.</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>При включении элементы библиотеки, название которых начинается с "The", группируются в алфавитном указателе под первой буквой следующего слова, например "The Rasmus" отображается под буквой R.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="Settings" xml:space="preserve">
|
||||
<value>设置</value>
|
||||
</data>
|
||||
<data name="EnablePagination" xml:space="preserve">
|
||||
<value>启用分页</value>
|
||||
</data>
|
||||
<data name="ItemsPerPage" xml:space="preserve">
|
||||
<value>每页项目数</value>
|
||||
</data>
|
||||
<data name="IgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>在字母选择器中忽略“The”前缀</value>
|
||||
</data>
|
||||
<data name="Save" xml:space="preserve">
|
||||
<value>保存</value>
|
||||
</data>
|
||||
<data name="SettingsSaved" xml:space="preserve">
|
||||
<value>设置已保存</value>
|
||||
</data>
|
||||
<data name="DescriptionEnablePagination" xml:space="preserve">
|
||||
<value>控制是否将库项目分页显示。</value>
|
||||
</data>
|
||||
<data name="DescriptionItemsPerPage" xml:space="preserve">
|
||||
<value>启用分页时每页显示的库项目数。</value>
|
||||
</data>
|
||||
<data name="DescriptionIgnoreThePrefixForAlphaPicker" xml:space="preserve">
|
||||
<value>启用后,标题以"The"开头的库项目将在字母选择器中按后一个词的首字母分组,例如"The Rasmus"会列在R下。</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -106,7 +106,7 @@
|
||||
@_localizer["Tools"]
|
||||
</div>
|
||||
<ul>
|
||||
<li><a href="tools/options" class="nav-link"><span>@_localizer["Options"]</span></a></li>
|
||||
<li><a href="@_urlService.GetAbsoluteUrl("Index", "Settings")" class="nav-link"><span>@_localizer["Settings"]</span></a></li>
|
||||
</ul>
|
||||
}
|
||||
<div class="mobile-menu-heading">
|
||||
@@ -211,7 +211,7 @@
|
||||
</li>
|
||||
@if (User?.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
<li><a href="tools/options" class="nav-link">@_localizer["Options"]</a></li>
|
||||
<li><a href="@_urlService.GetAbsoluteUrl("Index", "Settings")" class="nav-link">@_localizer["Settings"]</a></li>
|
||||
}
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
@@ -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
|
||||
|
||||
<div style="display: grid; grid-template-rows: auto 1fr;"><!--container with two rows, one fixed, one filling remaining space-->
|
||||
<div style="min-height: 1rem;"></div><!--the first row is a dummy row for "margin", because setting a margin on the next row would offset the parent's position-->
|
||||
<div class="enlightenment-panel shadow-effect mx-auto panel w-50 mb-10" style="min-width: 320px;">
|
||||
<div class="shine-effect"></div>
|
||||
<form method="post" id="user-settings-form" class="inline">
|
||||
@Html.AntiForgeryToken()
|
||||
<div class="form-row">
|
||||
<h1 class="text-light-two w-100 text-center pt-0 pb-0 engraved-title">
|
||||
@_localizer["Settings"]
|
||||
</h1>
|
||||
</div>
|
||||
<div class="form-container">
|
||||
<!-- Pagination -->
|
||||
<div class="form-row">
|
||||
<div class="form-label">
|
||||
<label asp-for="IsPaginationEnabled">@_localizer["EnablePagination"]</label>:
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label class="enlightenment-checkbox-label">
|
||||
<input type="checkbox" asp-for="IsPaginationEnabled" class="enlightenment-checkbox-hidden" />
|
||||
<span class="enlightenment-checkbox"></span>
|
||||
</label>
|
||||
</div>
|
||||
<small class="form-label text-disabled form-description">@_localizer["DescriptionEnablePagination"]</small>
|
||||
</div>
|
||||
<!-- Items per page -->
|
||||
<div class="form-row">
|
||||
<div class="form-label">
|
||||
<label asp-for="ItemsPerPage">@_localizer["ItemsPerPage"]</label>
|
||||
<span class="mandatory-field">*</span>:
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<input asp-for="ItemsPerPage" min="1" step="1" class="enlightenment-input" />
|
||||
</div>
|
||||
<small class="form-label text-disabled form-description">@_localizer["DescriptionItemsPerPage"]</small>
|
||||
</div>
|
||||
<!-- Alpha picker -->
|
||||
<div class="form-row">
|
||||
<div class="form-label">
|
||||
<label asp-for="IgnoreThePrefixForAlphaPicker">@_localizer["IgnoreThePrefixForAlphaPicker"]</label>:
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label class="enlightenment-checkbox-label">
|
||||
<input type="checkbox" asp-for="IgnoreThePrefixForAlphaPicker" class="enlightenment-checkbox-hidden" />
|
||||
<span class="enlightenment-checkbox"></span>
|
||||
</label>
|
||||
</div>
|
||||
<small class="form-label text-disabled form-description">@_localizer["DescriptionIgnoreThePrefixForAlphaPicker"]</small>
|
||||
</div>
|
||||
<div class="form-row" style="justify-content: center;">
|
||||
<button type="submit" class="confirm-button h-22px">@_localizer["Save"]</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@section Scripts {
|
||||
<script type="text/javascript" data-form="@scriptId" defer>
|
||||
// create cleanup registry for this view
|
||||
const cleanupFunctions = [];
|
||||
let isInitialized = false;
|
||||
|
||||
const form = document.getElementById('user-settings-form');
|
||||
const checkboxIsPaginationEnabled = document.getElementById('IsPaginationEnabled');
|
||||
const inputItemsPerPage = document.getElementById('ItemsPerPage');
|
||||
const checkboxIgnoreThePrefixForAlphaPicker = document.getElementById('IgnoreThePrefixForAlphaPicker');
|
||||
|
||||
// toggle the enabled state of the items per page input based on the pagination checkbox
|
||||
function updateItemsPerPageEnabledState() {
|
||||
inputItemsPerPage.disabled = !checkboxIsPaginationEnabled.checked;
|
||||
}
|
||||
|
||||
// load the settings of the current user
|
||||
async function loadUserSettingsAsync() {
|
||||
const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetUserSettings", "Settings")');
|
||||
if (data) {
|
||||
checkboxIsPaginationEnabled.checked = data.isPaginationEnabled === true;
|
||||
inputItemsPerPage.value = data.itemsPerPage;
|
||||
checkboxIgnoreThePrefixForAlphaPicker.checked = data.ignoreThePrefixForAlphaPicker === true;
|
||||
updateItemsPerPageEnabledState();
|
||||
}
|
||||
}
|
||||
|
||||
// save the settings of the current user
|
||||
async function handleSaveUserSettingsAsync() {
|
||||
const formData = {
|
||||
IsPaginationEnabled: checkboxIsPaginationEnabled.checked,
|
||||
ItemsPerPage: Number(inputItemsPerPage.value),
|
||||
IgnoreThePrefixForAlphaPicker: checkboxIgnoreThePrefixForAlphaPicker.checked
|
||||
};
|
||||
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("UpdateUserSettings", "Settings")', formData);
|
||||
if (data && data.isUpdated === true)
|
||||
notificationService.show('@_localizer["SettingsSaved"]', NotificationType.SUCCESS);
|
||||
}
|
||||
|
||||
// on form submit event
|
||||
const handleSubmit = async function(e) {
|
||||
e.preventDefault();
|
||||
await handleSaveUserSettingsAsync();
|
||||
};
|
||||
|
||||
// on pagination checkbox change, update the enabled state of the items per page input
|
||||
const handlePaginationCheckboxChange = function() {
|
||||
updateItemsPerPageEnabledState();
|
||||
};
|
||||
|
||||
// add listeners
|
||||
form.addEventListener('submit', handleSubmit);
|
||||
checkboxIsPaginationEnabled.addEventListener('change', handlePaginationCheckboxChange);
|
||||
document.addEventListener('DOMContentLoaded', InitializeAsync);
|
||||
|
||||
// register cleanup for these listeners
|
||||
cleanupFunctions.push(() => {
|
||||
form.removeEventListener('submit', handleSubmit);
|
||||
checkboxIsPaginationEnabled.removeEventListener('change', handlePaginationCheckboxChange);
|
||||
document.removeEventListener('DOMContentLoaded', InitializeAsync);
|
||||
});
|
||||
|
||||
async function InitializeAsync() {
|
||||
if (isInitialized)
|
||||
return;
|
||||
isInitialized = true;
|
||||
await loadUserSettingsAsync();
|
||||
}
|
||||
|
||||
// store all cleanups for this view on window object using the scriptId
|
||||
window.viewCleanups = window.viewCleanups || {};
|
||||
window.viewCleanups['@scriptId'] = () => {
|
||||
cleanupFunctions.forEach(cleanup => cleanup());
|
||||
console.log(`Unloaded @scriptId`);
|
||||
};
|
||||
console.log(`Loaded @scriptId`);
|
||||
</script>
|
||||
}
|
||||
+55
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UserSettingsEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsEntityFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UserSettingsEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the user settings.</param>
|
||||
/// <param name="userId">Optional. The Id of the user that owns these settings.</param>
|
||||
/// <param name="isPaginationEnabled">Optional. Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="itemsPerPage">Optional. The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker, or not.</param>
|
||||
/// <returns>The created user settings entity.</returns>
|
||||
public UserSettingsEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? userId = null,
|
||||
bool? isPaginationEnabled = null,
|
||||
int? itemsPerPage = null,
|
||||
bool? ignoreThePrefixForAlphaPicker = null)
|
||||
{
|
||||
return new Faker<UserSettingsEntity>()
|
||||
.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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="UserSettingsEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UserSettingsEntity"/> instances.</returns>
|
||||
public List<UserSettingsEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+46
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateUserSettingsCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command to update the settings of the current user.
|
||||
/// </summary>
|
||||
/// <param name="isPaginationEnabled">Optional. Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="itemsPerPage">Optional. The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker, or not.</param>
|
||||
/// <returns>The created command.</returns>
|
||||
public UpdateUserSettingsCommand Create(
|
||||
bool? isPaginationEnabled = null,
|
||||
int? itemsPerPage = null,
|
||||
bool? ignoreThePrefixForAlphaPicker = null)
|
||||
{
|
||||
return new Faker<UpdateUserSettingsCommand>()
|
||||
.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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="UpdateUserSettingsCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UpdateUserSettingsCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+141
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
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<UserSettingsResponse>(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<UserSettingsResponse>(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<UserSettingsEntity> CreateTestUserSettings()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+143
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateUserSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
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<LuminaDbContext>();
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+116
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/users/me/settings</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
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<LuminaDbContext>();
|
||||
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<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+150
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/users/me/settings</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
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<LuminaDbContext>();
|
||||
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<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+169
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateUserSettingsCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IUserSettingsRepository _mockUserSettingsRepository;
|
||||
private readonly IValidator<UpdateUserSettingsCommand> _mockValidator;
|
||||
private readonly UpdateUserSettingsCommandHandler _sut;
|
||||
private readonly UpdateUserSettingsCommandFixture _updateUserSettingsCommandFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateUserSettingsCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<UpdateUserSettingsCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<UpdateUserSettingsCommand>())
|
||||
.Returns([]);
|
||||
|
||||
_sut = new UpdateUserSettingsCommandHandler(_mockCurrentUserService, _mockUnitOfWork, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSettingsDoNotExist_ShouldInsertSettingsAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(null));
|
||||
_mockUserSettingsRepository.InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<Updated> 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<UserSettingsEntity>(settings =>
|
||||
settings.UserId == _userId &&
|
||||
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
|
||||
settings.ItemsPerPage == command.ItemsPerPage &&
|
||||
settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSettingsExist_ShouldUpdateSettingsAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
|
||||
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId);
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(existingSettings));
|
||||
_mockUserSettingsRepository.UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
Result<Updated> 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<UserSettingsEntity>(settings =>
|
||||
settings.UserId == _userId &&
|
||||
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
|
||||
settings.ItemsPerPage == command.ItemsPerPage &&
|
||||
settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<UpdateUserSettingsCommand>())
|
||||
.Returns([DomainErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero]);
|
||||
|
||||
// Act
|
||||
Result<Updated> 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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotPersist()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<Updated> 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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+66
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateUserSettingsCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[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<Error> 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<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+119
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetUserSettingsQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetUserSettingsQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
|
||||
_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<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(storedSettings));
|
||||
|
||||
// Act
|
||||
Result<UserSettingsResponse> 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<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<UserSettingsResponse> 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<UserSettingsResponse> 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<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<UserSettingsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
}
|
||||
}
|
||||
+179
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserSettingsRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly UserSettingsRepository _sut;
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserSettingsRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public UserSettingsRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new UserSettingsRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenSettingsDoNotExist_ShouldAddSettingsToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(settings, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
|
||||
EntityEntry<UserSettingsEntity>? addedSettings = _mockContext.ChangeTracker.Entries<UserSettingsEntity>()
|
||||
.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<Created> result = await _sut.InsertAsync(settings, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.UserSettings.UserSettingsAlreadyExists, result.FirstError);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<UserSettingsEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenSettingsExist_ShouldReturnSettings()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
|
||||
_mockContext.UserSettings.Add(settings);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<UserSettingsEntity?> 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<UserSettingsEntity?> 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<UserSettingsEntity?> 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<UserSettingsEntity?> 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<Updated> 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<Updated> result = await _sut.UpdateAsync(settings, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.UserSettings.UserSettingsNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+141
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserSettings"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithoutValues_ShouldCreateSettingsWithDefaultValues()
|
||||
{
|
||||
// Arrange
|
||||
UserId userId = UserId.CreateUnique();
|
||||
|
||||
// Act
|
||||
Result<UserSettings> 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<UserSettings> 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<UserSettings> firstResult = UserSettings.Create();
|
||||
Result<UserSettings> 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<UserSettings> 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<UserSettings> 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<UserSettings> 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<UserSettings> createResult = UserSettings.Create(UserId.CreateUnique());
|
||||
|
||||
// Act
|
||||
Result<Updated> 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<UserSettings> createResult = UserSettings.Create(UserId.CreateUnique());
|
||||
|
||||
// Act
|
||||
Result<Updated> result = createResult.Value.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError);
|
||||
}
|
||||
}
|
||||
+119
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>> _mockHandler;
|
||||
private readonly GetUserSettingsEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetUserSettingsEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>>>();
|
||||
_sut = Factory.Create<GetUserSettingsEndpoint>(_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<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<UserSettingsResponse> okResult = Assert.IsType<Ok<UserSettingsResponse>>(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<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(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<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
|
||||
.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<GetUserSettingsQuery>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(info => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false));
|
||||
}, info.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+122
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<UpdateUserSettingsCommand, Result<Updated>> _mockHandler;
|
||||
private readonly UpdateUserSettingsEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateUserSettingsEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<UpdateUserSettingsCommand, Result<Updated>>>();
|
||||
_sut = FastEndpoints.Factory.Create<UpdateUserSettingsEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = new(true, 48, false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<Updated> okResult = Assert.IsType<Ok<Updated>>(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<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Assert.IsType<HttpValidationProblemDetails>(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<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateUserSettingsCommand>(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<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(info => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(Result.Updated);
|
||||
}, info.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user