From 7e54c990ad9cb7a5abf99d55b7d8d7b517207763 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 11:47:51 -0700 Subject: [PATCH] Adds a restore action for soft deleted bundled themes --- .../Themes/RestoreThemeRequestMapping.cs | 22 ++ .../Mapping/Themes/ThemeEntityMapping.cs | 3 +- .../RestoreTheme/RestoreThemeCommand.cs | 16 ++ .../RestoreThemeCommandHandler.cs | 106 ++++++++ .../RestoreThemeCommandValidator.cs | 24 ++ .../GetThemes/GetThemesQueryHandler.cs | 5 +- .../Requests/Themes/RestoreThemeRequest.cs | 15 ++ .../Responses/Themes/ThemeResponse.cs | 4 +- .../Common/Errors/Errors.Themes.cs | 1 + .../Common/Routes/Themes/ApiRoutes.Themes.cs | 1 + .../InstallThemeEndpointSummary.cs | 3 +- .../RestoreTheme/RestoreThemeEndpoint.cs | 53 ++++ .../RestoreThemeEndpointSummary.cs | 120 +++++++++ .../SetCurrentThemeEndpointSummary.cs | 3 +- .../GetCurrentThemeEndpointSummary.cs | 3 +- .../GetThemeTemplateEndpointSummary.cs | 3 +- .../GetThemes/GetThemesEndpointSummary.cs | 6 +- .../Common/DTO/Themes/ThemeInfoDto.cs | 4 +- .../Common/DTO/Themes/ThemeResponseDto.cs | 4 +- .../Requests/Themes/RestoreThemeRequest.cs | 14 + .../Common/Routes/ApiRoutes.Themes.cs | 1 + .../Common/Routes/WebRoutes.Themes.cs | 1 + .../RestoreTheme/RestoreThemeEndpoint.cs | 59 +++++ .../Resources/Views/Admin/Themes.de-DE.resx | 3 + .../Resources/Views/Admin/Themes.en-US.resx | 3 + .../Resources/Views/Admin/Themes.es-ES.resx | 3 + .../Resources/Views/Admin/Themes.fr-FR.resx | 3 + .../Resources/Views/Admin/Themes.it-IT.resx | 3 + .../Resources/Views/Admin/Themes.ja-JP.resx | 3 + .../Core/Resources/Views/Admin/Themes.resx | 3 + .../Resources/Views/Admin/Themes.ro-RO.resx | 3 + .../Resources/Views/Admin/Themes.ru-RU.resx | 3 + .../Resources/Views/Admin/Themes.zh-CN.resx | 3 + .../Core/Themes/ThemeService.cs | 12 +- .../Core/Views/Admin/Themes.cshtml | 30 ++- .../RestoreThemeCommandFixture.cs | 38 +++ .../Themes/RestoreThemeRequestFixture.cs | 38 +++ .../Responses/Themes/ThemeResponseFixture.cs | 7 +- .../Common/DTO/Themes/ThemeInfoDtoFixture.cs | 7 +- .../DTO/Themes/ThemeResponseDtoFixture.cs | 7 +- .../RestoreTheme/RestoreThemeEndpointTests.cs | 231 +++++++++++++++++ .../RestoreTheme/RestoreThemeEndpointTests.cs | 193 ++++++++++++++ .../Themes/RestoreThemeRequestMappingTests.cs | 32 +++ .../Mapping/Themes/ThemeEntityMappingTests.cs | 1 + .../RestoreThemeCommandHandlerTests.cs | 241 ++++++++++++++++++ .../RestoreThemeCommandValidatorTests.cs | 61 +++++ .../GetThemes/GetThemesQueryHandlerTests.cs | 6 +- .../RestoreTheme/RestoreThemeEndpointTests.cs | 202 +++++++++++++++ .../RestoreTheme/RestoreThemeEndpointTests.cs | 85 ++++++ 49 files changed, 1666 insertions(+), 26 deletions(-) create mode 100644 src/Lumina.Application/Common/Mapping/Themes/RestoreThemeRequestMapping.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommand.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidator.cs create mode 100644 src/Lumina.Contracts/Requests/Themes/RestoreThemeRequest.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpoint.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/RestoreThemeRequestFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/RestoreThemeRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs diff --git a/src/Lumina.Application/Common/Mapping/Themes/RestoreThemeRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/RestoreThemeRequestMapping.cs new file mode 100644 index 00000000..e4087116 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/RestoreThemeRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Contracts.Requests.Themes; +#endregion + +namespace Lumina.Application.Common.Mapping.Themes; + +/// +/// Extension methods for converting . +/// +public static class RestoreThemeRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static RestoreThemeCommand ToCommand(this RestoreThemeRequest request) + { + return new RestoreThemeCommand(request.ThemeId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs index c6818b85..b3460bc2 100644 --- a/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs @@ -27,6 +27,7 @@ public static class ThemeEntityMapping theme.PreviewPath, theme.InstallSource, theme.IsCurrent, - theme.InstalledAtUtc); + theme.InstalledAtUtc, + theme.IsDeleted); } } diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommand.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommand.cs new file mode 100644 index 00000000..642eb561 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Command for restoring a soft deleted bundled theme. +/// +/// The manifest id of the theme to restore. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record RestoreThemeCommand( + string? ThemeId +) : ICommand; diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs new file mode 100644 index 00000000..c092f1ac --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using System; +using System.Collections.Generic; +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.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Handler for the command to restore a soft deleted bundled theme. +/// +public class RestoreThemeCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IThemeService _themeService; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for the server-side storage and serving of theme packs. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public RestoreThemeCommandHandler( + IUnitOfWork unitOfWork, + IThemeService themeService, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to restore a soft deleted bundled theme. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(RestoreThemeCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // only admins can restore themes + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + Result getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false); + if (getThemeResult.IsFailure) + return getThemeResult.Errors; + + ThemeEntity? theme = getThemeResult.Value; + if (theme is null) + return DomainErrors.Themes.ThemeNotFound; + + // only bundled themes are soft deleted, so only a soft deleted bundled theme can be restored + if (!theme.IsDeleted || theme.InstallSource != ThemeInstallSource.Bundled) + return DomainErrors.Themes.ThemeCannotBeRestored; + + // restore the pack files from the shipped archive before reactivating the theme + Result restoreFilesResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); + if (restoreFilesResult.IsFailure) + return restoreFilesResult.Errors; + + theme.IsDeleted = false; + theme.IsCurrent = null; + theme.UpdatedOnUtc = DateTime.UtcNow; + theme.UpdatedBy = userId; + Result updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidator.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidator.cs new file mode 100644 index 00000000..d2b145a9 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Validates the needed validation rules for . +/// +public class RestoreThemeCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeCommandValidator() + { + RuleFor(command => command.ThemeId) + .NotEmpty() + .WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs index 90202b57..03eb9b5a 100644 --- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs @@ -45,10 +45,11 @@ public class GetThemesQueryHandler : IQueryHandler>([.. getThemesResult.Value - .Where(theme => !theme.IsDeleted) + .OrderBy(theme => theme.IsDeleted) // the shipped bundled themes are listed before the user themes, so the defaults stay the most visible - .OrderByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled) + .ThenByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled) .ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase) .Select(theme => theme.ToResponse())]); } diff --git a/src/Lumina.Contracts/Requests/Themes/RestoreThemeRequest.cs b/src/Lumina.Contracts/Requests/Themes/RestoreThemeRequest.cs new file mode 100644 index 00000000..b0e07d08 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Themes/RestoreThemeRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Themes; + +/// +/// Represents a request to restore a soft deleted bundled theme. +/// +/// The manifest id of the theme to restore. Required. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record RestoreThemeRequest( + string? ThemeId +); diff --git a/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs b/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs index adda0c8c..b8aca76f 100644 --- a/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs +++ b/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs @@ -19,6 +19,7 @@ namespace Lumina.Contracts.Responses.Themes; /// The source the theme was installed from. /// Whether the theme is the currently active one. /// The UTC timestamp at which the theme was installed. +/// Whether the theme was deleted by the user, which is only possible for bundled themes. [DebuggerDisplay("ThemeId: {ThemeId}, Name: {Name}")] public record ThemeResponse( Guid Id, @@ -30,5 +31,6 @@ public record ThemeResponse( string? PreviewPath, ThemeInstallSource InstallSource, bool? IsCurrent, - DateTime InstalledAtUtc + DateTime InstalledAtUtc, + bool IsDeleted ); diff --git a/src/Lumina.Domain/Common/Errors/Errors.Themes.cs b/src/Lumina.Domain/Common/Errors/Errors.Themes.cs index 81affa2e..3c32d711 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Themes.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Themes.cs @@ -18,6 +18,7 @@ public static partial class Errors public static Error ThemeArchiveCannotBeNull => Error.Validation(description: nameof(ThemeArchiveCannotBeNull)); public static Error LastBundledThemeCannotBeDeleted => Error.Forbidden(description: nameof(LastBundledThemeCannotBeDeleted)); public static Error ThemeCannotBeDeleted => Error.Forbidden(description: nameof(ThemeCannotBeDeleted)); + public static Error ThemeCannotBeRestored => Error.Forbidden(description: nameof(ThemeCannotBeRestored)); public static Error ThemeArchiveNotReadable => Error.Failure(description: nameof(ThemeArchiveNotReadable)); public static Error ThemeFilesUnreadable => Error.Failure(description: nameof(ThemeFilesUnreadable)); public static Error ThemeNotAvailable => Error.Failure(description: nameof(ThemeNotAvailable)); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs index f9e366ce..3c094d40 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs @@ -15,6 +15,7 @@ public static partial class ApiRoutes public const string GET_THEME_TEMPLATE = "/themes/{themeId}/templates/{*pageKey}"; public const string GET_THEME_ASSET = "/themes/{themeId}/assets/{*assetPath}"; public const string GET_THEME_ARCHIVE = "/themes/{themeId}/archive"; + public const string RESTORE_THEME = "/themes/{themeId}/restore"; public const string DELETE_THEME = "/themes/{themeId}"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs index 9513198f..83bd9815 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs @@ -34,7 +34,8 @@ public class InstallThemeEndpointSummary : Summary +/// API endpoint for the /themes/{themeId}/restore route. +/// +public class RestoreThemeEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _restoreThemeCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling restore theme commands. + public RestoreThemeEndpoint(ICommandHandler> restoreThemeCommandHandler) + { + _restoreThemeCommandHandler = restoreThemeCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Themes.RESTORE_THEME); + Version(1); + DontCatchExceptions(); + } + + /// + /// Restores the soft deleted bundled theme identified by . + /// + /// The request containing the theme to restore. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RestoreThemeRequest request, CancellationToken cancellationToken) + { + Result result = await _restoreThemeCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.NoContent(), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointSummary.cs new file mode 100644 index 00000000..e2592e87 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointSummary.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.RestoreTheme; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeEndpointSummary() + { + Summary = "Restores a deleted bundled theme."; + Description = "Restores the files and reactivates a bundled theme that was soft deleted by the user, restoring the pack from the shipped archive."; + + ExampleRequest = new RestoreThemeRequest( + ThemeId: "editorial-paper" + ); + + RequestParam(r => r.ThemeId, "The manifest id of the bundled theme to restore. Required."); + + Response(204, "The theme was successfully restored."); + + 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/themes/{themeId}/restore" + }, + 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/themes/{themeId}/restore" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/themes/{themeId}/restore" + } + } + ); + + Response(403, "The request failed because the user is not an Admin or the theme is not a soft deleted bundled theme.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/themes/{themeId}/restore", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "ThemeCannotBeRestored", + instance = "/api/v1/themes/{themeId}/restore", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the provided theme does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ThemeNotFound", + instance = "/api/v1/themes/{themeId}/restore", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + 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/themes/{themeId}/restore", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ThemeIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs index a26d0331..b6bf6338 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs @@ -41,7 +41,8 @@ public class SetCurrentThemeEndpointSummary : Summary
{{content}}
" )); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs index f4d20771..2faaeadb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs @@ -34,7 +34,8 @@ public class GetThemesEndpointSummary : Summary PreviewPath: "preview.png", InstallSource: ThemeInstallSource.Bundled, IsCurrent: true, - InstalledAtUtc: DateTime.UtcNow + InstalledAtUtc: DateTime.UtcNow, + IsDeleted: false ), new ( Id: Guid.NewGuid(), @@ -46,7 +47,8 @@ public class GetThemesEndpointSummary : Summary PreviewPath: "preview.jpg", InstallSource: ThemeInstallSource.Uploaded, IsCurrent: null, - InstalledAtUtc: DateTime.UtcNow + InstalledAtUtc: DateTime.UtcNow, + IsDeleted: false ) }); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs index 3303271a..4dcf7cdb 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs @@ -14,6 +14,7 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes; /// The version of the theme, using semantic version form. /// The URL of the theme preview image. /// Whether the theme ships with the application or noy. +/// Whether the theme was deleted by the user, which is only possible for bundled themes. [DebuggerDisplay("Id: {Id}, Name: {Name}")] public sealed record ThemeInfoDto( string Id, @@ -22,5 +23,6 @@ public sealed record ThemeInfoDto( string Author, string Version, string PreviewUrl, - bool IsBundled + bool IsBundled, + bool IsDeleted ); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs index 632cac46..fe46174c 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs @@ -19,6 +19,7 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes; /// The source the theme was installed from. /// Whether the theme is the currently active one. /// The UTC timestamp at which the theme was installed. +/// Whether the theme was deleted by the user, which is only possible for bundled themes. [DebuggerDisplay("ThemeId: {ThemeId}, Name: {Name}")] public sealed record ThemeResponseDto( Guid Id, @@ -30,5 +31,6 @@ public sealed record ThemeResponseDto( string? PreviewPath, ThemeInstallSource InstallSource, bool? IsCurrent, - DateTime InstalledAtUtc + DateTime InstalledAtUtc, + bool IsDeleted ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs new file mode 100644 index 00000000..0ded5c46 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Themes; + +/// +/// Represents a request to restore a soft deleted bundled theme. +/// +/// The manifest id of the bundled theme to restore. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record RestoreThemeRequest( + string? ThemeId +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs index c7f14c91..040bdf48 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs @@ -18,6 +18,7 @@ public static partial class ApiRoutes public const string GET_THEME_TEMPLATE = "themes/{themeId}/templates/{*pageKey}"; public const string GET_THEME_ASSET = "themes/{themeId}/assets/{*assetPath}"; public const string GET_THEME_ARCHIVE = "themes/{themeId}/archive"; + public const string RESTORE_THEME = "themes/{themeId}/restore"; public const string DELETE_THEME = "themes/{themeId}"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs index 3ff06780..52ca707e 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs @@ -13,6 +13,7 @@ public static partial class WebRoutes public const string GET_THEMES = "{culture}/admin/themes/api-get-themes"; public const string INSTALL_THEME = "{culture}/admin/themes/api-install-theme"; public const string SET_CURRENT_THEME = "{culture}/admin/themes/api-set-current-theme"; + public const string RESTORE_THEME = "{culture}/admin/themes/api-restore-theme/{themeId}"; public const string DELETE_THEME = "{culture}/admin/themes/api-delete-theme/{themeId}"; public const string DOWNLOAD_THEME = "{culture}/admin/themes/api-download-theme/{themeId}"; public const string THEME_ASSETS = "theme-assets/{themeId}/{*path}"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpoint.cs new file mode 100644 index 00000000..0c53d557 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; + +/// +/// API endpoint for the /{culture}/admin/themes/api-restore-theme/{themeId} route. +/// +public class RestoreThemeEndpoint : BaseEndpoint +{ + private readonly ThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the remote theme endpoints. + public RestoreThemeEndpoint(ThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Themes.RESTORE_THEME); + DontAutoTag(); + Options(options => options.WithTags("Themes")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Restores the soft deleted bundled theme identified by . + /// + /// The request containing the theme to restore. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RestoreThemeRequest request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.ThemeId)) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id cannot be empty."); + + await _themeService.RestoreThemeAsync(request.ThemeId, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx index 646913fe..732fbc9f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx @@ -144,6 +144,9 @@ Herunterladen + + Wiederherstellen + Hochladen diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx index cdff40e2..6b067312 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx @@ -144,6 +144,9 @@ Download + + Restore + Upload diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx index dbd389c0..a09ab9b0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx @@ -144,6 +144,9 @@ Descargar + + Restaurar + Subir diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx index 86823228..16496ace 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx @@ -144,6 +144,9 @@ Télécharger + + Restaurer + Téléverser diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx index 8bf1478b..8bb93eaf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx @@ -144,6 +144,9 @@ Scarica + + Ripristina + Carica diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx index 4cf2bc83..ed060625 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx @@ -144,6 +144,9 @@ ダウンロード + + 復元 + アップロード diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx index cdff40e2..6b067312 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx @@ -144,6 +144,9 @@ Download + + Restore + Upload diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx index 502efbd1..27398dbb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx @@ -144,6 +144,9 @@ Descarcă + + Restaurează + Încarcă diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx index 720ec102..35abb21e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx @@ -144,6 +144,9 @@ Скачать + + Восстановить + Загрузить diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx index 3cb35acf..5fb9c608 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx @@ -144,6 +144,9 @@ 下载 + + 恢复 + 上传 diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs index ebb5b27a..42ff8bb0 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs @@ -94,6 +94,16 @@ public sealed class ThemeService await _apiHttpClient.DeleteAsync(ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false); } + /// + /// Restores a soft deleted bundled theme from its shipped archive. + /// + /// The identifier of the bundled theme to restore. + /// Cancellation token that can be used to stop the execution. + public async Task RestoreThemeAsync(string themeId, CancellationToken cancellationToken = default) + { + await _apiHttpClient.PostAsync(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), new { }, cancellationToken).ConfigureAwait(false); + } + /// /// Gets the theme and raw template source selected for a page key. /// @@ -134,6 +144,6 @@ public sealed class ThemeService private static ThemeInfoDto ToThemeInfo(ThemeResponseDto theme) { string previewUrl = string.IsNullOrWhiteSpace(theme.PreviewPath) ? "/admin/theme-placeholder.svg" : $"/theme-assets/{theme.ThemeId}/{theme.PreviewPath}"; - return new ThemeInfoDto(theme.ThemeId, theme.Name, theme.Description, theme.Author, theme.Version, previewUrl, theme.InstallSource == ThemeInstallSource.Bundled); + return new ThemeInfoDto(theme.ThemeId, theme.Name, theme.Description, theme.Author, theme.Version, previewUrl, theme.InstallSource == ThemeInstallSource.Bundled, theme.IsDeleted); } } diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml index 6529ff80..7d2756f8 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml @@ -5,6 +5,7 @@ @using Lumina.Presentation.Web.Common.DTO.Themes @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization +@using System.Linq @{ var themes = ViewData["themes"] as IReadOnlyList; @@ -14,7 +15,7 @@ int bundledThemeCount = 0; if (themes is not null) foreach (ThemeInfoDto theme in themes) - if (theme.IsBundled) + if (theme.IsBundled && !theme.IsDeleted) bundledThemeCount++; } @@ -109,7 +110,7 @@ @foreach (ThemeInfoDto theme in themes) { bool isCurrent = theme.Id == currentThemeId; - bool isLastRemaining = themes.Count <= 1 || (theme.IsBundled && bundledThemeCount == 1); + bool isLastRemaining = themes.Count(theme => !theme.IsDeleted) <= 1 || (theme.IsBundled && bundledThemeCount == 1); - - + @if (theme.IsDeleted) + { + + } + else + { + + + + } @@ -171,6 +179,16 @@ } } + // restores the soft deleted bundled theme of the clicked row + async function handleRestoreClick(event) { + const button = event.target.closest('.restore-theme-button'); + if (!button) + return; + // an empty JSON body is sent so the antiforgery-protected POST request binds the route theme id without a JsonException + await callApiPostAsync(button.dataset.url, {}); + reloadPage(); + } + // downloads the archive of the theme of the clicked row function handleDownloadClick(event) { const button = event.target.closest('.download-theme-button'); @@ -227,6 +245,7 @@ document.addEventListener('click', handleActivateClick); document.addEventListener('click', handleDownloadClick); document.addEventListener('click', handleDeleteClick); + document.addEventListener('click', handleRestoreClick); document.addEventListener('click', handlePreviewClick); // register cleanup for these listeners @@ -236,6 +255,7 @@ document.removeEventListener('click', handleActivateClick); document.removeEventListener('click', handleDownloadClick); document.removeEventListener('click', handleDeleteClick); + document.removeEventListener('click', handleRestoreClick); document.removeEventListener('click', handlePreviewClick); }); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandFixture.cs new file mode 100644 index 00000000..5df2db9c --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeCommandFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional manifest id of the theme to restore. + /// The created . + public RestoreThemeCommand Create(string? themeId = null) + { + return new RestoreThemeCommand(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/RestoreThemeRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/RestoreThemeRequestFixture.cs new file mode 100644 index 00000000..74c725ca --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/RestoreThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The manifest id of the theme to restore. + /// The created . + public RestoreThemeRequest Create(string? themeId = null) + { + return new RestoreThemeRequest(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs index c0c03b0d..780ed917 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs @@ -33,6 +33,7 @@ public class ThemeResponseFixture /// Optional. Whether the theme is the currently active one. /// Whether to set , or when . /// Optional. The UTC timestamp when the theme was installed. + /// Optional. Whether the theme was deleted by the user. /// The created . public ThemeResponse Create( Guid? id = null, @@ -46,7 +47,8 @@ public class ThemeResponseFixture ThemeInstallSource? installSource = null, bool? isCurrent = null, bool includeIsCurrent = false, - DateTime? installedAtUtc = null) + DateTime? installedAtUtc = null, + bool? isDeleted = null) { return new ThemeResponse( id ?? Guid.NewGuid(), @@ -58,7 +60,8 @@ public class ThemeResponseFixture includePreviewPath ? (previewPath ?? (_faker.Random.Bool() ? _faker.System.FilePath() : null)) : null, installSource ?? _faker.PickRandom(), includeIsCurrent ? (isCurrent ?? (_faker.Random.Bool() ? true : null)) : null, - installedAtUtc ?? _faker.Date.Recent().ToUniversalTime()); + installedAtUtc ?? _faker.Date.Recent().ToUniversalTime(), + isDeleted ?? _faker.Random.Bool()); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs index a7f32034..7fa24e10 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs @@ -25,6 +25,7 @@ public class ThemeInfoDtoFixture /// Optional semantic version of the theme. /// Optional URL of the theme preview image. /// Whether the theme ships with the application. + /// Whether the theme was deleted by the user. /// A configured instance. public ThemeInfoDto Create( string? id = null, @@ -33,7 +34,8 @@ public class ThemeInfoDtoFixture string? author = null, string? version = null, string? previewUrl = null, - bool? isBundled = null) + bool? isBundled = null, + bool? isDeleted = null) { Faker faker = new(); return new ThemeInfoDto( @@ -43,7 +45,8 @@ public class ThemeInfoDtoFixture Author: author ?? faker.Name.FullName(), Version: version ?? faker.System.Semver(), PreviewUrl: previewUrl ?? $"/theme-assets/{faker.Lorem.Word()}/preview.png", - IsBundled: isBundled ?? faker.Random.Bool() + IsBundled: isBundled ?? faker.Random.Bool(), + IsDeleted: isDeleted ?? faker.Random.Bool() ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs index 9abbbf15..ab1803a5 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs @@ -31,6 +31,7 @@ public class ThemeResponseDtoFixture /// Optional value indicating whether the theme is the active one. /// Whether to set , or when . /// Optional UTC timestamp at which the theme was installed. + /// Optional value indicating whether the theme was deleted by the user. /// A configured instance. public ThemeResponseDto Create( Guid? id = null, @@ -44,7 +45,8 @@ public class ThemeResponseDtoFixture ThemeInstallSource? installSource = null, bool? isCurrent = null, bool includeIsCurrent = false, - DateTime? installedAtUtc = null) + DateTime? installedAtUtc = null, + bool? isDeleted = null) { Faker faker = new(); return new ThemeResponseDto( @@ -57,7 +59,8 @@ public class ThemeResponseDtoFixture PreviewPath: includePreviewPath ? (previewPath ?? (faker.Random.Bool() ? faker.System.FilePath() : null)) : null, InstallSource: installSource ?? ThemeInstallSource.Uploaded, IsCurrent: includeIsCurrent ? (isCurrent ?? (faker.Random.Bool() ? true : null)) : null, - InstalledAtUtc: installedAtUtc ?? faker.Date.Recent() + InstalledAtUtc: installedAtUtc ?? faker.Date.Recent(), + IsDeleted: isDeleted ?? faker.Random.Bool() ); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..c62ba506 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,231 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.RestoreTheme; +using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Themes; +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.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Management.RestoreTheme; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly TestThemeArchiveFixture _themeArchiveFixture = new(); + private readonly List _installedThemeIds = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes an authenticated admin API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedAdminClientAsync(); + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithDeletedBundledTheme_ShouldRestoreTheme() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(candidate => candidate.ThemeId == "editorial-paper"); + Assert.NotNull(theme); + theme!.IsDeleted = true; + theme.IsCurrent = null; + await dbContext.SaveChangesAsync(); + } + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + + // the theme is available again and appears in the list + using IServiceScope verificationScope = _apiFactory.Services.CreateScope(); + LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService(); + ThemeEntity? restoredTheme = await verificationContext.Themes.FirstOrDefaultAsync(candidate => candidate.ThemeId == "editorial-paper"); + Assert.NotNull(restoredTheme); + Assert.False(restoredTheme!.IsDeleted); + + HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes"); + List? themes = await listResponse.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(themes); + Assert.Contains(themes!, theme => theme.ThemeId == "editorial-paper" && !theme.IsDeleted); + } + + [Fact] + public async Task RestoreTheme_WhenThemeDoesNotExist_ShouldReturnNotFound() + { + // Arrange + string themeId = "nonexistent-theme"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/themes/{themeId}/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/themes/{themeId}/restore", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task RestoreTheme_WhenThemeIsNotDeleted_ShouldReturnForbiddenResult() + { + // Arrange + string themeId = await InstallUserThemeAsync(); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/themes/{themeId}/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("ThemeCannotBeRestored", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/themes/{themeId}/restore", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync(); + + // Act + HttpResponseMessage response = await nonAdminClient.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes/editorial-paper/restore", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Installs a test theme through the API and returns its manifest id. + /// + /// The manifest id of the installed theme. + private async Task InstallUserThemeAsync() + { + string themeId = $"test-theme-{Guid.NewGuid():N}"; + byte[] archiveBytes = _themeArchiveFixture.Create(themeId); + + using MultipartFormDataContent multipartContent = []; + using ByteArrayContent fileContent = new(archiveBytes); + multipartContent.Add(fileContent, "file", "theme.zip"); + + HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent); + response.EnsureSuccessStatusCode(); + + _installedThemeIds.Add(themeId); + return themeId; + } + + /// + /// Removes any test theme installed by a failed test and clears the authorization seed data of the admin test user. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + foreach (string themeId in _installedThemeIds) + { + ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == themeId); + if (theme is not null) + dbContext.Themes.Remove(theme); + } + + await dbContext.SaveChangesAsync(); + + IThemeService themeService = scope.ServiceProvider.GetRequiredService(); + foreach (string themeId in _installedThemeIds) + await themeService.DeleteAsync(themeId, CancellationToken.None); + + // the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..8cf6dff8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,193 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.SecurityTests.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.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.RestoreTheme; + +/// +/// Contains security tests for the POST /api/v1/themes/{themeId}/restore route. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly string _themeId; + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreThemeEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + _themeId = $"testtheme{Guid.NewGuid():N}"; + } + + [Fact] + public async Task RestoreTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/themes/{Guid.NewGuid():N}/restore"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, new { }); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task RestoreTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateUserAsync(client); + string url = $"/api/v1/themes/{Guid.NewGuid():N}/restore"; + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync(url, new { }); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task RestoreTheme_WhenThemeIsNotDeleted_ShouldReturnForbiddenResultWithoutReactivatingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedThemeAsync(isDeleted: false); + string url = $"/api/v1/themes/{_themeId}/restore"; + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync(url, new { }); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("ThemeCannotBeRestored", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("..%2F..%2Fevil")] // encoded slash traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal + [InlineData("..%5Cevil")] // encoded backslash traversal + [InlineData("..%2F")] // encoded trailing slash traversal + public async Task RestoreTheme_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + string url = $"/api/v1/themes/{maliciousThemeId}/restore"; + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync(url, new { }); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + + // note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem + if (!string.IsNullOrWhiteSpace(content)) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + } + } + + /// + /// Seeds a with the unique test theme id. + /// + /// Whether the seeded theme is marked as deleted. + /// A task representing the asynchronous operation. + private async Task SeedThemeAsync(bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: isDeleted)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Removes the seeded theme. + /// + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ThemeEntity? theme = dbContext.Themes.FirstOrDefault(candidate => candidate.ThemeId == _themeId); + if (theme is not null) + { + dbContext.Themes.Remove(theme); + dbContext.SaveChanges(); + } + + _client.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/RestoreThemeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/RestoreThemeRequestMappingTests.cs new file mode 100644 index 00000000..df9b6e8c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/RestoreThemeRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Themes; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeRequestMappingTests +{ + private readonly RestoreThemeRequestFixture _restoreThemeRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingRequest_ShouldMapThemeId() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(themeId: "editorial-paper"); + + // Act + RestoreThemeCommand command = request.ToCommand(); + + // Assert + Assert.NotNull(command); + Assert.Equal(request.ThemeId, command.ThemeId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs index 17f390ee..4b9cf5b3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs @@ -48,6 +48,7 @@ public class ThemeEntityMappingTests Assert.Equal(theme.InstallSource, result.InstallSource); Assert.Equal(theme.IsCurrent, result.IsCurrent); Assert.Equal(theme.InstalledAtUtc, result.InstalledAtUtc); + Assert.Equal(theme.IsDeleted, result.IsDeleted); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs new file mode 100644 index 00000000..0a3ffd43 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs @@ -0,0 +1,241 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Repositories.Themes; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly RestoreThemeCommandHandler _sut; + private readonly RestoreThemeCommandFixture _restoreThemeCommandFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(true); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockThemeService.RestoreBundledThemeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success); + + _sut = new RestoreThemeCommandHandler( + _mockUnitOfWork, + _mockThemeService, + _mockCurrentUserService, + _mockAuthorizationService, + _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get theme"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsNotDeleted_ShouldReturnThemeCannotBeRestoredError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeCannotBeRestored, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsDeletedButNotBundled_ShouldReturnThemeCannotBeRestoredError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeCannotBeRestored, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenFileRestorationFails_ShouldReturnErrorWithoutReactivatingTheme() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: true); + Error error = Error.Failure("Theme.FilesUnreadable", "Failed to restore theme files"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoringDeletedBundledTheme_ShouldRestoreFilesAndReactivateTheme() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && !entity.IsDeleted && entity.IsCurrent == null && entity.UpdatedBy == _userId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidatorTests.cs new file mode 100644 index 00000000..98383d69 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidatorTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme; +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.Themes.Management.Commands.RestoreTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeCommandValidatorTests +{ + private readonly RestoreThemeCommandValidator _validator = new(); + private readonly RestoreThemeCommandFixture _restoreThemeCommandFixture = new(); + + [Fact] + public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + command = command with { ThemeId = null }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(themeId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsValid_ShouldNotHaveValidationErrors() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs index 3066d68c..a6e2b80c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs @@ -41,7 +41,7 @@ public class GetThemesQueryHandlerTests } [Fact] - public async Task HandleAsync_WhenCalled_ShouldReturnAllAvailableThemesOrderedBundledFirstThenByName() + public async Task HandleAsync_WhenCalled_ShouldReturnAllThemesOrderedAvailableBundledFirstThenByNameWithDeletedLast() { // Arrange GetThemesQuery query = _getThemesQueryFixture.Create(); @@ -57,13 +57,15 @@ public class GetThemesQueryHandlerTests // Assert Assert.False(result.IsFailure); - Assert.Equal(3, result.Value.Count); + Assert.Equal(4, result.Value.Count); Assert.Equal(bundledLowerTheme.Id, result.Value[0].Id); Assert.Equal(bundledUpperTheme.Id, result.Value[1].Id); Assert.Equal(uploadedTheme.Id, result.Value[2].Id); + Assert.Equal(deletedTheme.Id, result.Value[3].Id); Assert.Equal(ThemeInstallSource.Bundled, result.Value[0].InstallSource); Assert.Equal(ThemeInstallSource.Bundled, result.Value[1].InstallSource); Assert.Equal(ThemeInstallSource.Uploaded, result.Value[2].InstallSource); + Assert.True(result.Value[3].IsDeleted); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..cc96569a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,202 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.RestoreTheme; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +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.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.RestoreTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly RestoreThemeEndpoint _sut; + private readonly RestoreThemeRequestFixture _restoreThemeRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContentResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.IsType(result); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsForbiddenError_ShouldReturnProblemResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeCannotBeRestored; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Forbidden", problemDetailsBody.Title); + Assert.Equal("ThemeCannotBeRestored", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendRestoreThemeCommandToHandler() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ThemeId == request.ThemeId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..96d7f0f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +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.Web.UnitTests.Core.Endpoints.Admin.Themes.RestoreTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RestoreThemeEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldRestoreThemeAndReturnSuccessJson() + { + // Arrange + string themeId = "editorial-paper"; + + // Act + IResult result = await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body)) + { + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldRestoreThemeWithResolvedEndpoint() + { + // Arrange + string themeId = "editorial-paper"; + string expectedEndpoint = ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId); + + // Act + await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync(expectedEndpoint, Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData(null)] // missing theme id + [InlineData("")] // empty theme id + [InlineData(" ")] // whitespace theme id + public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) + { + // Act + IResult result = await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().PostAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +}