From 48fb09dcc6ec06a5b07ed482a71fb3d9998b7c87 Mon Sep 17 00:00:00 2001 From: Kjetil Haugland Date: Tue, 5 Nov 2024 12:28:35 +0100 Subject: [PATCH] Refactor classes to file-scoped namespace --- .../Helpers/SlugHelper.cs | 291 ++-- .../Queries/ContextTypes/ContextTypeDto.cs | 11 +- .../Queries/Portals/PortalOnboardedAppDto.cs | 17 +- .../Services/AppService/AppService.cs | 59 +- .../Services/PortalService/PortalService.cs | 137 +- .../Infrastructure/QueryBase.cs | 7 +- .../Controllers/OnboardedAppController.cs | 373 +++-- .../Controllers/PortalController.cs | 921 ++++++----- .../ContextType/ApiAddContextTypeRequest.cs | 31 +- .../ViewModels/ContextType/ApiContextType.cs | 23 +- .../ApiRemoveContextTypeRequest.cs | 33 +- .../FusionApp/ApiFusionAppCategory.cs | 43 +- .../FusionApp/ApiFusionAppVersion.cs | 23 +- .../OnboardedApp/ApiOnboardAppRequest.cs | 33 +- .../OnboardedApp/ApiOnboardedApp.cs | 43 +- .../ApiRemoveOnboardedAppRequest.cs | 31 +- .../ApiUpdateOnboardedAppRequest.cs | 25 +- .../ApiAddContextTypeToOnboardedAppRequest.cs | 31 +- .../ApiRemoveOnboardedAppContextType.cs | 13 +- .../OnboardedContext/ApiOnboardedContext.cs | 41 +- .../ApiOnboardedContextRequest.cs | 43 +- .../ApiRemoveOnboardedContextRequest.cs | 31 +- .../ApiUpdateOnboardedContextRequest.cs | 31 +- .../Portal/ApiCreatePortalRequest.cs | 71 +- .../ViewModels/Portal/ApiPortal.cs | 61 +- .../Portal/ApiPortalConfiguration.cs | 29 +- .../Portal/ApiRemovePortalRequest.cs | 15 +- .../ApiUpdatePortalConfigurationRequest.cs | 47 +- .../Portal/ApiUpdatePortalRequest.cs | 65 +- .../ApiAddContextAppToPortalRequest.cs | 33 +- .../ApiAddGlobalAppToPortalRequest.cs | 47 +- .../ViewModels/PortalApp/ApiPortalApp.cs | 31 +- .../PortalApp/ApiPortalOnboardedApp.cs | 47 +- .../PortalApp/ApiRemovePortalAppRequest.cs | 21 +- .../ApiAddContextTypeToPortalRequest.cs | 31 +- .../ApiRemovePortalContextType.cs | 13 +- .../Data/ContextTypeData.cs | 35 +- .../Data/FusionAppApiData.cs | 119 +- .../Data/FusionContextApiData.cs | 87 +- .../Data/OnboardedAppData.cs | 23 +- .../Data/OnboardedContextData.cs | 15 +- .../Data/PortalConfigurationData.cs | 21 +- .../Data/PortalData.cs | 41 +- .../IntegrationTests/AssertHelpers.cs | 97 +- .../ContextTypeControllerTests.cs | 389 +++-- .../OnboardedAppControllerTests.cs | 593 ++++---- .../OnboardedContextControllerTests.cs | 383 +++-- .../IntegrationTests/PortalControllerTests.cs | 1351 ++++++++--------- .../Misc/ApplicationDbContextExtension.cs | 123 +- .../Setup/ITestUser.cs | 13 +- .../Setup/IntegrationTestAuthHandler.cs | 139 +- .../Setup/IntegrationTestAuthOptions.cs | 7 +- .../Setup/TestUser.cs | 15 +- .../Setup/TokenProfile.cs | 45 +- .../Setup/UserType.cs | 15 +- .../TestBase.cs | 15 +- .../TestFactory.cs | 402 +++-- 57 files changed, 3336 insertions(+), 3394 deletions(-) diff --git a/backend/src/Equinor.ProjectExecutionPortal.Application/Helpers/SlugHelper.cs b/backend/src/Equinor.ProjectExecutionPortal.Application/Helpers/SlugHelper.cs index e128cef70..1f5796858 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.Application/Helpers/SlugHelper.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.Application/Helpers/SlugHelper.cs @@ -1,165 +1,164 @@ using System.Globalization; using System.Text; -namespace Equinor.ProjectExecutionPortal.Application.Helpers +namespace Equinor.ProjectExecutionPortal.Application.Helpers; + +// https://github.com/zarxor/url-friendly-slug +public static class SlugHelper { - // https://github.com/zarxor/url-friendly-slug - public static class SlugHelper + /// + /// Creates a URL And SEO friendly slug + /// + /// Text to slugify + /// Max length of slug + /// URL and SEO friendly string + public static string Sluggify(string text, int maxLength = 0) { - /// - /// Creates a URL And SEO friendly slug - /// - /// Text to slugify - /// Max length of slug - /// URL and SEO friendly string - public static string Sluggify(string text, int maxLength = 0) - { - var normalizedString = text - .ToLowerInvariant() - .Normalize(NormalizationForm.FormD); - - var stringBuilder = new StringBuilder(); - var stringLength = normalizedString.Length; - var prevdash = false; - var trueLength = 0; + var normalizedString = text + .ToLowerInvariant() + .Normalize(NormalizationForm.FormD); - for (var i = 0; i < stringLength; i++) - { - var c = normalizedString[i]; + var stringBuilder = new StringBuilder(); + var stringLength = normalizedString.Length; + var prevdash = false; + var trueLength = 0; - switch (CharUnicodeInfo.GetUnicodeCategory(c)) - { - // Check if the character is a letter or a digit if the character is a - // international character remap it to an ascii valid character - case UnicodeCategory.LowercaseLetter: - case UnicodeCategory.UppercaseLetter: - case UnicodeCategory.DecimalDigitNumber: - if (c < 128) - { - stringBuilder.Append(c); - } - else - { - stringBuilder.Append(RemapInternationalCharToAscii(c)); - } + for (var i = 0; i < stringLength; i++) + { + var c = normalizedString[i]; - prevdash = false; - trueLength = stringBuilder.Length; - break; + switch (CharUnicodeInfo.GetUnicodeCategory(c)) + { + // Check if the character is a letter or a digit if the character is a + // international character remap it to an ascii valid character + case UnicodeCategory.LowercaseLetter: + case UnicodeCategory.UppercaseLetter: + case UnicodeCategory.DecimalDigitNumber: + if (c < 128) + { + stringBuilder.Append(c); + } + else + { + stringBuilder.Append(RemapInternationalCharToAscii(c)); + } - // Check if the character is to be replaced by a hyphen but only if the last character wasn't - case UnicodeCategory.SpaceSeparator: - case UnicodeCategory.ConnectorPunctuation: - case UnicodeCategory.DashPunctuation: - case UnicodeCategory.OtherPunctuation: - case UnicodeCategory.MathSymbol: - if (!prevdash) - { - stringBuilder.Append('-'); - prevdash = true; - trueLength = stringBuilder.Length; - } - break; - } + prevdash = false; + trueLength = stringBuilder.Length; + break; - // If we are at max length, stop parsing - if (maxLength > 0 && trueLength >= maxLength) - { + // Check if the character is to be replaced by a hyphen but only if the last character wasn't + case UnicodeCategory.SpaceSeparator: + case UnicodeCategory.ConnectorPunctuation: + case UnicodeCategory.DashPunctuation: + case UnicodeCategory.OtherPunctuation: + case UnicodeCategory.MathSymbol: + if (!prevdash) + { + stringBuilder.Append('-'); + prevdash = true; + trueLength = stringBuilder.Length; + } break; - } } - // Trim excess hyphens - var result = stringBuilder.ToString().Trim('-'); - - // Remove any excess character to meet maxlength criteria - return maxLength <= 0 || result.Length <= maxLength ? result : result.Substring(0, maxLength); + // If we are at max length, stop parsing + if (maxLength > 0 && trueLength >= maxLength) + { + break; + } } - /// - /// Remaps international characters to ascii compatible ones - /// based of: https://meta.stackexchange.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696 - /// - /// Charcter to remap - /// Remapped character - private static string RemapInternationalCharToAscii(char c) - { - var value = c.ToString().ToLowerInvariant(); + // Trim excess hyphens + var result = stringBuilder.ToString().Trim('-'); - if ("àåáâäãåą".Contains(value)) - { - return "a"; - } - if ("èéêëę".Contains(value)) - { - return "e"; - } - if ("ìíîïı".Contains(value)) - { - return "i"; - } - if ("òóôõöøőð".Contains(value)) - { - return "o"; - } - if ("ùúûüŭů".Contains(value)) - { - return "u"; - } - if ("çćčĉ".Contains(value)) - { - return "c"; - } - if ("żźž".Contains(value)) - { - return "z"; - } - if ("śşšŝ".Contains(value)) - { - return "s"; - } - if ("ñń".Contains(value)) - { - return "n"; - } - if ("ýÿ".Contains(value)) - { - return "y"; - } - if ("ğĝ".Contains(value)) - { - return "g"; - } - if (c == 'ř') - { - return "r"; - } - if (c == 'ł') - { - return "l"; - } - if (c == 'đ') - { - return "d"; - } - if (c == 'ß') - { - return "ss"; - } - if (c == 'þ') - { - return "th"; - } - if (c == 'ĥ') - { - return "h"; - } - if (c == 'ĵ') - { - return "j"; - } + // Remove any excess character to meet maxlength criteria + return maxLength <= 0 || result.Length <= maxLength ? result : result.Substring(0, maxLength); + } + + /// + /// Remaps international characters to ascii compatible ones + /// based of: https://meta.stackexchange.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696 + /// + /// Charcter to remap + /// Remapped character + private static string RemapInternationalCharToAscii(char c) + { + var value = c.ToString().ToLowerInvariant(); - return ""; + if ("àåáâäãåą".Contains(value)) + { + return "a"; + } + if ("èéêëę".Contains(value)) + { + return "e"; + } + if ("ìíîïı".Contains(value)) + { + return "i"; + } + if ("òóôõöøőð".Contains(value)) + { + return "o"; + } + if ("ùúûüŭů".Contains(value)) + { + return "u"; + } + if ("çćčĉ".Contains(value)) + { + return "c"; + } + if ("żźž".Contains(value)) + { + return "z"; + } + if ("śşšŝ".Contains(value)) + { + return "s"; } + if ("ñń".Contains(value)) + { + return "n"; + } + if ("ýÿ".Contains(value)) + { + return "y"; + } + if ("ğĝ".Contains(value)) + { + return "g"; + } + if (c == 'ř') + { + return "r"; + } + if (c == 'ł') + { + return "l"; + } + if (c == 'đ') + { + return "d"; + } + if (c == 'ß') + { + return "ss"; + } + if (c == 'þ') + { + return "th"; + } + if (c == 'ĥ') + { + return "h"; + } + if (c == 'ĵ') + { + return "j"; + } + + return ""; } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.Application/Queries/ContextTypes/ContextTypeDto.cs b/backend/src/Equinor.ProjectExecutionPortal.Application/Queries/ContextTypes/ContextTypeDto.cs index e3db9cdd3..aa62bb817 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.Application/Queries/ContextTypes/ContextTypeDto.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.Application/Queries/ContextTypes/ContextTypeDto.cs @@ -1,10 +1,9 @@ using Equinor.ProjectExecutionPortal.Application.Infrastructure.Mappings; -namespace Equinor.ProjectExecutionPortal.Application.Queries.ContextTypes +namespace Equinor.ProjectExecutionPortal.Application.Queries.ContextTypes; + +public class ContextTypeDto : IMapFrom { - public class ContextTypeDto : IMapFrom - { - public string ContextTypeKey { get; set; } + public string ContextTypeKey { get; set; } - } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.Application/Queries/Portals/PortalOnboardedAppDto.cs b/backend/src/Equinor.ProjectExecutionPortal.Application/Queries/Portals/PortalOnboardedAppDto.cs index 6b3349c70..9e3df76ff 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.Application/Queries/Portals/PortalOnboardedAppDto.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.Application/Queries/Portals/PortalOnboardedAppDto.cs @@ -1,14 +1,13 @@ using Equinor.ProjectExecutionPortal.Application.Infrastructure.Mappings; using Equinor.ProjectExecutionPortal.Application.Queries.OnboardedApps; -namespace Equinor.ProjectExecutionPortal.Application.Queries.Portals +namespace Equinor.ProjectExecutionPortal.Application.Queries.Portals; + +public class PortalOnboardedAppDto : IMapFrom { - public class PortalOnboardedAppDto : IMapFrom - { - public OnboardedAppDto OnboardedApp { get; set; } - public List ContextIds { get; set; } = []; - public bool IsActive { get; set; } = false; - public bool IsGlobal { get; set; } - public bool IsContextual { get; set; } - } + public OnboardedAppDto OnboardedApp { get; set; } + public List ContextIds { get; set; } = []; + public bool IsActive { get; set; } = false; + public bool IsGlobal { get; set; } + public bool IsContextual { get; set; } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.Application/Services/AppService/AppService.cs b/backend/src/Equinor.ProjectExecutionPortal.Application/Services/AppService/AppService.cs index 31dd00428..ffaf7a9c6 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.Application/Services/AppService/AppService.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.Application/Services/AppService/AppService.cs @@ -2,49 +2,48 @@ using Equinor.ProjectExecutionPortal.Application.Services.FusionAppsService; using Fusion.Integration.Apps.Abstractions.Models; -namespace Equinor.ProjectExecutionPortal.Application.Services.AppService +namespace Equinor.ProjectExecutionPortal.Application.Services.AppService; + +public class AppService : IAppService { - public class AppService : IAppService + private readonly IFusionAppsService _fusionAppsService; + + public AppService(IFusionAppsService fusionAppsService) { - private readonly IFusionAppsService _fusionAppsService; + _fusionAppsService = fusionAppsService; + } - public AppService(IFusionAppsService fusionAppsService) - { - _fusionAppsService = fusionAppsService; - } + public async Task EnrichWithFusionAppData(OnboardedAppDto onboardedApp, CancellationToken cancellationToken) + { + var fusionApp = await _fusionAppsService.GetFusionApp(onboardedApp.AppKey); - public async Task EnrichWithFusionAppData(OnboardedAppDto onboardedApp, CancellationToken cancellationToken) + if (fusionApp != null) { - var fusionApp = await _fusionAppsService.GetFusionApp(onboardedApp.AppKey); + onboardedApp.SupplyWithFusionData(fusionApp); + } - if (fusionApp != null) - { - onboardedApp.SupplyWithFusionData(fusionApp); - } + return onboardedApp; + } - return onboardedApp; - } + public async Task> EnrichWithFusionAppData(IList onboardedApps, CancellationToken cancellationToken) + { + var fusionApps = await _fusionAppsService.GetFusionApps(); - public async Task> EnrichWithFusionAppData(IList onboardedApps, CancellationToken cancellationToken) + foreach (var onboardedApp in onboardedApps) { - var fusionApps = await _fusionAppsService.GetFusionApps(); + CombineAppWithFusionAppData(onboardedApp, fusionApps); + } - foreach (var onboardedApp in onboardedApps) - { - CombineAppWithFusionAppData(onboardedApp, fusionApps); - } + return onboardedApps; + } - return onboardedApps; - } + private static void CombineAppWithFusionAppData(OnboardedAppDto onboardedApp, IEnumerable fusionApps) + { + var fusionApp = fusionApps.FirstOrDefault(fusionApp => string.Equals(fusionApp.AppKey, onboardedApp.AppKey, StringComparison.CurrentCultureIgnoreCase)); - private static void CombineAppWithFusionAppData(OnboardedAppDto onboardedApp, IEnumerable fusionApps) + if (fusionApp != null) { - var fusionApp = fusionApps.FirstOrDefault(fusionApp => string.Equals(fusionApp.AppKey, onboardedApp.AppKey, StringComparison.CurrentCultureIgnoreCase)); - - if (fusionApp != null) - { - onboardedApp.SupplyWithFusionData(fusionApp); - } + onboardedApp.SupplyWithFusionData(fusionApp); } } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.Application/Services/PortalService/PortalService.cs b/backend/src/Equinor.ProjectExecutionPortal.Application/Services/PortalService/PortalService.cs index e249a2ae7..9f96bdc0e 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.Application/Services/PortalService/PortalService.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.Application/Services/PortalService/PortalService.cs @@ -3,97 +3,96 @@ using Equinor.ProjectExecutionPortal.Application.Queries.Portals; using Equinor.ProjectExecutionPortal.Domain.Entities; -namespace Equinor.ProjectExecutionPortal.Application.Services.PortalService +namespace Equinor.ProjectExecutionPortal.Application.Services.PortalService; + +public class PortalService : IPortalService { - public class PortalService : IPortalService - { - private readonly IMapper _mapper; + private readonly IMapper _mapper; - public PortalService(IMapper mapper) - { - _mapper = mapper; - } + public PortalService(IMapper mapper) + { + _mapper = mapper; + } - public IList CombinePortalAppsWithOnboardedApps(Portal portal, IList onboardedApps, CancellationToken cancellationToken) - { - var portalAppsDto = _mapper.Map, List>(GetDistinctPortalApps(portal.Apps.ToList())); + public IList CombinePortalAppsWithOnboardedApps(Portal portal, IList onboardedApps, CancellationToken cancellationToken) + { + var portalAppsDto = _mapper.Map, List>(GetDistinctPortalApps(portal.Apps.ToList())); - SetAppsAsActiveInPortal(portalAppsDto); + SetAppsAsActiveInPortal(portalAppsDto); - var onBoardedAppsNotActiveInPortal = GetOnBoardedAppsNotActiveInPortal(portal, onboardedApps); + var onBoardedAppsNotActiveInPortal = GetOnBoardedAppsNotActiveInPortal(portal, onboardedApps); - portalAppsDto.AddRange(onBoardedAppsNotActiveInPortal); + portalAppsDto.AddRange(onBoardedAppsNotActiveInPortal); - return portalAppsDto.OrderBy(x => x.OnboardedApp?.AppKey).ToList(); - } + return portalAppsDto.OrderBy(x => x.OnboardedApp?.AppKey).ToList(); + } - public async Task EnrichPortalAppWithContextIds(PortalOnboardedAppDto portalOnboardedAppDto, IList contextIds, CancellationToken cancellationToken) - { - portalOnboardedAppDto.ContextIds = contextIds.ToList(); + public async Task EnrichPortalAppWithContextIds(PortalOnboardedAppDto portalOnboardedAppDto, IList contextIds, CancellationToken cancellationToken) + { + portalOnboardedAppDto.ContextIds = contextIds.ToList(); - await Task.CompletedTask; + await Task.CompletedTask; - return portalOnboardedAppDto; - } + return portalOnboardedAppDto; + } - public PortalOnboardedAppDto GetPortalOnboardedAppNotActive(OnboardedApp onboardedApp, CancellationToken cancellationToken) + public PortalOnboardedAppDto GetPortalOnboardedAppNotActive(OnboardedApp onboardedApp, CancellationToken cancellationToken) + { + return new PortalOnboardedAppDto { - return new PortalOnboardedAppDto - { - OnboardedApp = _mapper.Map(onboardedApp), - IsActive = false - }; - } + OnboardedApp = _mapper.Map(onboardedApp), + IsActive = false + }; + } - public async Task SetAppAsActiveInPortal(PortalOnboardedAppDto app, CancellationToken cancellationToken) - { - app.IsActive = true; + public async Task SetAppAsActiveInPortal(PortalOnboardedAppDto app, CancellationToken cancellationToken) + { + app.IsActive = true; - await Task.CompletedTask; + await Task.CompletedTask; - return app; - } + return app; + } - private static void SetAppsAsActiveInPortal(IList apps) + private static void SetAppsAsActiveInPortal(IList apps) + { + foreach (var app in apps) { - foreach (var app in apps) - { - app.IsActive = true; - } + app.IsActive = true; } + } - private static List GetDistinctPortalApps(List portalApps) - { - var distinctPortalApps = portalApps.GroupBy(app => app.OnboardedApp.Id) - .Select(group => group.First()) - .ToList(); + private static List GetDistinctPortalApps(List portalApps) + { + var distinctPortalApps = portalApps.GroupBy(app => app.OnboardedApp.Id) + .Select(group => group.First()) + .ToList(); - return distinctPortalApps; - } + return distinctPortalApps; + } - private List GetOnBoardedAppsNotActiveInPortal(Portal portal, IList onboardedApps) - { - var onBoardedAppsNotActiveInPortal = IsContextualPortal(portal) ? - onboardedApps - .Where(onboardedApp => - portal.Apps.All(portalAppDto => portalAppDto.OnboardedApp.Id != onboardedApp.Id) && - (onboardedApp.ContextTypes.Count == 0 || - onboardedApp.ContextTypes.Any(m => portal.ContextTypes.Any(n => n.ContextTypeKey == m.ContextTypeKey)))) - .ToList() : - onboardedApps - .Where(onboardedApp => portal.Apps.All(portalAppDto => portalAppDto.OnboardedApp.Id != onboardedApp.Id)) - .ToList(); - - return onBoardedAppsNotActiveInPortal.Select(onBoardedApp => new PortalOnboardedAppDto() - { - OnboardedApp = _mapper.Map(onBoardedApp), - IsActive = false - }).ToList(); - } + private List GetOnBoardedAppsNotActiveInPortal(Portal portal, IList onboardedApps) + { + var onBoardedAppsNotActiveInPortal = IsContextualPortal(portal) ? + onboardedApps + .Where(onboardedApp => + portal.Apps.All(portalAppDto => portalAppDto.OnboardedApp.Id != onboardedApp.Id) && + (onboardedApp.ContextTypes.Count == 0 || + onboardedApp.ContextTypes.Any(m => portal.ContextTypes.Any(n => n.ContextTypeKey == m.ContextTypeKey)))) + .ToList() : + onboardedApps + .Where(onboardedApp => portal.Apps.All(portalAppDto => portalAppDto.OnboardedApp.Id != onboardedApp.Id)) + .ToList(); - private static bool IsContextualPortal(Portal portal) + return onBoardedAppsNotActiveInPortal.Select(onBoardedApp => new PortalOnboardedAppDto() { - return portal.ContextTypes.Count > 0; - } + OnboardedApp = _mapper.Map(onBoardedApp), + IsActive = false + }).ToList(); + } + + private static bool IsContextualPortal(Portal portal) + { + return portal.ContextTypes.Count > 0; } } \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.Domain/Infrastructure/QueryBase.cs b/backend/src/Equinor.ProjectExecutionPortal.Domain/Infrastructure/QueryBase.cs index e8ae4bff0..1312f8a6c 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.Domain/Infrastructure/QueryBase.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.Domain/Infrastructure/QueryBase.cs @@ -1,6 +1,5 @@ using MediatR; -namespace Equinor.ProjectExecutionPortal.Domain.Infrastructure -{ - public abstract class QueryBase : IRequest; -} +namespace Equinor.ProjectExecutionPortal.Domain.Infrastructure; + +public abstract class QueryBase : IRequest; \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/Controllers/OnboardedAppController.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/Controllers/OnboardedAppController.cs index 9bba960be..365a9f809 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/Controllers/OnboardedAppController.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/Controllers/OnboardedAppController.cs @@ -9,194 +9,193 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace Equinor.ProjectExecutionPortal.WebApi.Controllers +namespace Equinor.ProjectExecutionPortal.WebApi.Controllers; + +[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] +[ApiVersion("0.1")] +[Route("api/onboarded-apps")] +public class OnboardedAppController : ApiControllerBase { - [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] - [ApiVersion("0.1")] - [Route("api/onboarded-apps")] - public class OnboardedAppController : ApiControllerBase + [HttpGet("")] + public async Task>> OnboardedApps() + { + var onboardedAppsDto = await Mediator.Send(new GetOnboardedAppsQuery()); + + return Ok(onboardedAppsDto.Select(onboardedAppDto => new ApiOnboardedApp(onboardedAppDto)).ToList()); + } + + [HttpGet("{appKey}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task> OnboardedApp([FromRoute] string appKey) { - [HttpGet("")] - public async Task>> OnboardedApps() - { - var onboardedAppsDto = await Mediator.Send(new GetOnboardedAppsQuery()); - - return Ok(onboardedAppsDto.Select(onboardedAppDto => new ApiOnboardedApp(onboardedAppDto)).ToList()); - } - - [HttpGet("{appKey}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task> OnboardedApp([FromRoute] string appKey) - { - var onboardedAppDto = await Mediator.Send(new GetOnboardedAppQuery(appKey)); - - if (onboardedAppDto == null) - { - return FusionApiError.NotFound(appKey, "Could not find onboarded app"); - } - - return new ApiOnboardedAppExpanded(onboardedAppDto); - } - - [HttpPost("")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status201Created)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> OnboardApp([FromBody] ApiOnboardAppRequest request) - { - try - { - await Mediator.Send(request.ToCommand()); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(null, ex.Message); - } - catch (InvalidActionException ex) - { - return FusionApiError.ResourceExists(request.AppKey, ex.Message, ex); - } - catch (InvalidOperationException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while onboarding app"); - } - - return Created(); - } - - [HttpPut("{appKey}")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> UpdateOnboardedApp([FromRoute] string appKey, [FromBody] ApiUpdateOnboardedAppRequest request) - { - try - { - await Mediator.Send(request.ToCommand(appKey)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(appKey, ex.Message); - } - catch (InvalidOperationException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while updating the onboarded app"); - } - - return Ok(); - } - - [HttpDelete("{appKey}")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task RemoveOnboardedApp([FromRoute] string appKey) - { - var request = new ApiRemoveOnboardedAppRequest { AppKey = appKey }; - - try - { - await Mediator.Send(request.ToCommand()); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(appKey, ex.Message); - } - catch (InvalidOperationException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while removing the onboarded app"); - } - - return Ok(); - } - - //ContextTypes - [HttpPost("{appKey}/context-type")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> AddContextType([FromRoute] string appKey, [FromBody] ApiAddContextTypeToOnboardedAppRequest request) - { - try - { - await Mediator.Send(request.ToCommand(appKey)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(appKey, ex.Message); - } - catch (InvalidOperationException ex) - { - return FusionApiError.ResourceExists(request.Type, ex.Message, ex); - } - catch (InvalidActionException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while adding context-type"); - } - - return Ok(); - } - - [HttpDelete("{appKey}/context-type/{contextType}")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task RemoveContextType([FromRoute] string appKey, [FromRoute] string contextType) - { - var request = new ApiRemoveOnboardedAppContextType(); - try - { - await Mediator.Send(request.ToCommand(appKey, contextType)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(appKey, ex.Message); - } - catch (InvalidActionException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while removing context-type"); - } - - return Ok(); + var onboardedAppDto = await Mediator.Send(new GetOnboardedAppQuery(appKey)); + + if (onboardedAppDto == null) + { + return FusionApiError.NotFound(appKey, "Could not find onboarded app"); + } + + return new ApiOnboardedAppExpanded(onboardedAppDto); + } + + [HttpPost("")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> OnboardApp([FromBody] ApiOnboardAppRequest request) + { + try + { + await Mediator.Send(request.ToCommand()); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(null, ex.Message); + } + catch (InvalidActionException ex) + { + return FusionApiError.ResourceExists(request.AppKey, ex.Message, ex); + } + catch (InvalidOperationException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while onboarding app"); + } + + return Created(); + } + + [HttpPut("{appKey}")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> UpdateOnboardedApp([FromRoute] string appKey, [FromBody] ApiUpdateOnboardedAppRequest request) + { + try + { + await Mediator.Send(request.ToCommand(appKey)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(appKey, ex.Message); + } + catch (InvalidOperationException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while updating the onboarded app"); + } + + return Ok(); + } + + [HttpDelete("{appKey}")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task RemoveOnboardedApp([FromRoute] string appKey) + { + var request = new ApiRemoveOnboardedAppRequest { AppKey = appKey }; + + try + { + await Mediator.Send(request.ToCommand()); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(appKey, ex.Message); + } + catch (InvalidOperationException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while removing the onboarded app"); + } + + return Ok(); + } + + //ContextTypes + [HttpPost("{appKey}/context-type")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> AddContextType([FromRoute] string appKey, [FromBody] ApiAddContextTypeToOnboardedAppRequest request) + { + try + { + await Mediator.Send(request.ToCommand(appKey)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(appKey, ex.Message); + } + catch (InvalidOperationException ex) + { + return FusionApiError.ResourceExists(request.Type, ex.Message, ex); + } + catch (InvalidActionException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while adding context-type"); + } + + return Ok(); + } + + [HttpDelete("{appKey}/context-type/{contextType}")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task RemoveContextType([FromRoute] string appKey, [FromRoute] string contextType) + { + var request = new ApiRemoveOnboardedAppContextType(); + try + { + await Mediator.Send(request.ToCommand(appKey, contextType)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(appKey, ex.Message); + } + catch (InvalidActionException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while removing context-type"); + } + + return Ok(); } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/Controllers/PortalController.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/Controllers/PortalController.cs index 90660d063..e7b6cdfa1 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/Controllers/PortalController.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/Controllers/PortalController.cs @@ -15,468 +15,467 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace Equinor.ProjectExecutionPortal.WebApi.Controllers +namespace Equinor.ProjectExecutionPortal.WebApi.Controllers; + +[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] +[ApiVersion("0.1")] +[Route("api/portals")] +public class PortalController : ApiControllerBase { - [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] - [ApiVersion("0.1")] - [Route("api/portals")] - public class PortalController : ApiControllerBase + [HttpGet("")] + public async Task>> Portals() + { + var portalDtos = await Mediator.Send(new GetPortalsQuery()); + + return Ok(portalDtos.Select(dto => new ApiPortal(dto)).ToList()); + } + + [HttpGet("{portalId:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task> Portal([FromRoute] Guid portalId) + { + var portalWithAppsDto = await Mediator.Send(new GetPortalQuery(portalId)); + + if (portalWithAppsDto == null) + { + return FusionApiError.NotFound(portalId, "Could not find portal"); + } + + return Ok(new ApiPortal(portalWithAppsDto)); + } + + [HttpPost("")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> CreatePortal([FromBody] ApiCreatePortalRequest request) + { + try + { + await Mediator.Send(request.ToCommand()); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(request.Name, ex.Message); + } + catch (InvalidActionException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while creating portal"); + } + + return Ok(); + } + + [HttpPut("{portalId:guid}")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> UpdatePortal([FromRoute] Guid portalId, [FromBody] ApiUpdatePortalRequest request) + { + try + { + await Mediator.Send(request.ToCommand(portalId)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while updating portal"); + } + + return Ok(); + } + + [HttpGet("{portalId:guid}/configuration")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task> PortalConfiguration([FromRoute] Guid portalId) + { + var portalConfigurationDto = await Mediator.Send(new GetPortalConfigurationQuery(portalId)); + + if (portalConfigurationDto == null) + { + return FusionApiError.NotFound(portalId, "Could not find portal"); + } + + return Ok(new ApiPortalConfiguration(portalConfigurationDto)); + } + + [HttpPut("{portalId:guid}/configuration")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> UpdatePortalConfiguration([FromRoute] Guid portalId, [FromBody] ApiUpdatePortalConfigurationRequest request) + { + try + { + await Mediator.Send(request.ToCommand(portalId)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while updating portal configuration"); + } + + return Ok(); + } + + [HttpDelete("{portalId:guid}")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task RemovePortalApp([FromRoute] Guid portalId) + { + var request = new ApiRemovePortalRequest(); + + try + { + await Mediator.Send(request.ToCommand(portalId)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (InvalidOperationException ex) + { + return FusionApiError.Forbidden(ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while removing portal"); + } + + return Ok(); + } + + // Onboarded Apps + + [HttpGet("{portalId:guid}/onboarded-apps")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task>> PortalOnboardedApps([FromRoute] Guid portalId) + { + var portalOnboardedAppsDto = await Mediator.Send(new GetPortalOnboardedAppsQuery(portalId)); + + if (!portalOnboardedAppsDto.Any()) + { + return FusionApiError.NotFound(portalId, "Could not find portal with id"); + } + + return Ok(portalOnboardedAppsDto.Select(onboardedAppDto => new ApiPortalOnboardedApp(onboardedAppDto)).ToList()); + } + + [HttpGet("{portalId:guid}/onboarded-apps/{appKey}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task> PortalOnboardedApp([FromRoute] Guid portalId, string appKey) { - [HttpGet("")] - public async Task>> Portals() - { - var portalDtos = await Mediator.Send(new GetPortalsQuery()); - - return Ok(portalDtos.Select(dto => new ApiPortal(dto)).ToList()); - } - - [HttpGet("{portalId:guid}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task> Portal([FromRoute] Guid portalId) - { - var portalWithAppsDto = await Mediator.Send(new GetPortalQuery(portalId)); - - if (portalWithAppsDto == null) - { - return FusionApiError.NotFound(portalId, "Could not find portal"); - } - - return Ok(new ApiPortal(portalWithAppsDto)); - } - - [HttpPost("")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> CreatePortal([FromBody] ApiCreatePortalRequest request) - { - try - { - await Mediator.Send(request.ToCommand()); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(request.Name, ex.Message); - } - catch (InvalidActionException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while creating portal"); - } - - return Ok(); - } - - [HttpPut("{portalId:guid}")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> UpdatePortal([FromRoute] Guid portalId, [FromBody] ApiUpdatePortalRequest request) - { - try - { - await Mediator.Send(request.ToCommand(portalId)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while updating portal"); - } - - return Ok(); - } - - [HttpGet("{portalId:guid}/configuration")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task> PortalConfiguration([FromRoute] Guid portalId) - { - var portalConfigurationDto = await Mediator.Send(new GetPortalConfigurationQuery(portalId)); - - if (portalConfigurationDto == null) - { - return FusionApiError.NotFound(portalId, "Could not find portal"); - } - - return Ok(new ApiPortalConfiguration(portalConfigurationDto)); - } - - [HttpPut("{portalId:guid}/configuration")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> UpdatePortalConfiguration([FromRoute] Guid portalId, [FromBody] ApiUpdatePortalConfigurationRequest request) - { - try - { - await Mediator.Send(request.ToCommand(portalId)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while updating portal configuration"); - } - - return Ok(); - } - - [HttpDelete("{portalId:guid}")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task RemovePortalApp([FromRoute] Guid portalId) - { - var request = new ApiRemovePortalRequest(); - - try - { - await Mediator.Send(request.ToCommand(portalId)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (InvalidOperationException ex) - { - return FusionApiError.Forbidden(ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while removing portal"); - } - - return Ok(); - } - - // Onboarded Apps - - [HttpGet("{portalId:guid}/onboarded-apps")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task>> PortalOnboardedApps([FromRoute] Guid portalId) - { - var portalOnboardedAppsDto = await Mediator.Send(new GetPortalOnboardedAppsQuery(portalId)); - - if (!portalOnboardedAppsDto.Any()) - { - return FusionApiError.NotFound(portalId, "Could not find portal with id"); - } - - return Ok(portalOnboardedAppsDto.Select(onboardedAppDto => new ApiPortalOnboardedApp(onboardedAppDto)).ToList()); - } - - [HttpGet("{portalId:guid}/onboarded-apps/{appKey}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task> PortalOnboardedApp([FromRoute] Guid portalId, string appKey) - { - var portalOnboardedAppDto = await Mediator.Send(new GetPortalOnboardedAppQuery(portalId, appKey)); - - if (portalOnboardedAppDto == null) - { - return FusionApiError.NotFound(portalId, "Could not find portal with id or appkey is invalid"); - } - - return new ApiPortalOnboardedApp(portalOnboardedAppDto); - } - - // App Keys - - // TODO: Rename to /apps - [HttpGet("{portalId:guid}/appkeys")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task>> PortalAppKeys([FromRoute] Guid portalId) - { - try - { - var portalGlobalAppKeys = await Mediator.Send(new GetGlobalAppKeysForPortalQuery(portalId)); - - return Ok(portalGlobalAppKeys); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred"); - } - } - - // TODO Rename to /apps - [HttpGet("{portalId:guid}/contexts/{contextId:guid}/appkeys")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task>> PortalAppKeys([FromRoute] Guid portalId, [FromRoute] Guid contextId) - { - try - { - var portalContextualAppKeys = await Mediator.Send(new GetContextualAndGlobalAppKeysByPortalAndContextQuery(portalId, contextId)); - - return Ok(portalContextualAppKeys); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred"); - } - } - - // Apps - - // TODO: Remove - [HttpGet("{portalId:guid}/apps")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task>> PortalApps([FromRoute] Guid portalId) - { - try - { - var portalAppsDto = await Mediator.Send(new GetGlobalAppsForPortalQuery(portalId)); - - return Ok(portalAppsDto.Select(portalAppDto => new ApiPortalApp(portalAppDto)).ToList()); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred"); - } - } - - // TODO: Remove - [HttpGet("{portalId:guid}/contexts/{contextId:guid}/apps")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task>> PortalApps([FromRoute] Guid portalId, [FromRoute] Guid contextId) - { - try - { - var portalAppsDto = await Mediator.Send(new GetContextualAndGlobalAppsByPortalAndContextQuery(portalId, contextId)); - - return Ok(portalAppsDto.Select(portalAppDto => new ApiPortalApp(portalAppDto)).ToList()); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred"); - } - } - - [HttpPost("{portalId:guid}/apps")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> AddPortalApp([FromRoute] Guid portalId, [FromBody] ApiAddGlobalAppToPortalRequest request) - { - try - { - await Mediator.Send(request.ToCommand(portalId)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (InvalidActionException ex) - { - return FusionApiError.ResourceExists(request.AppKey, ex.Message, ex); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while adding portal app"); - } - - return Ok(); - } - - [HttpPost("{portalId:guid}/contexts/{contextId:guid}/apps")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> AddPortalApp([FromRoute] Guid portalId, Guid contextId, [FromBody] ApiAddContextAppToPortalRequest request) - { - try - { - await Mediator.Send(request.ToCommand(portalId, contextId)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (InvalidOperationException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (InvalidActionException ex) - { - return FusionApiError.ResourceExists(request.AppKey, ex.Message, ex); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while adding portal app"); - } - - return Ok(); - } - - [HttpDelete("{portalId:guid}/apps/{appKey}")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task RemovePortalApp([FromRoute] Guid portalId, [FromRoute] string appKey) - { - var request = new ApiRemovePortalAppRequest(); - - try - { - await Mediator.Send(request.ToCommand(portalId, appKey)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while removing portal app"); - } - - return Ok(); - } - - [HttpDelete("{portalId:guid}/contexts/{contextId:guid}/apps/{appKey}")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task RemovePortalApp([FromRoute] Guid portalId, Guid contextId, [FromRoute] string appKey) - { - var request = new ApiRemovePortalAppRequest(); - - try - { - await Mediator.Send(request.ToCommand(portalId, contextId, appKey)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while removing portal app"); - } - - return Ok(); - } - - // ContextTypes - [HttpPost("{portalId:guid}/context-type")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [Consumes(MediaTypeNames.Application.Json)] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task> AddContextType([FromRoute] Guid portalId, [FromBody] ApiAddContextTypeToPortalRequest request) - { - try - { - await Mediator.Send(request.ToCommand(portalId)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (InvalidActionException ex) - { - return FusionApiError.ResourceExists(request.Type, ex.Message, ex); - } - catch (InvalidOperationException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while adding portal app"); - } - - return Ok(); - } - - [HttpDelete("{portalId:guid}/context-type/{contextType}")] - [Authorize(Policy = Policies.ProjectPortal.Admin)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task RemoveContextType([FromRoute] Guid portalId, [FromRoute] string contextType) - { - var request = new ApiRemovePortalContextType(); - try - { - await Mediator.Send(request.ToCommand(portalId, contextType)); - } - catch (NotFoundException ex) - { - return FusionApiError.NotFound(portalId, ex.Message); - } - catch (InvalidActionException ex) - { - return FusionApiError.InvalidOperation("400", ex.Message); - } - catch (Exception) - { - return FusionApiError.InvalidOperation("500", "An error occurred while removing context-type"); - } - - return Ok(); + var portalOnboardedAppDto = await Mediator.Send(new GetPortalOnboardedAppQuery(portalId, appKey)); + + if (portalOnboardedAppDto == null) + { + return FusionApiError.NotFound(portalId, "Could not find portal with id or appkey is invalid"); + } + + return new ApiPortalOnboardedApp(portalOnboardedAppDto); + } + + // App Keys + + // TODO: Rename to /apps + [HttpGet("{portalId:guid}/appkeys")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task>> PortalAppKeys([FromRoute] Guid portalId) + { + try + { + var portalGlobalAppKeys = await Mediator.Send(new GetGlobalAppKeysForPortalQuery(portalId)); + + return Ok(portalGlobalAppKeys); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred"); + } + } + + // TODO Rename to /apps + [HttpGet("{portalId:guid}/contexts/{contextId:guid}/appkeys")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task>> PortalAppKeys([FromRoute] Guid portalId, [FromRoute] Guid contextId) + { + try + { + var portalContextualAppKeys = await Mediator.Send(new GetContextualAndGlobalAppKeysByPortalAndContextQuery(portalId, contextId)); + + return Ok(portalContextualAppKeys); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred"); } } -} + + // Apps + + // TODO: Remove + [HttpGet("{portalId:guid}/apps")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task>> PortalApps([FromRoute] Guid portalId) + { + try + { + var portalAppsDto = await Mediator.Send(new GetGlobalAppsForPortalQuery(portalId)); + + return Ok(portalAppsDto.Select(portalAppDto => new ApiPortalApp(portalAppDto)).ToList()); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred"); + } + } + + // TODO: Remove + [HttpGet("{portalId:guid}/contexts/{contextId:guid}/apps")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task>> PortalApps([FromRoute] Guid portalId, [FromRoute] Guid contextId) + { + try + { + var portalAppsDto = await Mediator.Send(new GetContextualAndGlobalAppsByPortalAndContextQuery(portalId, contextId)); + + return Ok(portalAppsDto.Select(portalAppDto => new ApiPortalApp(portalAppDto)).ToList()); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred"); + } + } + + [HttpPost("{portalId:guid}/apps")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> AddPortalApp([FromRoute] Guid portalId, [FromBody] ApiAddGlobalAppToPortalRequest request) + { + try + { + await Mediator.Send(request.ToCommand(portalId)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (InvalidActionException ex) + { + return FusionApiError.ResourceExists(request.AppKey, ex.Message, ex); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while adding portal app"); + } + + return Ok(); + } + + [HttpPost("{portalId:guid}/contexts/{contextId:guid}/apps")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> AddPortalApp([FromRoute] Guid portalId, Guid contextId, [FromBody] ApiAddContextAppToPortalRequest request) + { + try + { + await Mediator.Send(request.ToCommand(portalId, contextId)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (InvalidOperationException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); + } + catch (InvalidActionException ex) + { + return FusionApiError.ResourceExists(request.AppKey, ex.Message, ex); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while adding portal app"); + } + + return Ok(); + } + + [HttpDelete("{portalId:guid}/apps/{appKey}")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task RemovePortalApp([FromRoute] Guid portalId, [FromRoute] string appKey) + { + var request = new ApiRemovePortalAppRequest(); + + try + { + await Mediator.Send(request.ToCommand(portalId, appKey)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while removing portal app"); + } + + return Ok(); + } + + [HttpDelete("{portalId:guid}/contexts/{contextId:guid}/apps/{appKey}")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task RemovePortalApp([FromRoute] Guid portalId, Guid contextId, [FromRoute] string appKey) + { + var request = new ApiRemovePortalAppRequest(); + + try + { + await Mediator.Send(request.ToCommand(portalId, contextId, appKey)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while removing portal app"); + } + + return Ok(); + } + + // ContextTypes + [HttpPost("{portalId:guid}/context-type")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [Consumes(MediaTypeNames.Application.Json)] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task> AddContextType([FromRoute] Guid portalId, [FromBody] ApiAddContextTypeToPortalRequest request) + { + try + { + await Mediator.Send(request.ToCommand(portalId)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (InvalidActionException ex) + { + return FusionApiError.ResourceExists(request.Type, ex.Message, ex); + } + catch (InvalidOperationException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while adding portal app"); + } + + return Ok(); + } + + [HttpDelete("{portalId:guid}/context-type/{contextType}")] + [Authorize(Policy = Policies.ProjectPortal.Admin)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task RemoveContextType([FromRoute] Guid portalId, [FromRoute] string contextType) + { + var request = new ApiRemovePortalContextType(); + try + { + await Mediator.Send(request.ToCommand(portalId, contextType)); + } + catch (NotFoundException ex) + { + return FusionApiError.NotFound(portalId, ex.Message); + } + catch (InvalidActionException ex) + { + return FusionApiError.InvalidOperation("400", ex.Message); + } + catch (Exception) + { + return FusionApiError.InvalidOperation("500", "An error occurred while removing context-type"); + } + + return Ok(); + } +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiAddContextTypeRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiAddContextTypeRequest.cs index a5dc2236a..153022016 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiAddContextTypeRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiAddContextTypeRequest.cs @@ -1,26 +1,25 @@ using Equinor.ProjectExecutionPortal.Application.Commands.ContextTypes.AddContextType; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType; + +public class ApiAddContextTypeRequest { - public class ApiAddContextTypeRequest - { - public required string Type { get; init; } + public required string Type { get; init; } - public AddContextTypeCommand ToCommand() - { - return new AddContextTypeCommand(Type); - } + public AddContextTypeCommand ToCommand() + { + return new AddContextTypeCommand(Type); + } - public class ApiAddContextTypeRequestValidator : AbstractValidator + public class ApiAddContextTypeRequestValidator : AbstractValidator + { + public ApiAddContextTypeRequestValidator() { - public ApiAddContextTypeRequestValidator() - { - RuleFor(x => x.Type) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Type required"); - } + RuleFor(x => x.Type) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Type required"); } } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiContextType.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiContextType.cs index 4a39ab1ca..6500eb50c 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiContextType.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiContextType.cs @@ -1,17 +1,16 @@ using Equinor.ProjectExecutionPortal.Application.Queries.ContextTypes; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType -{ - public class ApiContextType - { - public ApiContextType() - { } +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType; - public ApiContextType(ContextTypeDto contextTypeDto) - { - Type = contextTypeDto.ContextTypeKey; - } +public class ApiContextType +{ + public ApiContextType() + { } - public string Type { get; set; } + public ApiContextType(ContextTypeDto contextTypeDto) + { + Type = contextTypeDto.ContextTypeKey; } -} + + public string Type { get; set; } +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiRemoveContextTypeRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiRemoveContextTypeRequest.cs index 793e0eb14..a300418e4 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiRemoveContextTypeRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/ContextType/ApiRemoveContextTypeRequest.cs @@ -1,26 +1,25 @@ using Equinor.ProjectExecutionPortal.Application.Commands.ContextTypes.RemoveContextType; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType; + +public class ApiRemoveContextTypeRequest { - public class ApiRemoveContextTypeRequest - { - public required string Type { get; init; } + public required string Type { get; init; } - public RemoveContextTypeCommand ToCommand() - { - return new RemoveContextTypeCommand(Type); - } + public RemoveContextTypeCommand ToCommand() + { + return new RemoveContextTypeCommand(Type); + } - public class ApiAddContextTypeRequestValidator : AbstractValidator + public class ApiAddContextTypeRequestValidator : AbstractValidator + { + public ApiAddContextTypeRequestValidator() { - public ApiAddContextTypeRequestValidator() - { - RuleFor(x => x.Type) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Type required"); - } + RuleFor(x => x.Type) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Type required"); } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/FusionApp/ApiFusionAppCategory.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/FusionApp/ApiFusionAppCategory.cs index 251444522..7412e8d54 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/FusionApp/ApiFusionAppCategory.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/FusionApp/ApiFusionAppCategory.cs @@ -1,27 +1,26 @@ using Fusion.Integration.Apps.Abstractions.Models; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.FusionApp -{ - public class ApiFusionAppCategory - { - public ApiFusionAppCategory() - { } +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.FusionApp; - public ApiFusionAppCategory(AppCategory fusionAppCategory) - { - Id = fusionAppCategory.Id; - Name = fusionAppCategory.Name; - DisplayName = fusionAppCategory.DisplayName; - Color = fusionAppCategory.Color; - DefaultIcon = fusionAppCategory.DefaultIcon; - SortOrder = fusionAppCategory.SortOrder; - } +public class ApiFusionAppCategory +{ + public ApiFusionAppCategory() + { } - public Guid Id { get; set; } - public string Name { get; set; } - public string DisplayName { get; set; } - public string Color { get; set; } - public string DefaultIcon { get; set; } - public short SortOrder { get; set; } + public ApiFusionAppCategory(AppCategory fusionAppCategory) + { + Id = fusionAppCategory.Id; + Name = fusionAppCategory.Name; + DisplayName = fusionAppCategory.DisplayName; + Color = fusionAppCategory.Color; + DefaultIcon = fusionAppCategory.DefaultIcon; + SortOrder = fusionAppCategory.SortOrder; } -} + + public Guid Id { get; set; } + public string Name { get; set; } + public string DisplayName { get; set; } + public string Color { get; set; } + public string DefaultIcon { get; set; } + public short SortOrder { get; set; } +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/FusionApp/ApiFusionAppVersion.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/FusionApp/ApiFusionAppVersion.cs index bff535c90..b5bfd6d6a 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/FusionApp/ApiFusionAppVersion.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/FusionApp/ApiFusionAppVersion.cs @@ -1,17 +1,16 @@ using Fusion.Integration.Apps.Abstractions.Models; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.FusionApp -{ - public class ApiFusionAppVersion - { - public ApiFusionAppVersion() - { } +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.FusionApp; - public ApiFusionAppVersion(AppVersion fusionAppVersion) - { - Version = fusionAppVersion.Version; - } +public class ApiFusionAppVersion +{ + public ApiFusionAppVersion() + { } - public string Version { get; set; } + public ApiFusionAppVersion(AppVersion fusionAppVersion) + { + Version = fusionAppVersion.Version; } -} + + public string Version { get; set; } +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiOnboardAppRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiOnboardAppRequest.cs index 6c38bb8c3..bae9bac8c 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiOnboardAppRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiOnboardAppRequest.cs @@ -1,27 +1,26 @@ using Equinor.ProjectExecutionPortal.Application.Commands.OnboardedApps.OnboardApp; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedApp +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedApp; + +public class ApiOnboardAppRequest { - public class ApiOnboardAppRequest - { - public required string AppKey { get; init; } - public required IList ContextTypes { get; init; } + public required string AppKey { get; init; } + public required IList ContextTypes { get; init; } - public OnboardAppCommand ToCommand() - { - return new OnboardAppCommand(AppKey, ContextTypes); - } + public OnboardAppCommand ToCommand() + { + return new OnboardAppCommand(AppKey, ContextTypes); + } - public class OnboardAppRequestValidator : AbstractValidator + public class OnboardAppRequestValidator : AbstractValidator + { + public OnboardAppRequestValidator() { - public OnboardAppRequestValidator() - { - RuleFor(x => x.AppKey) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("AppKey is required"); - } + RuleFor(x => x.AppKey) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("AppKey is required"); } } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiOnboardedApp.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiOnboardedApp.cs index ccac78277..a4067943a 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiOnboardedApp.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiOnboardedApp.cs @@ -1,28 +1,27 @@ using Equinor.ProjectExecutionPortal.Application.Queries.OnboardedApps; using Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedApp -{ - public class ApiOnboardedApp - { - public ApiOnboardedApp() - { } +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedApp; - public ApiOnboardedApp(OnboardedAppDto onboardedAppDto) - { - Id = onboardedAppDto.Id; - AppKey = onboardedAppDto.AppKey; - DisplayName = onboardedAppDto.AppInformation?.DisplayName; - Description = onboardedAppDto.AppInformation?.Description; - Contexts = onboardedAppDto.ContextTypes.Select(x => new ApiContextType(x)).ToList(); - ContextTypes = onboardedAppDto.ContextTypes.Select(x => x.ContextTypeKey).ToList(); - } +public class ApiOnboardedApp +{ + public ApiOnboardedApp() + { } - public Guid Id { get; set; } - public string AppKey { get; set; } - public string? DisplayName { get; set; } - public string? Description { get; set; } - public IList Contexts { get; set; } = new List(); - public IList ContextTypes { get; set; } = new List(); + public ApiOnboardedApp(OnboardedAppDto onboardedAppDto) + { + Id = onboardedAppDto.Id; + AppKey = onboardedAppDto.AppKey; + DisplayName = onboardedAppDto.AppInformation?.DisplayName; + Description = onboardedAppDto.AppInformation?.Description; + Contexts = onboardedAppDto.ContextTypes.Select(x => new ApiContextType(x)).ToList(); + ContextTypes = onboardedAppDto.ContextTypes.Select(x => x.ContextTypeKey).ToList(); } -} + + public Guid Id { get; set; } + public string AppKey { get; set; } + public string? DisplayName { get; set; } + public string? Description { get; set; } + public IList Contexts { get; set; } = new List(); + public IList ContextTypes { get; set; } = new List(); +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiRemoveOnboardedAppRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiRemoveOnboardedAppRequest.cs index c5b46a0dd..3f7a7dd7f 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiRemoveOnboardedAppRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiRemoveOnboardedAppRequest.cs @@ -1,25 +1,24 @@ using Equinor.ProjectExecutionPortal.Application.Commands.OnboardedApps.RemoveOnboardedApp; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedApp +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedApp; + +public class ApiRemoveOnboardedAppRequest { - public class ApiRemoveOnboardedAppRequest - { - public required string AppKey { get; init; } + public required string AppKey { get; init; } - public RemoveOnboardedAppCommand ToCommand() - { - return new RemoveOnboardedAppCommand(AppKey); - } + public RemoveOnboardedAppCommand ToCommand() + { + return new RemoveOnboardedAppCommand(AppKey); + } - public class RemoveOnboardedAppRequestValidator : AbstractValidator + public class RemoveOnboardedAppRequestValidator : AbstractValidator + { + public RemoveOnboardedAppRequestValidator() { - public RemoveOnboardedAppRequestValidator() - { - RuleFor(x => x.AppKey) - .NotEmpty() - .WithMessage("AppKey is required"); - } + RuleFor(x => x.AppKey) + .NotEmpty() + .WithMessage("AppKey is required"); } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiUpdateOnboardedAppRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiUpdateOnboardedAppRequest.cs index b852ed3f1..9625984f8 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiUpdateOnboardedAppRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedApp/ApiUpdateOnboardedAppRequest.cs @@ -1,23 +1,22 @@ using Equinor.ProjectExecutionPortal.Application.Commands.OnboardedApps.UpdateOnboardedApp; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedApp +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedApp; + +public class ApiUpdateOnboardedAppRequest { - public class ApiUpdateOnboardedAppRequest - { - public required IList ContextTypes { get; init; } + public required IList ContextTypes { get; init; } - public UpdateOnboardedAppCommand ToCommand(string appKey) - { - return new UpdateOnboardedAppCommand(appKey, ContextTypes); - } + public UpdateOnboardedAppCommand ToCommand(string appKey) + { + return new UpdateOnboardedAppCommand(appKey, ContextTypes); + } - public class ApiUpdateOnboardedAppRequestValidator : AbstractValidator + public class ApiUpdateOnboardedAppRequestValidator : AbstractValidator + { + public ApiUpdateOnboardedAppRequestValidator() { - public ApiUpdateOnboardedAppRequestValidator() - { - } } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedAppContextType/ApiAddContextTypeToOnboardedAppRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedAppContextType/ApiAddContextTypeToOnboardedAppRequest.cs index c89411ce2..f835af90e 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedAppContextType/ApiAddContextTypeToOnboardedAppRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedAppContextType/ApiAddContextTypeToOnboardedAppRequest.cs @@ -1,26 +1,25 @@ using Equinor.ProjectExecutionPortal.Application.Commands.OnboardedApps.AddContextTypeToOnboardedApp; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedAppContextType +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedAppContextType; + +public class ApiAddContextTypeToOnboardedAppRequest { - public class ApiAddContextTypeToOnboardedAppRequest - { - public required string Type { get; set; } + public required string Type { get; set; } - public AddContextTypeToOnboardedAppCommand ToCommand(string appKey) - { - return new AddContextTypeToOnboardedAppCommand(appKey, Type); - } + public AddContextTypeToOnboardedAppCommand ToCommand(string appKey) + { + return new AddContextTypeToOnboardedAppCommand(appKey, Type); + } - public class ApiAddContextTypeToOnboardedAppRequestValidator : AbstractValidator + public class ApiAddContextTypeToOnboardedAppRequestValidator : AbstractValidator + { + public ApiAddContextTypeToOnboardedAppRequestValidator() { - public ApiAddContextTypeToOnboardedAppRequestValidator() - { - RuleFor(x => x.Type) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Type required"); - } + RuleFor(x => x.Type) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Type required"); } } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedAppContextType/ApiRemoveOnboardedAppContextType.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedAppContextType/ApiRemoveOnboardedAppContextType.cs index ee77d0206..407346af5 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedAppContextType/ApiRemoveOnboardedAppContextType.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedAppContextType/ApiRemoveOnboardedAppContextType.cs @@ -1,12 +1,11 @@ using Equinor.ProjectExecutionPortal.Application.Commands.OnboardedApps.RemoveContextTypeFromOnboardedApp; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedAppContextType +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedAppContextType; + +public class ApiRemoveOnboardedAppContextType { - public class ApiRemoveOnboardedAppContextType + public RemoveContextTypeFromFromOnboardedAppCommand ToCommand(string appKey, string contextType) { - public RemoveContextTypeFromFromOnboardedAppCommand ToCommand(string appKey, string contextType) - { - return new RemoveContextTypeFromFromOnboardedAppCommand(appKey, contextType); - } + return new RemoveContextTypeFromFromOnboardedAppCommand(appKey, contextType); } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiOnboardedContext.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiOnboardedContext.cs index d9aad58e2..9b81379c9 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiOnboardedContext.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiOnboardedContext.cs @@ -1,26 +1,25 @@ using Equinor.ProjectExecutionPortal.Application.Queries.OnboardedContexts; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedContext -{ - public class ApiOnboardedContext - { - public ApiOnboardedContext() { } +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedContext; - public ApiOnboardedContext(OnboardedContextDto onboardedAppDto) - { - Id = onboardedAppDto.Id; - ExternalId = onboardedAppDto.ExternalId; - Type = onboardedAppDto.Type; - ContextId = onboardedAppDto.ContextId; - Description = onboardedAppDto.Description; - Title = onboardedAppDto.Title; - } +public class ApiOnboardedContext +{ + public ApiOnboardedContext() { } - public Guid Id { get; set; } - public string ExternalId { get; set; } = null!; - public string Type { get; set; } = null!; - public Guid ContextId { get; set; } - public string Title { get; set; } - public string? Description { get; set; } + public ApiOnboardedContext(OnboardedContextDto onboardedAppDto) + { + Id = onboardedAppDto.Id; + ExternalId = onboardedAppDto.ExternalId; + Type = onboardedAppDto.Type; + ContextId = onboardedAppDto.ContextId; + Description = onboardedAppDto.Description; + Title = onboardedAppDto.Title; } -} + + public Guid Id { get; set; } + public string ExternalId { get; set; } = null!; + public string Type { get; set; } = null!; + public Guid ContextId { get; set; } + public string Title { get; set; } + public string? Description { get; set; } +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiOnboardedContextRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiOnboardedContextRequest.cs index 453fa2f8d..e4f5de4d8 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiOnboardedContextRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiOnboardedContextRequest.cs @@ -1,33 +1,32 @@ using Equinor.ProjectExecutionPortal.Application.Commands.OnboardedContexts.OnboardContext; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedContext +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedContext; + +public class ApiOnboardContextRequest { - public class ApiOnboardContextRequest - { - public required string ExternalId { get; init; } - public required string Type { get; init; } - public string? Description { get; init; } + public required string ExternalId { get; init; } + public required string Type { get; init; } + public string? Description { get; init; } - public OnboardContextCommand ToCommand(string externalId, string type) - { - return new OnboardContextCommand(externalId, type, Description); - } + public OnboardContextCommand ToCommand(string externalId, string type) + { + return new OnboardContextCommand(externalId, type, Description); + } - public class OnboardContextRequestValidator : AbstractValidator + public class OnboardContextRequestValidator : AbstractValidator + { + public OnboardContextRequestValidator() { - public OnboardContextRequestValidator() - { - RuleFor(x => x.ExternalId) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("External Id is required"); + RuleFor(x => x.ExternalId) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("External Id is required"); - RuleFor(x => x.Type) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Context type is required"); - } + RuleFor(x => x.Type) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Context type is required"); } } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiRemoveOnboardedContextRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiRemoveOnboardedContextRequest.cs index 371ad839b..68c2702f4 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiRemoveOnboardedContextRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiRemoveOnboardedContextRequest.cs @@ -1,25 +1,24 @@ using Equinor.ProjectExecutionPortal.Application.Commands.OnboardedContexts.RemoveOnboardedContext; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedContext +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedContext; + +public class ApiRemoveOnboardedContextRequest { - public class ApiRemoveOnboardedContextRequest - { - public Guid Id { get; init; } + public Guid Id { get; init; } - public RemoveOnboardedContextCommand ToCommand() - { - return new RemoveOnboardedContextCommand(Id); - } + public RemoveOnboardedContextCommand ToCommand() + { + return new RemoveOnboardedContextCommand(Id); + } - public class RemoveOnboardedContextRequestValidator : AbstractValidator + public class RemoveOnboardedContextRequestValidator : AbstractValidator + { + public RemoveOnboardedContextRequestValidator() { - public RemoveOnboardedContextRequestValidator() - { - RuleFor(x => x.Id) - .NotEmpty() - .WithMessage("External Id is required"); - } + RuleFor(x => x.Id) + .NotEmpty() + .WithMessage("External Id is required"); } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiUpdateOnboardedContextRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiUpdateOnboardedContextRequest.cs index c4086c2a2..f1445134a 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiUpdateOnboardedContextRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/OnboardedContext/ApiUpdateOnboardedContextRequest.cs @@ -1,25 +1,24 @@ using Equinor.ProjectExecutionPortal.Application.Commands.OnboardedContexts.UpdateOnboardedContext; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedContext +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.OnboardedContext; + +public class ApiUpdateOnboardedContextRequest { - public class ApiUpdateOnboardedContextRequest - { - public string? Description { get; set; } + public string? Description { get; set; } - public UpdateOnboardedContextCommand ToCommand(Guid id) - { - return new UpdateOnboardedContextCommand(id, Description); - } + public UpdateOnboardedContextCommand ToCommand(Guid id) + { + return new UpdateOnboardedContextCommand(id, Description); + } - public class UpdateOnboardedContextRequestValidator : AbstractValidator + public class UpdateOnboardedContextRequestValidator : AbstractValidator + { + public UpdateOnboardedContextRequestValidator() { - public UpdateOnboardedContextRequestValidator() - { - RuleFor(x => x.Description) - .MaximumLength(Domain.Entities.OnboardedContext.DescriptionLengthMax) - .NotContainScriptTag(); - } + RuleFor(x => x.Description) + .MaximumLength(Domain.Entities.OnboardedContext.DescriptionLengthMax) + .NotContainScriptTag(); } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiCreatePortalRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiCreatePortalRequest.cs index 9a53c4c09..f225c8198 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiCreatePortalRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiCreatePortalRequest.cs @@ -1,46 +1,45 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.CreatePortal; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal; + +public class ApiCreatePortalRequest { - public class ApiCreatePortalRequest + public required string Name { get; init; } + public required string ShortName { get; init; } + public required string Subtext { get; init; } + public string? Description { get; init; } + public required string Icon { get; init; } + public required IList ContextTypes { get; init; } + + public CreatePortalCommand ToCommand() { - public required string Name { get; init; } - public required string ShortName { get; init; } - public required string Subtext { get; init; } - public string? Description { get; init; } - public required string Icon { get; init; } - public required IList ContextTypes { get; init; } - - public CreatePortalCommand ToCommand() - { - return new CreatePortalCommand(Name, ShortName, Subtext, Description, Icon, ContextTypes); - } + return new CreatePortalCommand(Name, ShortName, Subtext, Description, Icon, ContextTypes); + } - public class CreatePortalRequestValidator : AbstractValidator + public class CreatePortalRequestValidator : AbstractValidator + { + public CreatePortalRequestValidator() { - public CreatePortalRequestValidator() - { - RuleFor(x => x.Name) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("DisplayName required"); - - RuleFor(x => x.ShortName) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Short name required"); - - RuleFor(x => x.Subtext) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Sub text required"); - - RuleFor(x => x.Description) - .NotContainScriptTag() - .MaximumLength(Domain.Entities.Portal.DescriptionLengthMax); - - } + RuleFor(x => x.Name) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("DisplayName required"); + + RuleFor(x => x.ShortName) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Short name required"); + + RuleFor(x => x.Subtext) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Sub text required"); + + RuleFor(x => x.Description) + .NotContainScriptTag() + .MaximumLength(Domain.Entities.Portal.DescriptionLengthMax); + } } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiPortal.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiPortal.cs index fd1c25583..cd618113b 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiPortal.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiPortal.cs @@ -2,37 +2,36 @@ using Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType; using Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal -{ - public class ApiPortal - { - public ApiPortal() { } +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal; - public ApiPortal(PortalDto portalDto) - { - Id = portalDto.Id; - Key = portalDto.Key; - Name = portalDto.Name; - ShortName = portalDto.ShortName; - Subtext = portalDto.SubText; - Description = portalDto.Description; - Icon = portalDto.Icon; - Contexts = portalDto.ContextTypes.Select(x => new ApiContextType(x)).ToList(); - ContextTypes = portalDto.ContextTypes.Select(x => x.ContextTypeKey).ToList(); - Apps = portalDto.Apps.Select(x => new ApiPortalApp(x)).ToList(); - Configuration = portalDto.Configuration != null ? new ApiPortalConfiguration(portalDto.Configuration) : null; - } +public class ApiPortal +{ + public ApiPortal() { } - public Guid Id { get; set; } - public string Key { get; set; } = null!; - public string Name { get; set; } = null!; - public string ShortName { get; set; } = null!; - public string Subtext { get; set; } = null!; - public string? Description { get; set; } - public string Icon { get; set; } = null!; - public IList Contexts { get; set; } - public IList ContextTypes { get; set; } - public List Apps { get; set; } = null!; - public ApiPortalConfiguration? Configuration { get; set; } + public ApiPortal(PortalDto portalDto) + { + Id = portalDto.Id; + Key = portalDto.Key; + Name = portalDto.Name; + ShortName = portalDto.ShortName; + Subtext = portalDto.SubText; + Description = portalDto.Description; + Icon = portalDto.Icon; + Contexts = portalDto.ContextTypes.Select(x => new ApiContextType(x)).ToList(); + ContextTypes = portalDto.ContextTypes.Select(x => x.ContextTypeKey).ToList(); + Apps = portalDto.Apps.Select(x => new ApiPortalApp(x)).ToList(); + Configuration = portalDto.Configuration != null ? new ApiPortalConfiguration(portalDto.Configuration) : null; } -} + + public Guid Id { get; set; } + public string Key { get; set; } = null!; + public string Name { get; set; } = null!; + public string ShortName { get; set; } = null!; + public string Subtext { get; set; } = null!; + public string? Description { get; set; } + public string Icon { get; set; } = null!; + public IList Contexts { get; set; } + public IList ContextTypes { get; set; } + public List Apps { get; set; } = null!; + public ApiPortalConfiguration? Configuration { get; set; } +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiPortalConfiguration.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiPortalConfiguration.cs index 0bc6df7fb..8916e3055 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiPortalConfiguration.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiPortalConfiguration.cs @@ -1,20 +1,19 @@ using Equinor.ProjectExecutionPortal.Application.Queries.Portals; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal -{ - public class ApiPortalConfiguration - { - public ApiPortalConfiguration() { } +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal; - public ApiPortalConfiguration(PortalConfigurationDto portalConfigurationDto) - { - Router = portalConfigurationDto.Router; - Extension = portalConfigurationDto.Extension; - Environment = portalConfigurationDto.Environment; - } +public class ApiPortalConfiguration +{ + public ApiPortalConfiguration() { } - public string? Router { get; set; } - public string? Extension { get; set; } - public string? Environment { get; set; } + public ApiPortalConfiguration(PortalConfigurationDto portalConfigurationDto) + { + Router = portalConfigurationDto.Router; + Extension = portalConfigurationDto.Extension; + Environment = portalConfigurationDto.Environment; } -} + + public string? Router { get; set; } + public string? Extension { get; set; } + public string? Environment { get; set; } +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiRemovePortalRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiRemovePortalRequest.cs index 1562f516f..ad1526e8a 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiRemovePortalRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiRemovePortalRequest.cs @@ -1,13 +1,12 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.RemovePortal; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal; + +public class ApiRemovePortalRequest { - public class ApiRemovePortalRequest + public RemovePortalCommand ToCommand(Guid id) { - public RemovePortalCommand ToCommand(Guid id) - { - return new RemovePortalCommand(id); - } - + return new RemovePortalCommand(id); } -} + +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiUpdatePortalConfigurationRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiUpdatePortalConfigurationRequest.cs index e7fae398e..a256ad819 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiUpdatePortalConfigurationRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiUpdatePortalConfigurationRequest.cs @@ -1,35 +1,34 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.UpdatePortalConfiguration; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal; + +public class ApiUpdatePortalConfigurationRequest { - public class ApiUpdatePortalConfigurationRequest - { - public string? Router { get; init; } - public string? Extension { get; init; } - public string? Environment { get; init; } + public string? Router { get; init; } + public string? Extension { get; init; } + public string? Environment { get; init; } - public UpdatePortalConfigurationCommand ToCommand(Guid portalId) - { - return new UpdatePortalConfigurationCommand(portalId, Router, Extension, Environment); - } + public UpdatePortalConfigurationCommand ToCommand(Guid portalId) + { + return new UpdatePortalConfigurationCommand(portalId, Router, Extension, Environment); + } - public class UpdatePortalConfigurationValidator : AbstractValidator + public class UpdatePortalConfigurationValidator : AbstractValidator + { + public UpdatePortalConfigurationValidator() { - public UpdatePortalConfigurationValidator() - { - RuleFor(x => x.Router) - .NotContainScriptTag() - .MaximumLength(Domain.Entities.PortalConfiguration.RouterLengthMax); + RuleFor(x => x.Router) + .NotContainScriptTag() + .MaximumLength(Domain.Entities.PortalConfiguration.RouterLengthMax); - RuleFor(x => x.Extension) - .NotContainScriptTag() - .MaximumLength(Domain.Entities.PortalConfiguration.ExtensionLengthMax); + RuleFor(x => x.Extension) + .NotContainScriptTag() + .MaximumLength(Domain.Entities.PortalConfiguration.ExtensionLengthMax); - RuleFor(x => x.Environment) - .NotContainScriptTag() - .MaximumLength(Domain.Entities.PortalConfiguration.EnvironmentLengthMax); - } + RuleFor(x => x.Environment) + .NotContainScriptTag() + .MaximumLength(Domain.Entities.PortalConfiguration.EnvironmentLengthMax); } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiUpdatePortalRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiUpdatePortalRequest.cs index a4ad3747d..a337abea0 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiUpdatePortalRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/Portal/ApiUpdatePortalRequest.cs @@ -1,45 +1,44 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.UpdatePortal; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.Portal; + +public class ApiUpdatePortalRequest { - public class ApiUpdatePortalRequest - { - public required string Name { get; init; } - public required string ShortName { get; init; } - public required string Subtext { get; init; } - public string? Description { get; init; } - public required string Icon { get; init; } - public required IList ContextTypes { get; init; } + public required string Name { get; init; } + public required string ShortName { get; init; } + public required string Subtext { get; init; } + public string? Description { get; init; } + public required string Icon { get; init; } + public required IList ContextTypes { get; init; } - public UpdatePortalCommand ToCommand(Guid id) - { - return new UpdatePortalCommand(id, Name, ShortName, Subtext, Description, Icon, ContextTypes); - } + public UpdatePortalCommand ToCommand(Guid id) + { + return new UpdatePortalCommand(id, Name, ShortName, Subtext, Description, Icon, ContextTypes); + } - public class UpdatePortalRequestValidator : AbstractValidator + public class UpdatePortalRequestValidator : AbstractValidator + { + public UpdatePortalRequestValidator() { - public UpdatePortalRequestValidator() - { - RuleFor(x => x.Name) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("DisplayName required"); + RuleFor(x => x.Name) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("DisplayName required"); - RuleFor(x => x.ShortName) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Short name required"); + RuleFor(x => x.ShortName) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Short name required"); - RuleFor(x => x.Subtext) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Sub text required"); + RuleFor(x => x.Subtext) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Sub text required"); - RuleFor(x => x.Description) - .NotContainScriptTag() - .MaximumLength(Domain.Entities.Portal.DescriptionLengthMax); - } + RuleFor(x => x.Description) + .NotContainScriptTag() + .MaximumLength(Domain.Entities.Portal.DescriptionLengthMax); } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiAddContextAppToPortalRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiAddContextAppToPortalRequest.cs index 4db6e384b..bf1452115 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiAddContextAppToPortalRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiAddContextAppToPortalRequest.cs @@ -1,26 +1,25 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.AddContextAppToPortal; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp; + +public class ApiAddContextAppToPortalRequest { - public class ApiAddContextAppToPortalRequest - { - public required string AppKey { get; set; } + public required string AppKey { get; set; } - public AddContextAppToPortalCommand ToCommand(Guid portalId, Guid contextId) - { - return new AddContextAppToPortalCommand(portalId, contextId, AppKey); - } + public AddContextAppToPortalCommand ToCommand(Guid portalId, Guid contextId) + { + return new AddContextAppToPortalCommand(portalId, contextId, AppKey); + } - public class ApiAddContextAppToPortalRequestValidator : AbstractValidator + public class ApiAddContextAppToPortalRequestValidator : AbstractValidator + { + public ApiAddContextAppToPortalRequestValidator() { - public ApiAddContextAppToPortalRequestValidator() - { - RuleFor(x => x.AppKey) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("AppKey required"); - } + RuleFor(x => x.AppKey) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("AppKey required"); } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiAddGlobalAppToPortalRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiAddGlobalAppToPortalRequest.cs index 21c91c35b..07a2bfe95 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiAddGlobalAppToPortalRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiAddGlobalAppToPortalRequest.cs @@ -1,34 +1,33 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.AddGlobalAppToPortal; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp; + +public class ApiAddGlobalAppToPortalRequest { - public class ApiAddGlobalAppToPortalRequest - { - public required string AppKey { get; set; } + public required string AppKey { get; set; } - /// - /// Only for when adding global apps - /// When set to true, this will potentially remove the app from all contexts where it has previously been specifically set. - /// This is done to avoid conflict where we have both a global and contextual instance of the same app. - /// If set to false and the app already has been added to specific contexts, an error will be thrown. - /// - public bool RemoveAppForContexts { get; set; } + /// + /// Only for when adding global apps + /// When set to true, this will potentially remove the app from all contexts where it has previously been specifically set. + /// This is done to avoid conflict where we have both a global and contextual instance of the same app. + /// If set to false and the app already has been added to specific contexts, an error will be thrown. + /// + public bool RemoveAppForContexts { get; set; } - public AddGlobalAppToPortalCommand ToCommand(Guid portalId) - { - return new AddGlobalAppToPortalCommand(portalId, AppKey, RemoveAppForContexts); - } + public AddGlobalAppToPortalCommand ToCommand(Guid portalId) + { + return new AddGlobalAppToPortalCommand(portalId, AppKey, RemoveAppForContexts); + } - public class ApiAddGlobalAppToPortalRequestValidator : AbstractValidator + public class ApiAddGlobalAppToPortalRequestValidator : AbstractValidator + { + public ApiAddGlobalAppToPortalRequestValidator() { - public ApiAddGlobalAppToPortalRequestValidator() - { - RuleFor(x => x.AppKey) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("AppKey required"); - } + RuleFor(x => x.AppKey) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("AppKey required"); } } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiPortalApp.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiPortalApp.cs index 4fed22914..a5529e90e 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiPortalApp.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiPortalApp.cs @@ -2,24 +2,23 @@ using Equinor.ProjectExecutionPortal.WebApi.ViewModels.ContextType; using Equinor.ProjectExecutionPortal.WebApi.ViewModels.FusionApp; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp; + +// TODO: Should be removed +public class ApiPortalApp { - // TODO: Should be removed - public class ApiPortalApp + public ApiPortalApp() { - public ApiPortalApp() - { - - } - public ApiPortalApp(PortalAppDto portalAppDto) - { - AppKey = portalAppDto.OnboardedApp.AppKey; - ContextTypes = portalAppDto.OnboardedApp.ContextTypes.Select(x => new ApiContextType(x)).ToList(); - AppManifest = portalAppDto.OnboardedApp.AppInformation != null ? new ApiFusionApp(portalAppDto.OnboardedApp.AppInformation) : null; - } - public string AppKey { get; set; } - public IList ContextTypes { get; set; } - public ApiFusionApp? AppManifest { get; set; } } + public ApiPortalApp(PortalAppDto portalAppDto) + { + AppKey = portalAppDto.OnboardedApp.AppKey; + ContextTypes = portalAppDto.OnboardedApp.ContextTypes.Select(x => new ApiContextType(x)).ToList(); + AppManifest = portalAppDto.OnboardedApp.AppInformation != null ? new ApiFusionApp(portalAppDto.OnboardedApp.AppInformation) : null; + } + + public string AppKey { get; set; } + public IList ContextTypes { get; set; } + public ApiFusionApp? AppManifest { get; set; } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiPortalOnboardedApp.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiPortalOnboardedApp.cs index f1d510ec6..956ae0a9b 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiPortalOnboardedApp.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiPortalOnboardedApp.cs @@ -1,30 +1,29 @@ using Equinor.ProjectExecutionPortal.Application.Queries.Portals; using Equinor.ProjectExecutionPortal.WebApi.ViewModels.FusionApp; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp -{ - public class ApiPortalOnboardedApp - { - public ApiPortalOnboardedApp() - { } +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp; - public ApiPortalOnboardedApp(PortalOnboardedAppDto portalOnboardedAppDto) - { - AppKey = portalOnboardedAppDto.OnboardedApp.AppKey; - ContextTypes = portalOnboardedAppDto.OnboardedApp.ContextTypes.Select(x => x.ContextTypeKey).ToList(); - ContextIds = portalOnboardedAppDto.ContextIds; - IsActive = portalOnboardedAppDto.IsActive; - IsGlobal = portalOnboardedAppDto.IsGlobal; - IsContextual = portalOnboardedAppDto.IsContextual; - AppManifest = portalOnboardedAppDto.OnboardedApp.AppInformation != null ? new ApiFusionApp(portalOnboardedAppDto.OnboardedApp.AppInformation) : null; - } +public class ApiPortalOnboardedApp +{ + public ApiPortalOnboardedApp() + { } - public string AppKey { get; set; } - public IList ContextTypes { get; set; } - public IList ContextIds { get; set; } - public bool IsActive { get; set; } - public bool IsGlobal { get; set; } - public bool IsContextual { get; set; } - public ApiFusionApp? AppManifest { get; set; } + public ApiPortalOnboardedApp(PortalOnboardedAppDto portalOnboardedAppDto) + { + AppKey = portalOnboardedAppDto.OnboardedApp.AppKey; + ContextTypes = portalOnboardedAppDto.OnboardedApp.ContextTypes.Select(x => x.ContextTypeKey).ToList(); + ContextIds = portalOnboardedAppDto.ContextIds; + IsActive = portalOnboardedAppDto.IsActive; + IsGlobal = portalOnboardedAppDto.IsGlobal; + IsContextual = portalOnboardedAppDto.IsContextual; + AppManifest = portalOnboardedAppDto.OnboardedApp.AppInformation != null ? new ApiFusionApp(portalOnboardedAppDto.OnboardedApp.AppInformation) : null; } -} + + public string AppKey { get; set; } + public IList ContextTypes { get; set; } + public IList ContextIds { get; set; } + public bool IsActive { get; set; } + public bool IsGlobal { get; set; } + public bool IsContextual { get; set; } + public ApiFusionApp? AppManifest { get; set; } +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiRemovePortalAppRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiRemovePortalAppRequest.cs index 1eaf0027f..280db4416 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiRemovePortalAppRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalApp/ApiRemovePortalAppRequest.cs @@ -1,18 +1,17 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.RemoveContextAppFromPortal; using Equinor.ProjectExecutionPortal.Application.Commands.Portals.RemoveGlobalAppFromPortal; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp; + +public class ApiRemovePortalAppRequest { - public class ApiRemovePortalAppRequest + public RemoveContextAppFromPortalCommand ToCommand(Guid portalId, Guid contextId, string appKey) { - public RemoveContextAppFromPortalCommand ToCommand(Guid portalId, Guid contextId, string appKey) - { - return new RemoveContextAppFromPortalCommand(portalId, contextId, appKey); - } + return new RemoveContextAppFromPortalCommand(portalId, contextId, appKey); + } - public RemoveAppFromPortalCommand ToCommand(Guid portalId, string appKey) - { - return new RemoveAppFromPortalCommand(portalId, appKey); - } + public RemoveAppFromPortalCommand ToCommand(Guid portalId, string appKey) + { + return new RemoveAppFromPortalCommand(portalId, appKey); } -} +} \ No newline at end of file diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalContextType/ApiAddContextTypeToPortalRequest.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalContextType/ApiAddContextTypeToPortalRequest.cs index 49d49828d..a2c69893a 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalContextType/ApiAddContextTypeToPortalRequest.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalContextType/ApiAddContextTypeToPortalRequest.cs @@ -1,26 +1,25 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.AddContextTypeToPortal; using FluentValidation; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalContextType +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalContextType; + +public class ApiAddContextTypeToPortalRequest { - public class ApiAddContextTypeToPortalRequest - { - public required string Type { get; set; } + public required string Type { get; set; } - public AddContextTypeToPortalCommand ToCommand(Guid portalId) - { - return new AddContextTypeToPortalCommand(portalId, Type); - } + public AddContextTypeToPortalCommand ToCommand(Guid portalId) + { + return new AddContextTypeToPortalCommand(portalId, Type); + } - public class ApiAddContextTypeToPortalRequestValidator : AbstractValidator + public class ApiAddContextTypeToPortalRequestValidator : AbstractValidator + { + public ApiAddContextTypeToPortalRequestValidator() { - public ApiAddContextTypeToPortalRequestValidator() - { - RuleFor(x => x.Type) - .NotEmpty() - .NotContainScriptTag() - .WithMessage("Type required"); - } + RuleFor(x => x.Type) + .NotEmpty() + .NotContainScriptTag() + .WithMessage("Type required"); } } } diff --git a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalContextType/ApiRemovePortalContextType.cs b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalContextType/ApiRemovePortalContextType.cs index 89b45df13..d12cd5094 100644 --- a/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalContextType/ApiRemovePortalContextType.cs +++ b/backend/src/Equinor.ProjectExecutionPortal.WebApi/ViewModels/PortalContextType/ApiRemovePortalContextType.cs @@ -1,12 +1,11 @@ using Equinor.ProjectExecutionPortal.Application.Commands.Portals.RemoveContextTypeFromPortal; -namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalContextType +namespace Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalContextType; + +public class ApiRemovePortalContextType { - public class ApiRemovePortalContextType + public RemoveContextTypeFromPortalCommand ToCommand(Guid portalId, string contextType) { - public RemoveContextTypeFromPortalCommand ToCommand(Guid portalId, string contextType) - { - return new RemoveContextTypeFromPortalCommand(portalId, contextType); - } + return new RemoveContextTypeFromPortalCommand(portalId, contextType); } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/ContextTypeData.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/ContextTypeData.cs index 740bb0ecf..77c32d34a 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/ContextTypeData.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/ContextTypeData.cs @@ -1,25 +1,24 @@ using Equinor.ProjectExecutionPortal.Domain.Entities; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data; + +internal static class ContextTypeData { - internal static class ContextTypeData + public static class InitialDbSeedData { - public static class InitialDbSeedData - { - public static readonly ContextType ContextType1 = new(ValidContextTypes.ProjectMasterContextTypeKey); - public static readonly ContextType ContextType2 = new(ValidContextTypes.FacilityContextTypeKey); - } + public static readonly ContextType ContextType1 = new(ValidContextTypes.ProjectMasterContextTypeKey); + public static readonly ContextType ContextType2 = new(ValidContextTypes.FacilityContextTypeKey); + } - public static class ValidContextTypes - { - public const string ProjectMasterContextTypeKey = "ProjectMaster"; - public const string FacilityContextTypeKey = "Facility"; - public const string ContractContextTypeKey = "Contract"; - } + public static class ValidContextTypes + { + public const string ProjectMasterContextTypeKey = "ProjectMaster"; + public const string FacilityContextTypeKey = "Facility"; + public const string ContractContextTypeKey = "Contract"; + } - public static class InvalidContextTypes - { - public const string InvalidContextTypeKey = "SuperContext"; - } + public static class InvalidContextTypes + { + public const string InvalidContextTypeKey = "SuperContext"; } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/FusionAppApiData.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/FusionAppApiData.cs index 28ae3100f..de6e73202 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/FusionAppApiData.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/FusionAppApiData.cs @@ -1,73 +1,72 @@ using Fusion.Integration.Apps.Abstractions.Models; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data; + +internal static class FusionAppApiData { - internal static class FusionAppApiData + public static App MeetingsFusion => new() { - public static App MeetingsFusion => new() - { - AppKey = "meetings", - DisplayName = "Meetings", - Description = "Some description" - }; + AppKey = "meetings", + DisplayName = "Meetings", + Description = "Some description" + }; - public static App ReviewsFusion => new() - { - AppKey = "reviews", - DisplayName = "Reviews", - Description = "Some description" - }; + public static App ReviewsFusion => new() + { + AppKey = "reviews", + DisplayName = "Reviews", + Description = "Some description" + }; - public static App TasksFusion => new() - { - AppKey = "tasks", - DisplayName = "Tasks", - Description = "Some description" - }; + public static App TasksFusion => new() + { + AppKey = "tasks", + DisplayName = "Tasks", + Description = "Some description" + }; - public static App OneEquinorFusion => new() - { - AppKey = "one-equinor", - DisplayName = "One Equinor", - Description = "Some description" - }; + public static App OneEquinorFusion => new() + { + AppKey = "one-equinor", + DisplayName = "One Equinor", + Description = "Some description" + }; - public static App HandoverGardenFusion => new() - { - AppKey = "handover-garden", - DisplayName = "Handover Garden", - Description = "Some description" - }; + public static App HandoverGardenFusion => new() + { + AppKey = "handover-garden", + DisplayName = "Handover Garden", + Description = "Some description" + }; - public static App WorkOrderGardenFusion => new() - { - AppKey = "workorder-garden", - DisplayName = "Workorder Garden", - Description = "Some description" - }; + public static App WorkOrderGardenFusion => new() + { + AppKey = "workorder-garden", + DisplayName = "Workorder Garden", + Description = "Some description" + }; - public static App TestFusion => new() - { - AppKey = "test-app", - DisplayName = "A test app", - Description = "Some description" - }; + public static App TestFusion => new() + { + AppKey = "test-app", + DisplayName = "A test app", + Description = "Some description" + }; - public static App TestToBeOffboardedFusion => new() - { - AppKey = "app-to-be-offboarded", - DisplayName = "An app to be offboarded by onboarded app tests", - Description = "Some description" - }; + public static App TestToBeOffboardedFusion => new() + { + AppKey = "app-to-be-offboarded", + DisplayName = "An app to be offboarded by onboarded app tests", + Description = "Some description" + }; - public static App NonExistentApp => new() - { - AppKey = "i-do-not-exist-in-fusion", - DisplayName = "i-do-not-exist-in-fusion", - Description = "i-do-not-exist-in-fusion" - }; + public static App NonExistentApp => new() + { + AppKey = "i-do-not-exist-in-fusion", + DisplayName = "i-do-not-exist-in-fusion", + Description = "i-do-not-exist-in-fusion" + }; - public static List ValidFusionApps => - [MeetingsFusion, ReviewsFusion, TasksFusion, OneEquinorFusion, HandoverGardenFusion, WorkOrderGardenFusion, TestFusion, TestToBeOffboardedFusion]; - } -} + public static List ValidFusionApps => + [MeetingsFusion, ReviewsFusion, TasksFusion, OneEquinorFusion, HandoverGardenFusion, WorkOrderGardenFusion, TestFusion, TestToBeOffboardedFusion]; +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/FusionContextApiData.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/FusionContextApiData.cs index 86d0a29f6..f12462d53 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/FusionContextApiData.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/FusionContextApiData.cs @@ -1,51 +1,50 @@ using Fusion.Integration; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data; + +internal static class FusionContextApiData { - internal static class FusionContextApiData - { - public const string JcaContextExternalId = "fc5ffcbc-392f-4d7e-bb14-79a006579337"; - public static Guid JcaContextId = new("94dd5f4d-17f1-4312-bf75-ad75f4d9572c"); - public const string OgpContextExternalId = "91dd6653-a364-40c7-af26-7af516d66c42"; - public static Guid OgpContextId = new("ce31b83a-b6cd-4267-89f3-db308edf721e"); - public const string MongstadContextExternalId = "09206ca3-02ac-4c65-adbf-caa7b66364ea"; - public static Guid MongstadContextId = new("4CB78175-46CF-41A3-58DB-08DC74C80D40"); - public const string InvalidContextExternalId = "11111111-1111-1111-1111-111111111111"; - public static Guid InvalidContextId = new("11111111-1111-1111-1111-111111111111"); + public const string JcaContextExternalId = "fc5ffcbc-392f-4d7e-bb14-79a006579337"; + public static Guid JcaContextId = new("94dd5f4d-17f1-4312-bf75-ad75f4d9572c"); + public const string OgpContextExternalId = "91dd6653-a364-40c7-af26-7af516d66c42"; + public static Guid OgpContextId = new("ce31b83a-b6cd-4267-89f3-db308edf721e"); + public const string MongstadContextExternalId = "09206ca3-02ac-4c65-adbf-caa7b66364ea"; + public static Guid MongstadContextId = new("4CB78175-46CF-41A3-58DB-08DC74C80D40"); + public const string InvalidContextExternalId = "11111111-1111-1111-1111-111111111111"; + public static Guid InvalidContextId = new("11111111-1111-1111-1111-111111111111"); - public static FusionContext JcaFusionContext => new() - { - Id = JcaContextId, - IsActive = true, - ExternalId = JcaContextExternalId, - Title = "Johan Castberg", - Type = FusionContextType.ProjectMaster, - Value = null!, - Source = null - }; + public static FusionContext JcaFusionContext => new() + { + Id = JcaContextId, + IsActive = true, + ExternalId = JcaContextExternalId, + Title = "Johan Castberg", + Type = FusionContextType.ProjectMaster, + Value = null!, + Source = null + }; - public static FusionContext OgpFusionContext => new() - { - Id = OgpContextId, - IsActive = true, - ExternalId = OgpContextExternalId, - Title = "Oseberg", - Type = FusionContextType.ProjectMaster, - Value = null!, - Source = null - }; + public static FusionContext OgpFusionContext => new() + { + Id = OgpContextId, + IsActive = true, + ExternalId = OgpContextExternalId, + Title = "Oseberg", + Type = FusionContextType.ProjectMaster, + Value = null!, + Source = null + }; - public static FusionContext MongstadFusionContext => new() - { - Id = MongstadContextId, - IsActive = true, - ExternalId = MongstadContextExternalId, - Title = "Mongstad WWTP", - Type = FusionContextType.ProjectMaster, - Value = null!, - Source = null - }; + public static FusionContext MongstadFusionContext => new() + { + Id = MongstadContextId, + IsActive = true, + ExternalId = MongstadContextExternalId, + Title = "Mongstad WWTP", + Type = FusionContextType.ProjectMaster, + Value = null!, + Source = null + }; - public static List ValidFusionContexts => [JcaFusionContext, OgpFusionContext, MongstadFusionContext]; - } -} + public static List ValidFusionContexts => [JcaFusionContext, OgpFusionContext, MongstadFusionContext]; +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/OnboardedAppData.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/OnboardedAppData.cs index f86bf7b4d..aba32de5c 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/OnboardedAppData.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/OnboardedAppData.cs @@ -1,17 +1,16 @@ using Equinor.ProjectExecutionPortal.Domain.Entities; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data; + +internal static class OnboardedAppData { - internal static class OnboardedAppData + public static class InitialDbSeedData { - public static class InitialDbSeedData - { - public static readonly OnboardedApp MeetingsApp = new("meetings"); - public static readonly OnboardedApp ReviewsApp = new("reviews"); - public static readonly OnboardedApp TasksApp = new("tasks"); - public static readonly OnboardedApp OrgChartApp = new("one-equinor"); - public static readonly OnboardedApp HandoverGardenApp = new("handover-garden"); - public static readonly OnboardedApp WorkOrderGardenApp = new("workorder-garden"); - } + public static readonly OnboardedApp MeetingsApp = new("meetings"); + public static readonly OnboardedApp ReviewsApp = new("reviews"); + public static readonly OnboardedApp TasksApp = new("tasks"); + public static readonly OnboardedApp OrgChartApp = new("one-equinor"); + public static readonly OnboardedApp HandoverGardenApp = new("handover-garden"); + public static readonly OnboardedApp WorkOrderGardenApp = new("workorder-garden"); } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/OnboardedContextData.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/OnboardedContextData.cs index 197efe1d0..b83a1475e 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/OnboardedContextData.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/OnboardedContextData.cs @@ -1,13 +1,12 @@ using Equinor.ProjectExecutionPortal.Domain.Entities; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data; + +internal static class OnboardedContextData { - internal static class OnboardedContextData + public static class InitialDbSeedData { - public static class InitialDbSeedData - { - public static readonly OnboardedContext JcaContext = new(FusionContextApiData.JcaContextExternalId, ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey, "desc"); - public static readonly OnboardedContext OgpContext = new(FusionContextApiData.OgpContextExternalId, ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey, "desc"); - } + public static readonly OnboardedContext JcaContext = new(FusionContextApiData.JcaContextExternalId, ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey, "desc"); + public static readonly OnboardedContext OgpContext = new(FusionContextApiData.OgpContextExternalId, ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey, "desc"); } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/PortalConfigurationData.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/PortalConfigurationData.cs index c423f4a9c..915451e77 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/PortalConfigurationData.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/PortalConfigurationData.cs @@ -1,16 +1,15 @@ using Equinor.ProjectExecutionPortal.Domain.Entities; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data; + +internal static class PortalConfigurationData { - internal static class PortalConfigurationData + public static class InitialDbSeedData { - public static class InitialDbSeedData - { - public static readonly PortalConfiguration GenericPortalConfiguration = new( - "routerConfig", - "extensionConfig", - "environmentConfig" - ); - } + public static readonly PortalConfiguration GenericPortalConfiguration = new( + "routerConfig", + "extensionConfig", + "environmentConfig" + ); } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/PortalData.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/PortalData.cs index 383ef8930..d24952dff 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/PortalData.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Data/PortalData.cs @@ -1,27 +1,26 @@ using Equinor.ProjectExecutionPortal.Domain.Entities; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Data; + +internal static class PortalData { - internal static class PortalData + public static class InitialDbSeedData { - public static class InitialDbSeedData - { - public static readonly Portal PortfolioManagement = new( - "portfolio-management", - "Portfolio Management", - "< DG 3", - "Here you can find all the tools that you need", - "A description", - "" - ); + public static readonly Portal PortfolioManagement = new( + "portfolio-management", + "Portfolio Management", + "< DG 3", + "Here you can find all the tools that you need", + "A description", + "" + ); - public static readonly Portal ProjectExecution = new("project-execution", - "Project Execution", - "DG 3 - DG 4", - "Go to this phase to work with projects that are beyond DG3", - "A description", - "" - ); - } + public static readonly Portal ProjectExecution = new("project-execution", + "Project Execution", + "DG 3 - DG 4", + "Go to this phase to work with projects that are beyond DG3", + "A description", + "" + ); } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/AssertHelpers.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/AssertHelpers.cs index ee072dd3e..b684ac632 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/AssertHelpers.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/AssertHelpers.cs @@ -4,70 +4,69 @@ using Equinor.ProjectExecutionPortal.WebApi.ViewModels.PortalApp; using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests; + +public class AssertHelpers { - public class AssertHelpers + public static void AssertPortalValues(ApiPortal? portal) { - public static void AssertPortalValues(ApiPortal? portal) + if (portal == null) { - if (portal == null) - { - Assert.Fail(); - } - - Assert.IsNotNull(portal.Id); - Assert.IsNotNull(portal.Name); - Assert.IsNotNull(portal.Icon); - Assert.IsNotNull(portal.Key); - Assert.IsNotNull(portal.ShortName); - Assert.IsNotNull(portal.Subtext); - Assert.IsNotNull(portal.Description); - Assert.IsNotNull(portal); + Assert.Fail(); } - public static void AssertPortalConfigurationValues(ApiPortalConfiguration? portalConfiguration, bool acceptNullValues) - { - if (portalConfiguration == null) - { - Assert.Fail(); - } + Assert.IsNotNull(portal.Id); + Assert.IsNotNull(portal.Name); + Assert.IsNotNull(portal.Icon); + Assert.IsNotNull(portal.Key); + Assert.IsNotNull(portal.ShortName); + Assert.IsNotNull(portal.Subtext); + Assert.IsNotNull(portal.Description); + Assert.IsNotNull(portal); + } - if (!acceptNullValues) - { - Assert.IsNotNull(portalConfiguration.Router); - Assert.IsNotNull(portalConfiguration.Extension); - Assert.IsNotNull(portalConfiguration.Environment); - } + public static void AssertPortalConfigurationValues(ApiPortalConfiguration? portalConfiguration, bool acceptNullValues) + { + if (portalConfiguration == null) + { + Assert.Fail(); } - public static void AssertPortalAppValues(ApiPortalApp? portalAll) + if (!acceptNullValues) { - if (portalAll == null) - { - Assert.Fail(); - } - - Assert.IsNotNull(portalAll.AppKey); + Assert.IsNotNull(portalConfiguration.Router); + Assert.IsNotNull(portalConfiguration.Extension); + Assert.IsNotNull(portalConfiguration.Environment); } + } - public static void AssertOnboardedAppValues(ApiOnboardedApp? onboardedApp) + public static void AssertPortalAppValues(ApiPortalApp? portalAll) + { + if (portalAll == null) { - if (onboardedApp == null) - { - Assert.Fail(); - } - - Assert.IsNotNull(onboardedApp.AppKey); + Assert.Fail(); } - public static void AssertContextTypeValues(ApiContextType? contextType) + Assert.IsNotNull(portalAll.AppKey); + } + + public static void AssertOnboardedAppValues(ApiOnboardedApp? onboardedApp) + { + if (onboardedApp == null) { - if (contextType == null) - { - Assert.Fail(); - } + Assert.Fail(); + } - Assert.IsNotNull(contextType.Type); + Assert.IsNotNull(onboardedApp.AppKey); + } + + public static void AssertContextTypeValues(ApiContextType? contextType) + { + if (contextType == null) + { + Assert.Fail(); } + + Assert.IsNotNull(contextType.Type); } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/ContextTypeControllerTests.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/ContextTypeControllerTests.cs index 6da4d6564..faaa92b49 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/ContextTypeControllerTests.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/ContextTypeControllerTests.cs @@ -6,266 +6,265 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests; + +[TestClass] +public class ContextTypeControllerTests : TestBase { - [TestClass] - public class ContextTypeControllerTests : TestBase - { - private const string Route = "api/context-types"; + private const string Route = "api/context-types"; - [TestMethod] - public async Task Get_ContextTypes_AsAuthenticatedUser_ShouldReturnOk() - { - // Act - var contextTypes = await AssertGetAllContextTypes(UserType.Authenticated, HttpStatusCode.OK); + [TestMethod] + public async Task Get_ContextTypes_AsAuthenticatedUser_ShouldReturnOk() + { + // Act + var contextTypes = await AssertGetAllContextTypes(UserType.Authenticated, HttpStatusCode.OK); - // Assert - Assert.IsTrue(contextTypes.Count > 0); + // Assert + Assert.IsTrue(contextTypes.Count > 0); - foreach (var contextType in contextTypes) - { - AssertHelpers.AssertContextTypeValues(contextType); - } + foreach (var contextType in contextTypes) + { + AssertHelpers.AssertContextTypeValues(contextType); } + } - [TestMethod] - public async Task Get_ContextTypes_AsAdministratorUser_ShouldReturnOk() - { - // Act - var contextTypes = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + [TestMethod] + public async Task Get_ContextTypes_AsAdministratorUser_ShouldReturnOk() + { + // Act + var contextTypes = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - // Assert - Assert.IsTrue(contextTypes.Count > 0); + // Assert + Assert.IsTrue(contextTypes.Count > 0); - foreach (var contextType in contextTypes) - { - AssertHelpers.AssertContextTypeValues(contextType); - } + foreach (var contextType in contextTypes) + { + AssertHelpers.AssertContextTypeValues(contextType); } + } - [TestMethod] - public async Task Get_ContextTypes_AsAnonymous_ShouldReturnUnauthorized() - { - // Act - var contextTypes = await AssertGetAllContextTypes(UserType.Anonymous, HttpStatusCode.Unauthorized); + [TestMethod] + public async Task Get_ContextTypes_AsAnonymous_ShouldReturnUnauthorized() + { + // Act + var contextTypes = await AssertGetAllContextTypes(UserType.Anonymous, HttpStatusCode.Unauthorized); - // Assert - Assert.IsNull(contextTypes); - } + // Assert + Assert.IsNull(contextTypes); + } - [TestMethod] - public async Task Add_Valid_ContextType_AsAdministratorUser_ShouldReturnCreated() - { - // Arrange - var getAllBeforeAdded = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + [TestMethod] + public async Task Add_Valid_ContextType_AsAdministratorUser_ShouldReturnCreated() + { + // Arrange + var getAllBeforeAdded = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - var payload = new ApiAddContextTypeRequest - { - Type = ContextTypeData.ValidContextTypes.ContractContextTypeKey - }; + var payload = new ApiAddContextTypeRequest + { + Type = ContextTypeData.ValidContextTypes.ContractContextTypeKey + }; - // Act - var response = await AddContextType(UserType.Administrator, payload); + // Act + var response = await AddContextType(UserType.Administrator, payload); - // Assert - var getAllAfterAdded = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + // Assert + var getAllAfterAdded = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); - Assert.IsNotNull(getAllBeforeAdded); - Assert.IsNotNull(getAllAfterAdded); - Assert.AreEqual(getAllBeforeAdded.Count + 1, getAllAfterAdded.Count); - Assert.AreEqual(payload.Type, getAllAfterAdded.Last().Type); - } + Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); + Assert.IsNotNull(getAllBeforeAdded); + Assert.IsNotNull(getAllAfterAdded); + Assert.AreEqual(getAllBeforeAdded.Count + 1, getAllAfterAdded.Count); + Assert.AreEqual(payload.Type, getAllAfterAdded.Last().Type); + } - [TestMethod] - public async Task Add_Valid_ContextType_AsAuthenticatedUser_ShouldReturnForbidden() + [TestMethod] + public async Task Add_Valid_ContextType_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var payload = new ApiAddContextTypeRequest { - // Arrange - var payload = new ApiAddContextTypeRequest - { - Type = ContextTypeData.ValidContextTypes.ContractContextTypeKey - }; + Type = ContextTypeData.ValidContextTypes.ContractContextTypeKey + }; - // Act - var response = await AddContextType(UserType.Authenticated, payload); + // Act + var response = await AddContextType(UserType.Authenticated, payload); - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } - [TestMethod] - public async Task Add_Valid_ContextType_AsAnonymousUser_ShouldReturnUnauthorized() + [TestMethod] + public async Task Add_Valid_ContextType_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var payload = new ApiAddContextTypeRequest { - // Arrange - var payload = new ApiAddContextTypeRequest - { - Type = ContextTypeData.ValidContextTypes.ContractContextTypeKey - }; + Type = ContextTypeData.ValidContextTypes.ContractContextTypeKey + }; - // Act - var response = await AddContextType(UserType.Anonymous, payload); + // Act + var response = await AddContextType(UserType.Anonymous, payload); - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } - [TestMethod] - public async Task Add_NonExistent_ContextType_AsAdministratorUser_ShouldReturnNotFound() + [TestMethod] + public async Task Add_NonExistent_ContextType_AsAdministratorUser_ShouldReturnNotFound() + { + // Arrange + var payload = new ApiAddContextTypeRequest { - // Arrange - var payload = new ApiAddContextTypeRequest - { - Type = ContextTypeData.InvalidContextTypes.InvalidContextTypeKey - }; + Type = ContextTypeData.InvalidContextTypes.InvalidContextTypeKey + }; - // Act - var response = await AddContextType(UserType.Administrator, payload); + // Act + var response = await AddContextType(UserType.Administrator, payload); - // Assert - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); + } - [TestMethod] - public async Task Add_Duplicate_ContextType_AsAdministratorUser_ShouldReturnConflict() + [TestMethod] + public async Task Add_Duplicate_ContextType_AsAdministratorUser_ShouldReturnConflict() + { + // Arrange + var payload = new ApiAddContextTypeRequest { - // Arrange - var payload = new ApiAddContextTypeRequest - { - Type = ContextTypeData.InitialDbSeedData.ContextType1.ContextTypeKey - }; + Type = ContextTypeData.InitialDbSeedData.ContextType1.ContextTypeKey + }; - // Act - var addDuplicateResponse = await AddContextType(UserType.Administrator, payload); + // Act + var addDuplicateResponse = await AddContextType(UserType.Administrator, payload); - // Assert - Assert.AreEqual(HttpStatusCode.Conflict, addDuplicateResponse.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.Conflict, addDuplicateResponse.StatusCode); + } - [TestMethod] - public async Task Remove_ContextType_WithoutPortals_AsAdministratorUser_ShouldReturnOk() - { - // Arrange - var payload = ContextTypeData.InitialDbSeedData.ContextType2.ContextTypeKey; + [TestMethod] + public async Task Remove_ContextType_WithoutPortals_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + var payload = ContextTypeData.InitialDbSeedData.ContextType2.ContextTypeKey; - // Act - var getAllBefore = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + // Act + var getAllBefore = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - var removeResponse = await RemoveContextType(UserType.Administrator, payload); + var removeResponse = await RemoveContextType(UserType.Administrator, payload); - var getAllAfterRemoval = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + var getAllAfterRemoval = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.OK, removeResponse.StatusCode); - Assert.IsNotNull(getAllBefore.Count); - Assert.IsNotNull(getAllAfterRemoval.Count); - Assert.AreEqual(getAllBefore.Count - 1, getAllAfterRemoval.Count); + // Assert + Assert.AreEqual(HttpStatusCode.OK, removeResponse.StatusCode); + Assert.IsNotNull(getAllBefore.Count); + Assert.IsNotNull(getAllAfterRemoval.Count); + Assert.AreEqual(getAllBefore.Count - 1, getAllAfterRemoval.Count); - } - - [TestMethod] - public async Task Remove_ContextType_WithPortals_AsAdministratorUser_ShouldReturnBadRequest() - { - // Arrange - var payload = ContextTypeData.InitialDbSeedData.ContextType1.ContextTypeKey; - - // Act - var getAllBefore = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + } - var removeResponse = await RemoveContextType(UserType.Administrator, payload); + [TestMethod] + public async Task Remove_ContextType_WithPortals_AsAdministratorUser_ShouldReturnBadRequest() + { + // Arrange + var payload = ContextTypeData.InitialDbSeedData.ContextType1.ContextTypeKey; - var getAllAfter = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + // Act + var getAllBefore = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.BadRequest, removeResponse.StatusCode); - Assert.AreEqual(getAllBefore.Count, getAllAfter.Count); - } + var removeResponse = await RemoveContextType(UserType.Administrator, payload); - [TestMethod] - public async Task Remove_ContextType_AsAuthenticatedUser_ShouldReturnForbidden() - { - // Arrange - var existingContextTypeKey = ContextTypeData.InitialDbSeedData.ContextType1.ContextTypeKey; + var getAllAfter = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - // Act - var getAllBefore = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + // Assert + Assert.AreEqual(HttpStatusCode.BadRequest, removeResponse.StatusCode); + Assert.AreEqual(getAllBefore.Count, getAllAfter.Count); + } - var removeResponse = await RemoveContextType(UserType.Authenticated, existingContextTypeKey); + [TestMethod] + public async Task Remove_ContextType_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var existingContextTypeKey = ContextTypeData.InitialDbSeedData.ContextType1.ContextTypeKey; - var getAllAfter = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + // Act + var getAllBefore = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, removeResponse.StatusCode); - Assert.AreEqual(getAllBefore.Count, getAllAfter.Count); - } + var removeResponse = await RemoveContextType(UserType.Authenticated, existingContextTypeKey); - [TestMethod] - public async Task Remove_ContextType_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Arrange - var existingContextTypeKey = ContextTypeData.InitialDbSeedData.ContextType1.ContextTypeKey; + var getAllAfter = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - // Act - var getAllBefore = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, removeResponse.StatusCode); + Assert.AreEqual(getAllBefore.Count, getAllAfter.Count); + } - var removeResponse = await RemoveContextType(UserType.Anonymous, existingContextTypeKey); + [TestMethod] + public async Task Remove_ContextType_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var existingContextTypeKey = ContextTypeData.InitialDbSeedData.ContextType1.ContextTypeKey; - var getAllAfter = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); + // Act + var getAllBefore = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, removeResponse.StatusCode); - Assert.AreEqual(getAllBefore.Count, getAllAfter.Count); - } + var removeResponse = await RemoveContextType(UserType.Anonymous, existingContextTypeKey); - #region Helpers + var getAllAfter = await AssertGetAllContextTypes(UserType.Administrator, HttpStatusCode.OK); - private static async Task> AssertGetAllContextTypes(UserType userType, HttpStatusCode expectedStatusCode) - { - // Act - var response = await GetAllContextTypes(userType); - var content = await response.Content.ReadAsStringAsync(); - var contextTypes = JsonConvert.DeserializeObject>(content); + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, removeResponse.StatusCode); + Assert.AreEqual(getAllBefore.Count, getAllAfter.Count); + } - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + #region Helpers - if (response.StatusCode != HttpStatusCode.OK) - { - return contextTypes; - } + private static async Task> AssertGetAllContextTypes(UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetAllContextTypes(userType); + var content = await response.Content.ReadAsStringAsync(); + var contextTypes = JsonConvert.DeserializeObject>(content); - Assert.IsNotNull(content); - Assert.IsNotNull(contextTypes); + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); + if (response.StatusCode != HttpStatusCode.OK) + { return contextTypes; } - private static async Task AddContextType(UserType userType, ApiAddContextTypeRequest contextType) - { - var serializePayload = JsonConvert.SerializeObject(contextType); - var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); + Assert.IsNotNull(content); + Assert.IsNotNull(contextTypes); - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.PostAsync($"{Route}", content); + return contextTypes; + } - return response; - } + private static async Task AddContextType(UserType userType, ApiAddContextTypeRequest contextType) + { + var serializePayload = JsonConvert.SerializeObject(contextType); + var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); - private static async Task GetAllContextTypes(UserType userType) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync($"{Route}"); + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.PostAsync($"{Route}", content); - return response; - } + return response; + } - private static async Task RemoveContextType(UserType userType, string contextTypeKey) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.DeleteAsync($"{Route}/{contextTypeKey}"); + private static async Task GetAllContextTypes(UserType userType) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync($"{Route}"); - return response; - } + return response; + } + + private static async Task RemoveContextType(UserType userType, string contextTypeKey) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.DeleteAsync($"{Route}/{contextTypeKey}"); - #endregion Helpers + return response; } -} + + #endregion Helpers +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/OnboardedAppControllerTests.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/OnboardedAppControllerTests.cs index 0c87bb657..20d6a5a08 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/OnboardedAppControllerTests.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/OnboardedAppControllerTests.cs @@ -6,384 +6,383 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests; + +[TestClass] +public class OnboardedAppControllerTests : TestBase { - [TestClass] - public class OnboardedAppControllerTests : TestBase + private const string Route = "api/onboarded-apps"; + + [TestMethod] + public async Task Get_OnboardedApps_AsAuthenticatedUser_ShouldReturnOk() { - private const string Route = "api/onboarded-apps"; + // Act + var onboardedApps = await AssertGetAllOnboardedApps(UserType.Authenticated, HttpStatusCode.OK); - [TestMethod] - public async Task Get_OnboardedApps_AsAuthenticatedUser_ShouldReturnOk() - { - // Act - var onboardedApps = await AssertGetAllOnboardedApps(UserType.Authenticated, HttpStatusCode.OK); + // Assert + Assert.IsNotNull(onboardedApps); + Assert.IsTrue(onboardedApps.Count > 0); - // Assert - Assert.IsNotNull(onboardedApps); - Assert.IsTrue(onboardedApps.Count > 0); + AssertHelpers.AssertOnboardedAppValues(onboardedApps.FirstOrDefault()); + } - AssertHelpers.AssertOnboardedAppValues(onboardedApps.FirstOrDefault()); - } + [TestMethod] + public async Task Get_OnboardedApps_AsAdministratorUser_ShouldReturnOk() + { + // Act + var onboardedApps = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); - [TestMethod] - public async Task Get_OnboardedApps_AsAdministratorUser_ShouldReturnOk() - { - // Act - var onboardedApps = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); + // Assert + Assert.IsNotNull(onboardedApps); + Assert.IsTrue(onboardedApps.Count > 0); + AssertHelpers.AssertOnboardedAppValues(onboardedApps.FirstOrDefault()); + } - // Assert - Assert.IsNotNull(onboardedApps); - Assert.IsTrue(onboardedApps.Count > 0); - AssertHelpers.AssertOnboardedAppValues(onboardedApps.FirstOrDefault()); - } + [TestMethod] + public async Task Get_OnboardedApps_AsAnonymous_ShouldReturnUnauthorized() + { + // Act + var onboardedApps = await AssertGetAllOnboardedApps(UserType.Anonymous, HttpStatusCode.Unauthorized); - [TestMethod] - public async Task Get_OnboardedApps_AsAnonymous_ShouldReturnUnauthorized() - { - // Act - var onboardedApps = await AssertGetAllOnboardedApps(UserType.Anonymous, HttpStatusCode.Unauthorized); + // Assert + Assert.IsNull(onboardedApps); + } - // Assert - Assert.IsNull(onboardedApps); - } + [TestMethod] + public async Task Get_OnboardedApp_AsAuthenticatedUser_ShouldReturnOk() + { + // Act + var onboardedApp = await AssertGetOnboardedApp(OnboardedAppData.InitialDbSeedData.MeetingsApp.AppKey, UserType.Authenticated, HttpStatusCode.OK); - [TestMethod] - public async Task Get_OnboardedApp_AsAuthenticatedUser_ShouldReturnOk() - { - // Act - var onboardedApp = await AssertGetOnboardedApp(OnboardedAppData.InitialDbSeedData.MeetingsApp.AppKey, UserType.Authenticated, HttpStatusCode.OK); + // Assert + Assert.IsNotNull(onboardedApp); - // Assert - Assert.IsNotNull(onboardedApp); + AssertHelpers.AssertOnboardedAppValues(onboardedApp); + } - AssertHelpers.AssertOnboardedAppValues(onboardedApp); - } + [TestMethod] + public async Task Get_OnboardedApp_AsAdministratorUser_ShouldReturnOk() + { + // Act + var onboardedApp = await AssertGetOnboardedApp(OnboardedAppData.InitialDbSeedData.MeetingsApp.AppKey, UserType.Administrator, HttpStatusCode.OK); - [TestMethod] - public async Task Get_OnboardedApp_AsAdministratorUser_ShouldReturnOk() - { - // Act - var onboardedApp = await AssertGetOnboardedApp(OnboardedAppData.InitialDbSeedData.MeetingsApp.AppKey, UserType.Administrator, HttpStatusCode.OK); + // Assert + Assert.IsNotNull(onboardedApp); - // Assert - Assert.IsNotNull(onboardedApp); + AssertHelpers.AssertOnboardedAppValues(onboardedApp); + } - AssertHelpers.AssertOnboardedAppValues(onboardedApp); - } + [TestMethod] + public async Task Get_OnboardedApp_AsAnonymous_ShouldReturnUnauthorized() + { + // Act + var onboardedApp = await AssertGetOnboardedApp(OnboardedAppData.InitialDbSeedData.MeetingsApp.AppKey, UserType.Anonymous, HttpStatusCode.Unauthorized); - [TestMethod] - public async Task Get_OnboardedApp_AsAnonymous_ShouldReturnUnauthorized() - { - // Act - var onboardedApp = await AssertGetOnboardedApp(OnboardedAppData.InitialDbSeedData.MeetingsApp.AppKey, UserType.Anonymous, HttpStatusCode.Unauthorized); + // Assert + Assert.IsNull(onboardedApp); + } - // Assert - Assert.IsNull(onboardedApp); - } + [TestMethod] + public async Task Add_Valid_OnboardedApp_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + var getAllBeforeAdded = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); + var totalCountBeforeAdded = getAllBeforeAdded?.Count; - [TestMethod] - public async Task Add_Valid_OnboardedApp_AsAdministratorUser_ShouldReturnOk() + var payload = new ApiOnboardAppRequest { - // Arrange - var getAllBeforeAdded = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); - var totalCountBeforeAdded = getAllBeforeAdded?.Count; - - var payload = new ApiOnboardAppRequest - { - AppKey = FusionAppApiData.TestFusion.AppKey, - ContextTypes = new List { ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey } - }; - - // Act - var response = await AddOnboardedApp(UserType.Administrator, payload); - - // Assert - var getAllAfterAdded = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); - var totalCountAfterAdded = getAllAfterAdded?.Count; - - Assert.IsNotNull(totalCountBeforeAdded); - Assert.IsNotNull(totalCountAfterAdded); - Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); - Assert.AreEqual(totalCountBeforeAdded + 1, totalCountAfterAdded); - } + AppKey = FusionAppApiData.TestFusion.AppKey, + ContextTypes = new List { ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey } + }; - [TestMethod] - public async Task Add_Valid_OnboardedApp_AsAuthenticatedUser_ShouldReturnForbidden() - { - // Arrange - var payload = new ApiOnboardAppRequest - { - AppKey = FusionAppApiData.TestFusion.AppKey, - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await AddOnboardedApp(UserType.Authenticated, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - } + // Act + var response = await AddOnboardedApp(UserType.Administrator, payload); - [TestMethod] - public async Task Add_Valid_OnboardedApp_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Arrange - var payload = new ApiOnboardAppRequest - { - AppKey = FusionAppApiData.TestFusion.AppKey, - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await AddOnboardedApp(UserType.Anonymous, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); - } + // Assert + var getAllAfterAdded = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); + var totalCountAfterAdded = getAllAfterAdded?.Count; - [TestMethod] - public async Task Add_Invalid_OnboardedApp_AsAdministratorUser_ShouldThrowExeption() - { - // Arrange - var payload = new ApiOnboardAppRequest - { - AppKey = FusionAppApiData.NonExistentApp.AppKey, - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await AddOnboardedApp(UserType.Administrator, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.IsNotNull(totalCountBeforeAdded); + Assert.IsNotNull(totalCountAfterAdded); + Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); + Assert.AreEqual(totalCountBeforeAdded + 1, totalCountAfterAdded); + } - [TestMethod] - public async Task Add_Duplicate_OnboardedApp_AsAdministratorUser_ShouldThrowException() + [TestMethod] + public async Task Add_Valid_OnboardedApp_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var payload = new ApiOnboardAppRequest { - // Arrange - var payload = new ApiOnboardAppRequest - { - AppKey = OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey, - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var addDuplicateResponse = await AddOnboardedApp(UserType.Administrator, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.Conflict, addDuplicateResponse.StatusCode); - } + AppKey = FusionAppApiData.TestFusion.AppKey, + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; - [TestMethod] - public async Task Update_OnboardedApp_AsAdministratorUser_ShouldReturnOk() - { - // Arrange - var getAllBeforeUpdated = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); - var theOneToUpdate = getAllBeforeUpdated!.First(); + // Act + var response = await AddOnboardedApp(UserType.Authenticated, payload); - var payload = new ApiUpdateOnboardedAppRequest - { - ContextTypes = new List() - }; + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } - // Act - var response = await UpdateOnboardedApp(UserType.Administrator, payload, theOneToUpdate.AppKey); + [TestMethod] + public async Task Add_Valid_OnboardedApp_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var payload = new ApiOnboardAppRequest + { + AppKey = FusionAppApiData.TestFusion.AppKey, + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; - // Assert - var getAllAfterAdded = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); - var theOneAfterUpdate = getAllAfterAdded!.First(x => x.Id == theOneToUpdate.Id); + // Act + var response = await AddOnboardedApp(UserType.Anonymous, payload); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.AreEqual(theOneToUpdate.AppKey, theOneAfterUpdate.AppKey); - Assert.AreEqual(theOneToUpdate.Contexts.Count, theOneAfterUpdate.Contexts.Count); - } + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } - [TestMethod] - public async Task Update_OnboardedApp_AsAuthenticatedUser_ShouldReturnForbidden() + [TestMethod] + public async Task Add_Invalid_OnboardedApp_AsAdministratorUser_ShouldThrowExeption() + { + // Arrange + var payload = new ApiOnboardAppRequest { - // Arrange - var payload = new ApiUpdateOnboardedAppRequest - { - ContextTypes = new List() - }; + AppKey = FusionAppApiData.NonExistentApp.AppKey, + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; - // Act - var response = await UpdateOnboardedApp(UserType.Authenticated, payload, OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey); + // Act + var response = await AddOnboardedApp(UserType.Administrator, payload); - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); + } - [TestMethod] - public async Task Update_OnboardedApp_AsAnonymousUser_ShouldReturnUnauthorized() + [TestMethod] + public async Task Add_Duplicate_OnboardedApp_AsAdministratorUser_ShouldThrowException() + { + // Arrange + var payload = new ApiOnboardAppRequest { - // Arrange - var payload = new ApiUpdateOnboardedAppRequest - { - ContextTypes = new List() - }; + AppKey = OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey, + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; - // Act - var response = await UpdateOnboardedApp(UserType.Anonymous, payload, OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey); + // Act + var addDuplicateResponse = await AddOnboardedApp(UserType.Administrator, payload); - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.Conflict, addDuplicateResponse.StatusCode); + } + + [TestMethod] + public async Task Update_OnboardedApp_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + var getAllBeforeUpdated = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); + var theOneToUpdate = getAllBeforeUpdated!.First(); - [TestMethod] - public async Task Remove_OnboardedApp_AsAdministratorUser_ShouldReturnOk() + var payload = new ApiUpdateOnboardedAppRequest { - // Arrange + ContextTypes = new List() + }; - var payload = new ApiOnboardAppRequest - { - AppKey = FusionAppApiData.TestToBeOffboardedFusion.AppKey, - ContextTypes = new List() { ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey } - }; + // Act + var response = await UpdateOnboardedApp(UserType.Administrator, payload, theOneToUpdate.AppKey); - // Act - await AddOnboardedApp(UserType.Administrator, payload); + // Assert + var getAllAfterAdded = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); + var theOneAfterUpdate = getAllAfterAdded!.First(x => x.Id == theOneToUpdate.Id); - var getAllAfterAdded = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); - var totalCountAfterAdded = getAllAfterAdded?.Count; + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual(theOneToUpdate.AppKey, theOneAfterUpdate.AppKey); + Assert.AreEqual(theOneToUpdate.Contexts.Count, theOneAfterUpdate.Contexts.Count); + } - var removeResponse = await RemoveOnboardedApp(UserType.Administrator, payload.AppKey); + [TestMethod] + public async Task Update_OnboardedApp_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var payload = new ApiUpdateOnboardedAppRequest + { + ContextTypes = new List() + }; - var getAllAfterRemoval = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); - var totalCountAfterRemoval = getAllAfterRemoval?.Count; + // Act + var response = await UpdateOnboardedApp(UserType.Authenticated, payload, OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey); - // Assert - Assert.IsNotNull(totalCountAfterAdded); - Assert.IsNotNull(totalCountAfterRemoval); - Assert.AreEqual(HttpStatusCode.OK, removeResponse.StatusCode); - Assert.AreEqual(totalCountAfterAdded - 1, totalCountAfterRemoval); - } + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } - [TestMethod] - public async Task Remove_OnboardedApp_AsAuthenticatedUser_ShouldReturnForbidden() + [TestMethod] + public async Task Update_OnboardedApp_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var payload = new ApiUpdateOnboardedAppRequest { - // Arrange - var existingOnboardedAppKey = OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey; + ContextTypes = new List() + }; - // Act - var removeResponse = await RemoveOnboardedApp(UserType.Authenticated, existingOnboardedAppKey); + // Act + var response = await UpdateOnboardedApp(UserType.Anonymous, payload, OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey); - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, removeResponse.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } - [TestMethod] - public async Task Remove_OnboardedApp_AsAnonymousUser_ShouldReturnUnauthorized() + [TestMethod] + public async Task Remove_OnboardedApp_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + + var payload = new ApiOnboardAppRequest { - // Arrange - var existingOnboardedAppKey = OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey; + AppKey = FusionAppApiData.TestToBeOffboardedFusion.AppKey, + ContextTypes = new List() { ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey } + }; - // Act - var removeResponse = await RemoveOnboardedApp(UserType.Anonymous, existingOnboardedAppKey); + // Act + await AddOnboardedApp(UserType.Administrator, payload); - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, removeResponse.StatusCode); - } + var getAllAfterAdded = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); + var totalCountAfterAdded = getAllAfterAdded?.Count; - #region Helpers + var removeResponse = await RemoveOnboardedApp(UserType.Administrator, payload.AppKey); - private static async Task?> AssertGetAllOnboardedApps(UserType userType, HttpStatusCode expectedStatusCode) - { - // Act - var response = await GetAllOnboardedApps(userType); - var content = await response.Content.ReadAsStringAsync(); - var onboardedApps = JsonConvert.DeserializeObject>(content); + var getAllAfterRemoval = await AssertGetAllOnboardedApps(UserType.Administrator, HttpStatusCode.OK); + var totalCountAfterRemoval = getAllAfterRemoval?.Count; + + // Assert + Assert.IsNotNull(totalCountAfterAdded); + Assert.IsNotNull(totalCountAfterRemoval); + Assert.AreEqual(HttpStatusCode.OK, removeResponse.StatusCode); + Assert.AreEqual(totalCountAfterAdded - 1, totalCountAfterRemoval); + } + + [TestMethod] + public async Task Remove_OnboardedApp_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var existingOnboardedAppKey = OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey; - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + // Act + var removeResponse = await RemoveOnboardedApp(UserType.Authenticated, existingOnboardedAppKey); - if (response.StatusCode != HttpStatusCode.OK) - { - return onboardedApps; - } + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, removeResponse.StatusCode); + } - Assert.IsNotNull(content); - Assert.IsNotNull(onboardedApps); + [TestMethod] + public async Task Remove_OnboardedApp_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var existingOnboardedAppKey = OnboardedAppData.InitialDbSeedData.OrgChartApp.AppKey; - foreach (var app in onboardedApps) - { - AssertHelpers.AssertOnboardedAppValues(app); - } + // Act + var removeResponse = await RemoveOnboardedApp(UserType.Anonymous, existingOnboardedAppKey); + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, removeResponse.StatusCode); + } + + #region Helpers + + private static async Task?> AssertGetAllOnboardedApps(UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetAllOnboardedApps(userType); + var content = await response.Content.ReadAsStringAsync(); + var onboardedApps = JsonConvert.DeserializeObject>(content); + + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); + + if (response.StatusCode != HttpStatusCode.OK) + { return onboardedApps; } - private static async Task AssertGetOnboardedApp(string appKey, UserType userType, HttpStatusCode expectedStatusCode) - { - // Act - var response = await GetOnboardedApp(userType, appKey); - var content = await response.Content.ReadAsStringAsync(); - var onboardedApp = JsonConvert.DeserializeObject(content); + Assert.IsNotNull(content); + Assert.IsNotNull(onboardedApps); - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + foreach (var app in onboardedApps) + { + AssertHelpers.AssertOnboardedAppValues(app); + } - if (response.StatusCode != HttpStatusCode.OK) - { - return onboardedApp; - } + return onboardedApps; + } - Assert.IsNotNull(content); - Assert.IsNotNull(onboardedApp); + private static async Task AssertGetOnboardedApp(string appKey, UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetOnboardedApp(userType, appKey); + var content = await response.Content.ReadAsStringAsync(); + var onboardedApp = JsonConvert.DeserializeObject(content); - AssertHelpers.AssertOnboardedAppValues(onboardedApp); + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); + if (response.StatusCode != HttpStatusCode.OK) + { return onboardedApp; } - private static async Task GetAllOnboardedApps(UserType userType) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync($"{Route}"); + Assert.IsNotNull(content); + Assert.IsNotNull(onboardedApp); - return response; - } + AssertHelpers.AssertOnboardedAppValues(onboardedApp); - private static async Task GetOnboardedApp(UserType userType, string appKey) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync($"{Route}/{appKey}"); + return onboardedApp; + } - return response; - } + private static async Task GetAllOnboardedApps(UserType userType) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync($"{Route}"); - private static async Task AddOnboardedApp(UserType userType, ApiOnboardAppRequest onboardApp) - { - var serializePayload = JsonConvert.SerializeObject(onboardApp); - var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); + return response; + } - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.PostAsync($"{Route}", content); + private static async Task GetOnboardedApp(UserType userType, string appKey) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync($"{Route}/{appKey}"); - return response; - } + return response; + } - private static async Task UpdateOnboardedApp(UserType userType, ApiUpdateOnboardedAppRequest updatedOnboardedApp, string appKey) - { - var serializePayload = JsonConvert.SerializeObject(updatedOnboardedApp); - var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); + private static async Task AddOnboardedApp(UserType userType, ApiOnboardAppRequest onboardApp) + { + var serializePayload = JsonConvert.SerializeObject(onboardApp); + var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.PutAsync($"{string.Format(Route)}/{appKey}", content); + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.PostAsync($"{Route}", content); - return response; - } + return response; + } - private static async Task RemoveOnboardedApp(UserType userType, string appKey) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.DeleteAsync($"{Route}/{appKey}"); + private static async Task UpdateOnboardedApp(UserType userType, ApiUpdateOnboardedAppRequest updatedOnboardedApp, string appKey) + { + var serializePayload = JsonConvert.SerializeObject(updatedOnboardedApp); + var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); - return response; - } + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.PutAsync($"{string.Format(Route)}/{appKey}", content); + + return response; + } - #endregion Helpers + private static async Task RemoveOnboardedApp(UserType userType, string appKey) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.DeleteAsync($"{Route}/{appKey}"); + + return response; } -} + + #endregion Helpers +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/OnboardedContextControllerTests.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/OnboardedContextControllerTests.cs index f7b57c374..398596321 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/OnboardedContextControllerTests.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/OnboardedContextControllerTests.cs @@ -6,241 +6,240 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests; + +[TestClass] +public class OnboardedContextControllerTests : TestBase { - [TestClass] - public class OnboardedContextControllerTests : TestBase + private const string Route = "api/onboarded-contexts"; + + [TestMethod] + public async Task Get_OnboardedContexts_AsAuthenticatedUser_ShouldReturnOk() { - private const string Route = "api/onboarded-contexts"; + // Act + var onboardedContext = await AssertGetAllOnboardedContexts(UserType.Authenticated, HttpStatusCode.OK); - [TestMethod] - public async Task Get_OnboardedContexts_AsAuthenticatedUser_ShouldReturnOk() - { - // Act - var onboardedContext = await AssertGetAllOnboardedContexts(UserType.Authenticated, HttpStatusCode.OK); + // Assert + Assert.IsNotNull(onboardedContext); + Assert.IsTrue(onboardedContext.Count > 0); + Assert.IsNotNull(onboardedContext.FirstOrDefault()?.ExternalId); + } - // Assert - Assert.IsNotNull(onboardedContext); - Assert.IsTrue(onboardedContext.Count > 0); - Assert.IsNotNull(onboardedContext.FirstOrDefault()?.ExternalId); - } + [TestMethod] + public async Task Get_OnboardedContexts_AsAdministratorUser_ShouldReturnOk() + { + // Act + var onboardedContext = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); - [TestMethod] - public async Task Get_OnboardedContexts_AsAdministratorUser_ShouldReturnOk() - { - // Act - var onboardedContext = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); + // Assert + Assert.IsNotNull(onboardedContext); + Assert.IsTrue(onboardedContext.Count > 0); + Assert.IsNotNull(onboardedContext.FirstOrDefault()?.ExternalId); + } - // Assert - Assert.IsNotNull(onboardedContext); - Assert.IsTrue(onboardedContext.Count > 0); - Assert.IsNotNull(onboardedContext.FirstOrDefault()?.ExternalId); - } + [TestMethod] + public async Task Get_OnboardedContexts_AsAnonymous_ShouldReturnUnauthorized() + { + // Act + var onboardedContexts = await AssertGetAllOnboardedContexts(UserType.Anonymous, HttpStatusCode.Unauthorized); - [TestMethod] - public async Task Get_OnboardedContexts_AsAnonymous_ShouldReturnUnauthorized() - { - // Act - var onboardedContexts = await AssertGetAllOnboardedContexts(UserType.Anonymous, HttpStatusCode.Unauthorized); + // Assert + Assert.IsNull(onboardedContexts); + } - // Assert - Assert.IsNull(onboardedContexts); - } + [TestMethod] + public async Task Add_Valid_OnboardedContext_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + var getAllBeforeAdded = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); + var totalCountBeforeAdded = getAllBeforeAdded?.Count; - [TestMethod] - public async Task Add_Valid_OnboardedContext_AsAdministratorUser_ShouldReturnOk() + var payload = new ApiOnboardContextRequest { - // Arrange - var getAllBeforeAdded = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); - var totalCountBeforeAdded = getAllBeforeAdded?.Count; - - var payload = new ApiOnboardContextRequest - { - ExternalId = FusionContextApiData.MongstadFusionContext.ExternalId!, - Type = FusionContextApiData.MongstadFusionContext.Type, - Description = "Some sort of very detailed description" - }; - - // Act - var response = await AddOnboardedContext(UserType.Administrator, payload); - - // Assert - var getAllAfterAdded = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); - var totalCountAfterAdded = getAllAfterAdded?.Count; - - Assert.IsNotNull(totalCountBeforeAdded); - Assert.IsNotNull(totalCountAfterAdded); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.AreEqual(totalCountBeforeAdded + 1, totalCountAfterAdded); - } + ExternalId = FusionContextApiData.MongstadFusionContext.ExternalId!, + Type = FusionContextApiData.MongstadFusionContext.Type, + Description = "Some sort of very detailed description" + }; + + // Act + var response = await AddOnboardedContext(UserType.Administrator, payload); + + // Assert + var getAllAfterAdded = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); + var totalCountAfterAdded = getAllAfterAdded?.Count; + + Assert.IsNotNull(totalCountBeforeAdded); + Assert.IsNotNull(totalCountAfterAdded); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual(totalCountBeforeAdded + 1, totalCountAfterAdded); + } - [TestMethod] - public async Task Add_Valid_OnboardedContext_AsAuthenticatedUser_ShouldReturnForbidden() + [TestMethod] + public async Task Add_Valid_OnboardedContext_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var payload = new ApiOnboardContextRequest { - // Arrange - var payload = new ApiOnboardContextRequest - { - ExternalId = FusionContextApiData.MongstadFusionContext.ExternalId!, - Type = FusionContextApiData.MongstadFusionContext.Type, - Description = "Some sort of very detailed description" - }; - - // Act - var response = await AddOnboardedContext(UserType.Authenticated, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - } + ExternalId = FusionContextApiData.MongstadFusionContext.ExternalId!, + Type = FusionContextApiData.MongstadFusionContext.Type, + Description = "Some sort of very detailed description" + }; - [TestMethod] - public async Task Add_Valid_OnboardedContext_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Arrange - var payload = new ApiOnboardContextRequest - { - ExternalId = FusionContextApiData.MongstadFusionContext.ExternalId!, - Type = FusionContextApiData.MongstadFusionContext.Type, - Description = "Some sort of very detailed description" - }; - - // Act - var response = await AddOnboardedContext(UserType.Anonymous, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); - } + // Act + var response = await AddOnboardedContext(UserType.Authenticated, payload); - [TestMethod] - public async Task Add_NonExistent_OnboardedContext_AsAdministratorUser_ShouldThrowExeption() + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } + + [TestMethod] + public async Task Add_Valid_OnboardedContext_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var payload = new ApiOnboardContextRequest { - // Arrange - var payload = new ApiOnboardContextRequest - { - ExternalId = FusionContextApiData.InvalidContextExternalId, - Type = "tanteSofie", - Description = "A non-existent context" - }; - - // Act - var response = await AddOnboardedContext(UserType.Administrator, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - } + ExternalId = FusionContextApiData.MongstadFusionContext.ExternalId!, + Type = FusionContextApiData.MongstadFusionContext.Type, + Description = "Some sort of very detailed description" + }; - [TestMethod] - public async Task Add_Duplicate_OnboardedContext_AsAdministratorUser_ShouldThrowException() + // Act + var response = await AddOnboardedContext(UserType.Anonymous, payload); + + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [TestMethod] + public async Task Add_NonExistent_OnboardedContext_AsAdministratorUser_ShouldThrowExeption() + { + // Arrange + var payload = new ApiOnboardContextRequest { - // Arrange - var payload = new ApiOnboardContextRequest - { - ExternalId = OnboardedContextData.InitialDbSeedData.JcaContext.ExternalId, - Type = OnboardedContextData.InitialDbSeedData.JcaContext.Type, - Description = "Description from test method" - }; - - // Act - var addDuplicateResponse = await AddOnboardedContext(UserType.Administrator, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.Conflict, addDuplicateResponse.StatusCode); - } + ExternalId = FusionContextApiData.InvalidContextExternalId, + Type = "tanteSofie", + Description = "A non-existent context" + }; + + // Act + var response = await AddOnboardedContext(UserType.Administrator, payload); + + // Assert + Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); + } - [TestMethod] - public async Task Remove_OnboardedContext_AsAdministratorUser_ShouldReturnOk() + [TestMethod] + public async Task Add_Duplicate_OnboardedContext_AsAdministratorUser_ShouldThrowException() + { + // Arrange + var payload = new ApiOnboardContextRequest { - // Arrange - var ogpExternalContextId = OnboardedContextData.InitialDbSeedData.OgpContext.ExternalId; + ExternalId = OnboardedContextData.InitialDbSeedData.JcaContext.ExternalId, + Type = OnboardedContextData.InitialDbSeedData.JcaContext.Type, + Description = "Description from test method" + }; - // Act - var getAllBeforeRemoval = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); - var payload = getAllBeforeRemoval!.First(x => x.ExternalId == ogpExternalContextId); + // Act + var addDuplicateResponse = await AddOnboardedContext(UserType.Administrator, payload); - var removeResponse = await RemoveOnboardedContext(UserType.Administrator, payload.Id); + // Assert + Assert.AreEqual(HttpStatusCode.Conflict, addDuplicateResponse.StatusCode); + } - var getAllAfterRemoval = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); + [TestMethod] + public async Task Remove_OnboardedContext_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + var ogpExternalContextId = OnboardedContextData.InitialDbSeedData.OgpContext.ExternalId; - // Assert - Assert.AreEqual(HttpStatusCode.OK, removeResponse.StatusCode); - Assert.AreEqual(getAllBeforeRemoval?.Count - 1, getAllAfterRemoval?.Count); - } + // Act + var getAllBeforeRemoval = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); + var payload = getAllBeforeRemoval!.First(x => x.ExternalId == ogpExternalContextId); - [TestMethod] - public async Task Remove_OnboardedContext_AsAuthenticatedUser_ShouldReturnForbidden() - { - // Arrange - var existingOnboardedContextExternalId = OnboardedContextData.InitialDbSeedData.JcaContext.Id; + var removeResponse = await RemoveOnboardedContext(UserType.Administrator, payload.Id); - // Act - var removeResponse = await RemoveOnboardedContext(UserType.Authenticated, existingOnboardedContextExternalId); + var getAllAfterRemoval = await AssertGetAllOnboardedContexts(UserType.Administrator, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, removeResponse.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.OK, removeResponse.StatusCode); + Assert.AreEqual(getAllBeforeRemoval?.Count - 1, getAllAfterRemoval?.Count); + } - [TestMethod] - public async Task Remove_OnboardedContext_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Arrange - var existingOnboardedContextExternalId = OnboardedContextData.InitialDbSeedData.JcaContext.Id; + [TestMethod] + public async Task Remove_OnboardedContext_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var existingOnboardedContextExternalId = OnboardedContextData.InitialDbSeedData.JcaContext.Id; - // Act - var removeResponse = await RemoveOnboardedContext(UserType.Anonymous, existingOnboardedContextExternalId); + // Act + var removeResponse = await RemoveOnboardedContext(UserType.Authenticated, existingOnboardedContextExternalId); - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, removeResponse.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, removeResponse.StatusCode); + } + + [TestMethod] + public async Task Remove_OnboardedContext_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var existingOnboardedContextExternalId = OnboardedContextData.InitialDbSeedData.JcaContext.Id; - #region Helpers + // Act + var removeResponse = await RemoveOnboardedContext(UserType.Anonymous, existingOnboardedContextExternalId); - private static async Task?> AssertGetAllOnboardedContexts(UserType userType, HttpStatusCode expectedStatusCode) - { - // Act - var response = await GetAllOnboardedContexts(userType); - var content = await response.Content.ReadAsStringAsync(); - var onboardedContexts = JsonConvert.DeserializeObject>(content); + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, removeResponse.StatusCode); + } - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + #region Helpers - if (response.StatusCode != HttpStatusCode.OK) - { - return onboardedContexts; - } + private static async Task?> AssertGetAllOnboardedContexts(UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetAllOnboardedContexts(userType); + var content = await response.Content.ReadAsStringAsync(); + var onboardedContexts = JsonConvert.DeserializeObject>(content); - Assert.IsNotNull(content); - Assert.IsNotNull(onboardedContexts); + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); + if (response.StatusCode != HttpStatusCode.OK) + { return onboardedContexts; } - private static async Task AddOnboardedContext(UserType userType, ApiOnboardContextRequest onboardContext) - { - var serializePayload = JsonConvert.SerializeObject(onboardContext); - var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); + Assert.IsNotNull(content); + Assert.IsNotNull(onboardedContexts); - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.PostAsync($"{Route}", content); + return onboardedContexts; + } - return response; - } + private static async Task AddOnboardedContext(UserType userType, ApiOnboardContextRequest onboardContext) + { + var serializePayload = JsonConvert.SerializeObject(onboardContext); + var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); - private static async Task GetAllOnboardedContexts(UserType userType) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync($"{Route}"); + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.PostAsync($"{Route}", content); - return response; - } + return response; + } - private static async Task RemoveOnboardedContext(UserType userType, Guid id) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.DeleteAsync($"{Route}/{id}"); + private static async Task GetAllOnboardedContexts(UserType userType) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync($"{Route}"); - return response; - } + return response; + } - #endregion Helpers + private static async Task RemoveOnboardedContext(UserType userType, Guid id) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.DeleteAsync($"{Route}/{id}"); + + return response; } -} + + #endregion Helpers +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/PortalControllerTests.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/PortalControllerTests.cs index 5f74982ca..4643e9cac 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/PortalControllerTests.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/IntegrationTests/PortalControllerTests.cs @@ -8,843 +8,842 @@ using Newtonsoft.Json; using JsonSerializer = System.Text.Json.JsonSerializer; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests -{ - [TestClass] - public class PortalControllerTests : TestBase - { - private const string Route = "api/portals"; +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.IntegrationTests; - [TestMethod] - public async Task Get_Portals_AsAuthenticatedUser_ShouldReturnOk() - { - // Act - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); +[TestClass] +public class PortalControllerTests : TestBase +{ + private const string Route = "api/portals"; - // Assert - Assert.IsNotNull(portals); - Assert.IsTrue(portals.Count > 0); - } + [TestMethod] + public async Task Get_Portals_AsAuthenticatedUser_ShouldReturnOk() + { + // Act + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - [TestMethod] - public async Task Get_Portals_AsAnonymous_ShouldReturnUnauthorized() - { - // Act - var portals = await AssertGetAllPortals(UserType.Anonymous, HttpStatusCode.Unauthorized); + // Assert + Assert.IsNotNull(portals); + Assert.IsTrue(portals.Count > 0); + } - // Assert - Assert.IsNull(portals); - } + [TestMethod] + public async Task Get_Portals_AsAnonymous_ShouldReturnUnauthorized() + { + // Act + var portals = await AssertGetAllPortals(UserType.Anonymous, HttpStatusCode.Unauthorized); - [TestMethod] - public async Task Get_Portal_AsAuthenticatedUser_ShouldReturnOk() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.FirstOrDefault(); + // Assert + Assert.IsNull(portals); + } - // Act & Assert - await AssertGetPortal(portalToTest!.Id, UserType.Authenticated, HttpStatusCode.OK); - } + [TestMethod] + public async Task Get_Portal_AsAuthenticatedUser_ShouldReturnOk() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.FirstOrDefault(); - [TestMethod] - public async Task Get_NonExistentPortal_AsAuthenticatedUser_ShouldReturnNotFound() - { - // Act & Assert - await AssertGetPortal(Guid.NewGuid(), UserType.Authenticated, HttpStatusCode.NotFound); - } + // Act & Assert + await AssertGetPortal(portalToTest!.Id, UserType.Authenticated, HttpStatusCode.OK); + } - [TestMethod] - public async Task Get_Portal_AsAnonymous_ShouldReturnUnauthorized() - { - // Act - var portal = await AssertGetPortal(Guid.NewGuid(), UserType.Anonymous, HttpStatusCode.Unauthorized); + [TestMethod] + public async Task Get_NonExistentPortal_AsAuthenticatedUser_ShouldReturnNotFound() + { + // Act & Assert + await AssertGetPortal(Guid.NewGuid(), UserType.Authenticated, HttpStatusCode.NotFound); + } - // Assert - Assert.IsNull(portal); - } + [TestMethod] + public async Task Get_Portal_AsAnonymous_ShouldReturnUnauthorized() + { + // Act + var portal = await AssertGetPortal(Guid.NewGuid(), UserType.Anonymous, HttpStatusCode.Unauthorized); - [TestMethod] - public async Task Create_Portal_AsAdministratorUser_ShouldReturnOk() - { - // Arrange - var getAllBeforeCreation = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); + // Assert + Assert.IsNull(portal); + } - var payload = new ApiCreatePortalRequest - { - Name = "Created portal name", - Description = "Created description", - ShortName = "Created short name", - Subtext = "Created subtext", - Icon = "Created icon", - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await CreatePortal(UserType.Administrator, payload); - var getAllAfterCreation = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); - var theOneCreated = getAllAfterCreation!.Last(); - - // Assert - var createdPortal = await AssertGetPortal(theOneCreated.Id, UserType.Authenticated, HttpStatusCode.OK); - - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.AreEqual(getAllBeforeCreation!.Count + 1, getAllAfterCreation!.Count); - Assert.AreEqual(theOneCreated.Id, createdPortal!.Id); - Assert.AreEqual(payload.Name, createdPortal.Name); - Assert.AreEqual(payload.Description, createdPortal.Description); - Assert.AreEqual(payload.ShortName, createdPortal.ShortName); - Assert.AreEqual(payload.Subtext, createdPortal.Subtext); - Assert.AreEqual(payload.Icon, createdPortal.Icon); - Assert.AreEqual(payload.ContextTypes.Count, createdPortal.ContextTypes.Count); - } + [TestMethod] + public async Task Create_Portal_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + var getAllBeforeCreation = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); + + var payload = new ApiCreatePortalRequest + { + Name = "Created portal name", + Description = "Created description", + ShortName = "Created short name", + Subtext = "Created subtext", + Icon = "Created icon", + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; + + // Act + var response = await CreatePortal(UserType.Administrator, payload); + var getAllAfterCreation = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); + var theOneCreated = getAllAfterCreation!.Last(); + + // Assert + var createdPortal = await AssertGetPortal(theOneCreated.Id, UserType.Authenticated, HttpStatusCode.OK); + + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual(getAllBeforeCreation!.Count + 1, getAllAfterCreation!.Count); + Assert.AreEqual(theOneCreated.Id, createdPortal!.Id); + Assert.AreEqual(payload.Name, createdPortal.Name); + Assert.AreEqual(payload.Description, createdPortal.Description); + Assert.AreEqual(payload.ShortName, createdPortal.ShortName); + Assert.AreEqual(payload.Subtext, createdPortal.Subtext); + Assert.AreEqual(payload.Icon, createdPortal.Icon); + Assert.AreEqual(payload.ContextTypes.Count, createdPortal.ContextTypes.Count); + } - [TestMethod] - public async Task Create_Portal_AsAuthenticatedUser_ShouldReturnForbidden() - { - // Arrange - var payload = new ApiCreatePortalRequest - { - Name = "Created portal name", - Description = "Created description", - ShortName = "Created short name", - Subtext = "Created subtext", - Icon = "Created icon", - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await CreatePortal(UserType.Authenticated, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - } + [TestMethod] + public async Task Create_Portal_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var payload = new ApiCreatePortalRequest + { + Name = "Created portal name", + Description = "Created description", + ShortName = "Created short name", + Subtext = "Created subtext", + Icon = "Created icon", + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; + + // Act + var response = await CreatePortal(UserType.Authenticated, payload); + + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } - [TestMethod] - public async Task Create_Portal_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Arrange - var payload = new ApiCreatePortalRequest - { - Name = "Created portal name", - Description = "Created description", - ShortName = "Created short name", - Subtext = "Created subtext", - Icon = "Created icon", - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await CreatePortal(UserType.Anonymous, payload); - - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); - } + [TestMethod] + public async Task Create_Portal_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var payload = new ApiCreatePortalRequest + { + Name = "Created portal name", + Description = "Created description", + ShortName = "Created short name", + Subtext = "Created subtext", + Icon = "Created icon", + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; + + // Act + var response = await CreatePortal(UserType.Anonymous, payload); + + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } - [TestMethod] - public async Task Update_Portal_AsAdministratorUser_ShouldReturnOk() - { - // Arrange - var getAllBeforeUpdated = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); - var theOneToUpdate = getAllBeforeUpdated!.First(); + [TestMethod] + public async Task Update_Portal_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + var getAllBeforeUpdated = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); + var theOneToUpdate = getAllBeforeUpdated!.First(); + + var payload = new ApiUpdatePortalRequest + { + Name = "Updated portal name", + Description = "Updated description", + ShortName = "Updated short name", + Subtext = "Updated subtext", + Icon = "Updated icon", + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; + + // Act + var response = await UpdatePortal(UserType.Administrator, payload, theOneToUpdate.Id); + + // Assert + var theOneAfterUpdate = await AssertGetPortal(theOneToUpdate.Id, UserType.Authenticated, HttpStatusCode.OK); + + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual(theOneToUpdate.Id, theOneAfterUpdate!.Id); + Assert.AreEqual(payload.Name, theOneAfterUpdate.Name); + Assert.AreEqual(payload.Description, theOneAfterUpdate.Description); + Assert.AreEqual(payload.ShortName, theOneAfterUpdate.ShortName); + Assert.AreEqual(payload.Subtext, theOneAfterUpdate.Subtext); + Assert.AreEqual(payload.Icon, theOneAfterUpdate.Icon); + Assert.AreEqual(payload.ContextTypes.Count, theOneAfterUpdate.ContextTypes.Count); + } - var payload = new ApiUpdatePortalRequest - { - Name = "Updated portal name", - Description = "Updated description", - ShortName = "Updated short name", - Subtext = "Updated subtext", - Icon = "Updated icon", - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await UpdatePortal(UserType.Administrator, payload, theOneToUpdate.Id); - - // Assert - var theOneAfterUpdate = await AssertGetPortal(theOneToUpdate.Id, UserType.Authenticated, HttpStatusCode.OK); - - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.AreEqual(theOneToUpdate.Id, theOneAfterUpdate!.Id); - Assert.AreEqual(payload.Name, theOneAfterUpdate.Name); - Assert.AreEqual(payload.Description, theOneAfterUpdate.Description); - Assert.AreEqual(payload.ShortName, theOneAfterUpdate.ShortName); - Assert.AreEqual(payload.Subtext, theOneAfterUpdate.Subtext); - Assert.AreEqual(payload.Icon, theOneAfterUpdate.Icon); - Assert.AreEqual(payload.ContextTypes.Count, theOneAfterUpdate.ContextTypes.Count); - } + [TestMethod] + public async Task Update_Portal_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var payload = new ApiUpdatePortalRequest + { + Name = "Updated portal name", + Description = "Updated description", + ShortName = "Updated short name", + Subtext = "Updated subtext", + Icon = "Updated icon", + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; + + // Act + var response = await UpdatePortal(UserType.Authenticated, payload, Guid.NewGuid()); + + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } - [TestMethod] - public async Task Update_Portal_AsAuthenticatedUser_ShouldReturnForbidden() - { - // Arrange - var payload = new ApiUpdatePortalRequest - { - Name = "Updated portal name", - Description = "Updated description", - ShortName = "Updated short name", - Subtext = "Updated subtext", - Icon = "Updated icon", - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await UpdatePortal(UserType.Authenticated, payload, Guid.NewGuid()); - - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - } + [TestMethod] + public async Task Update_Portal_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var payload = new ApiUpdatePortalRequest + { + Name = "Updated portal name", + Description = "Updated description", + ShortName = "Updated short name", + Subtext = "Updated subtext", + Icon = "Updated icon", + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; + + // Act + var response = await UpdatePortal(UserType.Anonymous, payload, Guid.NewGuid()); + + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } - [TestMethod] - public async Task Update_Portal_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Arrange - var payload = new ApiUpdatePortalRequest - { - Name = "Updated portal name", - Description = "Updated description", - ShortName = "Updated short name", - Subtext = "Updated subtext", - Icon = "Updated icon", - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - // Act - var response = await UpdatePortal(UserType.Anonymous, payload, Guid.NewGuid()); - - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); - } + [TestMethod] + public async Task Get_PortalConfiguration_AsAuthenticatedUser_ShouldReturnOk() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals!.First(); - [TestMethod] - public async Task Get_PortalConfiguration_AsAuthenticatedUser_ShouldReturnOk() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals!.First(); + // Act & Assert + await AssertGetPortalConfiguration(portalToTest.Id, UserType.Authenticated, HttpStatusCode.OK); + } - // Act & Assert - await AssertGetPortalConfiguration(portalToTest.Id, UserType.Authenticated, HttpStatusCode.OK); - } + [TestMethod] + public async Task Get_NonExistentPortalConfiguration_AsAuthenticatedUser_ShouldReturnNotFound() + { + // Act & Assert + await AssertGetPortalConfiguration(Guid.NewGuid(), UserType.Authenticated, HttpStatusCode.NotFound); + } - [TestMethod] - public async Task Get_NonExistentPortalConfiguration_AsAuthenticatedUser_ShouldReturnNotFound() - { - // Act & Assert - await AssertGetPortalConfiguration(Guid.NewGuid(), UserType.Authenticated, HttpStatusCode.NotFound); - } + [TestMethod] + public async Task Get_PortalConfiguration_AsAnonymous_ShouldReturnUnauthorized() + { + // Act + var portal = await AssertGetPortalConfiguration(Guid.NewGuid(), UserType.Anonymous, HttpStatusCode.Unauthorized); - [TestMethod] - public async Task Get_PortalConfiguration_AsAnonymous_ShouldReturnUnauthorized() - { - // Act - var portal = await AssertGetPortalConfiguration(Guid.NewGuid(), UserType.Anonymous, HttpStatusCode.Unauthorized); + // Assert + Assert.IsNull(portal); + } - // Assert - Assert.IsNull(portal); - } + [TestMethod] + public async Task Update_PortalConfiguration_AsAdministratorUser_ShouldReturnOk() + { + // Arrange + var getAllBeforeUpdated = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); + var portalToTest = getAllBeforeUpdated!.First(); + var theOneToUpdate = await AssertGetPortalConfiguration(portalToTest.Id, UserType.Authenticated, HttpStatusCode.OK); - [TestMethod] - public async Task Update_PortalConfiguration_AsAdministratorUser_ShouldReturnOk() - { - // Arrange - var getAllBeforeUpdated = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); - var portalToTest = getAllBeforeUpdated!.First(); - var theOneToUpdate = await AssertGetPortalConfiguration(portalToTest.Id, UserType.Authenticated, HttpStatusCode.OK); - - var routerData = JsonSerializer.Serialize( - new - { - Router = new { Root = "" }, - Routes = (List)[new { Id = 1 }, new { Id = 2 },] - } - ); - - var extensionDataData = JsonSerializer.Serialize( - new - { - Extension = new { Root = "" }, - Extensions = (List)[new { Id = 1 }, new { Id = 2 },] - } - ); - - var environmentData = JsonSerializer.Serialize( - new - { - Environment = new { Root = "" }, - Environments = (List)[new { Id = 1 }, new { Id = 2 },] - } - ); - - var payload = new ApiUpdatePortalConfigurationRequest + var routerData = JsonSerializer.Serialize( + new { - Router = routerData, - Extension = extensionDataData, - Environment = environmentData - }; + Router = new { Root = "" }, + Routes = (List)[new { Id = 1 }, new { Id = 2 },] + } + ); - // Act - var response = await UpdatePortalConfiguration(UserType.Administrator, payload, portalToTest.Id); + var extensionDataData = JsonSerializer.Serialize( + new + { + Extension = new { Root = "" }, + Extensions = (List)[new { Id = 1 }, new { Id = 2 },] + } + ); - // Assert - var theOneAfterUpdate = await AssertGetPortalConfiguration(portalToTest.Id, UserType.Authenticated, HttpStatusCode.OK); + var environmentData = JsonSerializer.Serialize( + new + { + Environment = new { Root = "" }, + Environments = (List)[new { Id = 1 }, new { Id = 2 },] + } + ); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.AreNotEqual(payload.Router, theOneToUpdate!.Router); - Assert.AreEqual(payload.Router, theOneAfterUpdate!.Router); + var payload = new ApiUpdatePortalConfigurationRequest + { + Router = routerData, + Extension = extensionDataData, + Environment = environmentData + }; - Assert.AreNotEqual(payload.Extension, theOneToUpdate.Extension); - Assert.AreEqual(payload.Extension, theOneAfterUpdate.Extension); + // Act + var response = await UpdatePortalConfiguration(UserType.Administrator, payload, portalToTest.Id); - Assert.AreNotEqual(payload.Environment, theOneToUpdate.Environment); - Assert.AreEqual(payload.Environment, theOneAfterUpdate.Environment); - } + // Assert + var theOneAfterUpdate = await AssertGetPortalConfiguration(portalToTest.Id, UserType.Authenticated, HttpStatusCode.OK); - [TestMethod] - public async Task Update_PortalConfiguration_AsAuthenticatedUser_ShouldReturnForbidden() - { - // Arrange - var payload = new ApiUpdatePortalConfigurationRequest(); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreNotEqual(payload.Router, theOneToUpdate!.Router); + Assert.AreEqual(payload.Router, theOneAfterUpdate!.Router); - // Act - var response = await UpdatePortalConfiguration(UserType.Authenticated, payload, Guid.NewGuid()); + Assert.AreNotEqual(payload.Extension, theOneToUpdate.Extension); + Assert.AreEqual(payload.Extension, theOneAfterUpdate.Extension); - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - } + Assert.AreNotEqual(payload.Environment, theOneToUpdate.Environment); + Assert.AreEqual(payload.Environment, theOneAfterUpdate.Environment); + } - [TestMethod] - public async Task Update_PortalConfiguration_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Arrange - var payload = new ApiUpdatePortalConfigurationRequest(); + [TestMethod] + public async Task Update_PortalConfiguration_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var payload = new ApiUpdatePortalConfigurationRequest(); - // Act - var response = await UpdatePortalConfiguration(UserType.Anonymous, payload, Guid.NewGuid()); + // Act + var response = await UpdatePortalConfiguration(UserType.Authenticated, payload, Guid.NewGuid()); - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); - } + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } - [TestMethod] - public async Task Get_OnlyGlobalAppKeysForPortal_WithoutContext_AsAuthenticatedUser_ShouldReturnOk() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + [TestMethod] + public async Task Update_PortalConfiguration_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var payload = new ApiUpdatePortalConfigurationRequest(); - // Act - var apps = await AssertGetAppKeysForPortal(portalToTest!.Id, null, UserType.Authenticated, HttpStatusCode.OK); + // Act + var response = await UpdatePortalConfiguration(UserType.Anonymous, payload, Guid.NewGuid()); - // Assert - Assert.IsNotNull(apps); - Assert.AreEqual(4, apps.Count); - } + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } - [TestMethod] - public async Task Get_BothGlobalAndContextAppKeysForPortal_WithValidContext_AsAuthenticatedUser_ShouldReturnOk() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + [TestMethod] + public async Task Get_OnlyGlobalAppKeysForPortal_WithoutContext_AsAuthenticatedUser_ShouldReturnOk() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Act - var apps = await AssertGetAppKeysForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Authenticated, HttpStatusCode.OK); + // Act + var apps = await AssertGetAppKeysForPortal(portalToTest!.Id, null, UserType.Authenticated, HttpStatusCode.OK); - // Assert - Assert.IsNotNull(apps); - Assert.AreEqual(6, apps.Count); - } + // Assert + Assert.IsNotNull(apps); + Assert.AreEqual(4, apps.Count); + } - [TestMethod] - public async Task Get_BothGlobalAndContextAppKeysForPortal_WithInvalidContext_AsAuthenticatedUser_ShouldReturn404() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + [TestMethod] + public async Task Get_BothGlobalAndContextAppKeysForPortal_WithValidContext_AsAuthenticatedUser_ShouldReturnOk() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Act - var response = await GetAppKeysForPortal(portalToTest!.Id, FusionContextApiData.InvalidContextId, UserType.Authenticated); + // Act + var apps = await AssertGetAppKeysForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Authenticated, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - } + // Assert + Assert.IsNotNull(apps); + Assert.AreEqual(6, apps.Count); + } - [TestMethod] - public async Task Get_OnlyGlobalAppsForPortal_WithoutContext_AsAuthenticatedUser_ShouldReturnOk() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + [TestMethod] + public async Task Get_BothGlobalAndContextAppKeysForPortal_WithInvalidContext_AsAuthenticatedUser_ShouldReturn404() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Act - var apps = await AssertGetAppsForPortal(portalToTest!.Id, null, UserType.Authenticated, HttpStatusCode.OK); + // Act + var response = await GetAppKeysForPortal(portalToTest!.Id, FusionContextApiData.InvalidContextId, UserType.Authenticated); - // Assert - Assert.IsNotNull(apps); - Assert.AreEqual(4, apps.Count); - } + // Assert + Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); + } - [TestMethod] - public async Task Get_BothGlobalAndContextAppsForPortal_WithValidContext_AsAuthenticatedUser_ShouldReturnOk() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + [TestMethod] + public async Task Get_OnlyGlobalAppsForPortal_WithoutContext_AsAuthenticatedUser_ShouldReturnOk() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Act - var apps = await AssertGetAppsForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Authenticated, HttpStatusCode.OK); + // Act + var apps = await AssertGetAppsForPortal(portalToTest!.Id, null, UserType.Authenticated, HttpStatusCode.OK); - // Assert - Assert.IsNotNull(apps); - Assert.AreEqual(6, apps.Count); - } + // Assert + Assert.IsNotNull(apps); + Assert.AreEqual(4, apps.Count); + } - [TestMethod] - public async Task Get_BothGlobalAndContextAppsForPortal_WithInvalidContext_AsAuthenticatedUser_ShouldReturn404() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + [TestMethod] + public async Task Get_BothGlobalAndContextAppsForPortal_WithValidContext_AsAuthenticatedUser_ShouldReturnOk() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Act - var response = await GetAppsForPortal(portalToTest!.Id, FusionContextApiData.InvalidContextId, UserType.Authenticated); + // Act + var apps = await AssertGetAppsForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Authenticated, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - } + // Assert + Assert.IsNotNull(apps); + Assert.AreEqual(6, apps.Count); + } - [TestMethod] - public async Task Get_AppsForNonExistentPortal_AsAuthenticatedUser_ShouldReturnNotFound() - { - // Act & Assert - var response = await GetAppsForPortal(Guid.NewGuid(), null, UserType.Authenticated); + [TestMethod] + public async Task Get_BothGlobalAndContextAppsForPortal_WithInvalidContext_AsAuthenticatedUser_ShouldReturn404() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - } + // Act + var response = await GetAppsForPortal(portalToTest!.Id, FusionContextApiData.InvalidContextId, UserType.Authenticated); - [TestMethod] - public async Task Get_AppsForPortal_WithoutContext_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Act - var apps = await AssertGetAppsForPortal(Guid.NewGuid(), null, UserType.Anonymous, HttpStatusCode.Unauthorized); + // Assert + Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); + } - // Assert - Assert.IsNull(apps); - } + [TestMethod] + public async Task Get_AppsForNonExistentPortal_AsAuthenticatedUser_ShouldReturnNotFound() + { + // Act & Assert + var response = await GetAppsForPortal(Guid.NewGuid(), null, UserType.Authenticated); - [TestMethod] - public async Task Get_AppsForPortal_WithValidContext_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Act - var apps = await AssertGetAppsForPortal(Guid.NewGuid(), FusionContextApiData.JcaContextId, UserType.Anonymous, HttpStatusCode.Unauthorized); + Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); + } - // Assert - Assert.IsNull(apps); - } + [TestMethod] + public async Task Get_AppsForPortal_WithoutContext_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Act + var apps = await AssertGetAppsForPortal(Guid.NewGuid(), null, UserType.Anonymous, HttpStatusCode.Unauthorized); - [TestMethod] - public async Task Get_PortalOnboardedApps_AsAuthenticatedUser_ShouldReturnOk() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals!.First(); + // Assert + Assert.IsNull(apps); + } - // Act - var response = await GetPortalOnboardedApps(portalToTest.Id, UserType.Authenticated); + [TestMethod] + public async Task Get_AppsForPortal_WithValidContext_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Act + var apps = await AssertGetAppsForPortal(Guid.NewGuid(), FusionContextApiData.JcaContextId, UserType.Anonymous, HttpStatusCode.Unauthorized); - // Assert - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + // Assert + Assert.IsNull(apps); + } - var content = await response.Content.ReadAsStringAsync(); - var apps = JsonConvert.DeserializeObject>(content); + [TestMethod] + public async Task Get_PortalOnboardedApps_AsAuthenticatedUser_ShouldReturnOk() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals!.First(); - Assert.IsNotNull(apps); - Assert.IsTrue(apps.Count > 0); - } + // Act + var response = await GetPortalOnboardedApps(portalToTest.Id, UserType.Authenticated); - [TestMethod] - public async Task Delete_Portal_AsAdministrator_ShouldReturnOk() - { - // Arrange - var payload = new ApiCreatePortalRequest - { - Name = "Portal to be deleted", - Description = "", - ShortName = "Created short name", - Subtext = "Created subtext", - Icon = "Created icon", - ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] - }; - - await CreatePortal(UserType.Administrator, payload); - var getAllAfterCreation = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); - var theOneCreatedToBeDeleted = getAllAfterCreation!.Last(); - - // Act - var response = await DeletePortal(theOneCreatedToBeDeleted.Id, UserType.Administrator); - - // Assert - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - - // Verify the portal is actually deleted - var deletedPortal = await AssertGetPortal(theOneCreatedToBeDeleted.Id, UserType.Authenticated, HttpStatusCode.NotFound); - Assert.IsNull(deletedPortal); - } + // Assert + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - [TestMethod] - public async Task Delete_PortalWithApps_AsAdministrator_ShouldReturnForbidden() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); - var portalToDelete = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + var content = await response.Content.ReadAsStringAsync(); + var apps = JsonConvert.DeserializeObject>(content); - // Ensure the portal has apps - var apps = await AssertGetAppsForPortal(portalToDelete!.Id, FusionContextApiData.JcaContextId, UserType.Administrator, HttpStatusCode.OK); + Assert.IsNotNull(apps); + Assert.IsTrue(apps.Count > 0); + } - Assert.IsNotNull(apps); - Assert.IsTrue(apps.Count > 0); + [TestMethod] + public async Task Delete_Portal_AsAdministrator_ShouldReturnOk() + { + // Arrange + var payload = new ApiCreatePortalRequest + { + Name = "Portal to be deleted", + Description = "", + ShortName = "Created short name", + Subtext = "Created subtext", + Icon = "Created icon", + ContextTypes = [ContextTypeData.ValidContextTypes.ProjectMasterContextTypeKey] + }; + + await CreatePortal(UserType.Administrator, payload); + var getAllAfterCreation = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); + var theOneCreatedToBeDeleted = getAllAfterCreation!.Last(); + + // Act + var response = await DeletePortal(theOneCreatedToBeDeleted.Id, UserType.Administrator); + + // Assert + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + + // Verify the portal is actually deleted + var deletedPortal = await AssertGetPortal(theOneCreatedToBeDeleted.Id, UserType.Authenticated, HttpStatusCode.NotFound); + Assert.IsNull(deletedPortal); + } - // Act - var response = await DeletePortal(portalToDelete.Id, UserType.Administrator); + [TestMethod] + public async Task Delete_PortalWithApps_AsAdministrator_ShouldReturnForbidden() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); + var portalToDelete = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + // Ensure the portal has apps + var apps = await AssertGetAppsForPortal(portalToDelete!.Id, FusionContextApiData.JcaContextId, UserType.Administrator, HttpStatusCode.OK); - // Verify the portal is not deleted - var deletedPortal = await AssertGetPortal(portalToDelete.Id, UserType.Administrator, HttpStatusCode.OK); - Assert.IsNotNull(deletedPortal); - } + Assert.IsNotNull(apps); + Assert.IsTrue(apps.Count > 0); - [TestMethod] - public async Task Delete_PortalApp_AsAdministrator_ShouldReturnOk() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + // Act + var response = await DeletePortal(portalToDelete.Id, UserType.Administrator); - // Ensure the portal has apps - var apps = await AssertGetAppsForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Administrator, HttpStatusCode.OK); + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - Assert.IsNotNull(apps); - Assert.IsTrue(apps.Count > 0); + // Verify the portal is not deleted + var deletedPortal = await AssertGetPortal(portalToDelete.Id, UserType.Administrator, HttpStatusCode.OK); + Assert.IsNotNull(deletedPortal); + } - var appToDelete = apps.First(); + [TestMethod] + public async Task Delete_PortalApp_AsAdministrator_ShouldReturnOk() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Administrator, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Act - var response = await DeletePortalApp(portalToTest.Id, appToDelete.AppKey, UserType.Administrator); + // Ensure the portal has apps + var apps = await AssertGetAppsForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Administrator, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.IsNotNull(apps); + Assert.IsTrue(apps.Count > 0); - // Verify the app is actually deleted - var deletedApp = await AssertGetPortalApp(portalToTest.Id, appToDelete.AppKey, UserType.Authenticated, HttpStatusCode.NotFound); - Assert.IsNull(deletedApp); - } + var appToDelete = apps.First(); - [TestMethod] - public async Task Delete_PortalApp_AsAuthenticatedUser_ShouldReturnForbidden() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + // Act + var response = await DeletePortalApp(portalToTest.Id, appToDelete.AppKey, UserType.Administrator); - // Ensure the portal has apps - var apps = await AssertGetAppsForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Authenticated, HttpStatusCode.OK); + // Assert + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.IsNotNull(apps); - Assert.IsTrue(apps.Count > 0); + // Verify the app is actually deleted + var deletedApp = await AssertGetPortalApp(portalToTest.Id, appToDelete.AppKey, UserType.Authenticated, HttpStatusCode.NotFound); + Assert.IsNull(deletedApp); + } - var appToDelete = apps.First(); + [TestMethod] + public async Task Delete_PortalApp_AsAuthenticatedUser_ShouldReturnForbidden() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Act - var response = await DeletePortalApp(portalToTest.Id, appToDelete.AppKey, UserType.Authenticated); + // Ensure the portal has apps + var apps = await AssertGetAppsForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Authenticated, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); - } + Assert.IsNotNull(apps); + Assert.IsTrue(apps.Count > 0); - [TestMethod] - public async Task Delete_PortalApp_AsAnonymousUser_ShouldReturnUnauthorized() - { - // Arrange - var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); - var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); + var appToDelete = apps.First(); - // Ensure the portal has apps - var apps = await AssertGetAppsForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Authenticated, HttpStatusCode.OK); + // Act + var response = await DeletePortalApp(portalToTest.Id, appToDelete.AppKey, UserType.Authenticated); - Assert.IsNotNull(apps); - Assert.IsTrue(apps.Count > 0); + // Assert + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } - var appToDelete = apps.First(); + [TestMethod] + public async Task Delete_PortalApp_AsAnonymousUser_ShouldReturnUnauthorized() + { + // Arrange + var portals = await AssertGetAllPortals(UserType.Authenticated, HttpStatusCode.OK); + var portalToTest = portals?.SingleOrDefault(x => x.Key == PortalData.InitialDbSeedData.ProjectExecution.Key); - // Act - var response = await DeletePortalApp(portalToTest.Id, appToDelete.AppKey, UserType.Anonymous); + // Ensure the portal has apps + var apps = await AssertGetAppsForPortal(portalToTest!.Id, FusionContextApiData.JcaContextId, UserType.Authenticated, HttpStatusCode.OK); - // Assert - Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); - } + Assert.IsNotNull(apps); + Assert.IsTrue(apps.Count > 0); - #region Helpers + var appToDelete = apps.First(); - private static async Task AssertGetPortalApp(Guid portalId, string appKey, UserType userType, HttpStatusCode expectedStatusCode) - { - // Act - var response = await GetPortalApp(portalId, appKey, userType); - var content = await response.Content.ReadAsStringAsync(); - var app = JsonConvert.DeserializeObject(content); + // Act + var response = await DeletePortalApp(portalToTest.Id, appToDelete.AppKey, UserType.Anonymous); - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + // Assert + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } - if (response.StatusCode != HttpStatusCode.OK) - { - return null; - } + #region Helpers - Assert.IsNotNull(content); - AssertHelpers.AssertPortalAppValues(app); + private static async Task AssertGetPortalApp(Guid portalId, string appKey, UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetPortalApp(portalId, appKey, userType); + var content = await response.Content.ReadAsStringAsync(); + var app = JsonConvert.DeserializeObject(content); - return app; - } + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); - private static async Task?> AssertGetAllPortals(UserType userType, HttpStatusCode expectedStatusCode) + if (response.StatusCode != HttpStatusCode.OK) { - // Act - var response = await GetAllPortals(userType); - var content = await response.Content.ReadAsStringAsync(); - var portals = JsonConvert.DeserializeObject>(content); + return null; + } - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + Assert.IsNotNull(content); + AssertHelpers.AssertPortalAppValues(app); - if (response.StatusCode != HttpStatusCode.OK) - { - return portals; - } + return app; + } - Assert.IsNotNull(content); - Assert.IsNotNull(portals); + private static async Task?> AssertGetAllPortals(UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetAllPortals(userType); + var content = await response.Content.ReadAsStringAsync(); + var portals = JsonConvert.DeserializeObject>(content); - foreach (var portal in portals) - { - AssertHelpers.AssertPortalValues(portal); - Assert.AreEqual(0, portal.Apps.Count); // No relational data should be included in this request - } + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); + if (response.StatusCode != HttpStatusCode.OK) + { return portals; } - private static async Task AssertGetPortal(Guid portalId, UserType userType, HttpStatusCode expectedStatusCode) + Assert.IsNotNull(content); + Assert.IsNotNull(portals); + + foreach (var portal in portals) { - // Act - var response = await GetPortal(portalId, userType); - var content = await response.Content.ReadAsStringAsync(); - var portal = JsonConvert.DeserializeObject(content); + AssertHelpers.AssertPortalValues(portal); + Assert.AreEqual(0, portal.Apps.Count); // No relational data should be included in this request + } - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + return portals; + } - if (response.StatusCode != HttpStatusCode.OK) - { - return null; - } + private static async Task AssertGetPortal(Guid portalId, UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetPortal(portalId, userType); + var content = await response.Content.ReadAsStringAsync(); + var portal = JsonConvert.DeserializeObject(content); - Assert.IsNotNull(content); - AssertHelpers.AssertPortalValues(portal); - AssertHelpers.AssertPortalConfigurationValues(portal!.Configuration, acceptNullValues: true); - Assert.AreEqual(0, portal.Apps.Count); // No relational data should be included in this request + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); - return portal; + if (response.StatusCode != HttpStatusCode.OK) + { + return null; } - private static async Task AssertGetPortalConfiguration(Guid portalId, UserType userType, HttpStatusCode expectedStatusCode) - { - // Act - var response = await GetPortalConfiguration(portalId, userType); - var content = await response.Content.ReadAsStringAsync(); - var portalConfiguration = JsonConvert.DeserializeObject(content); + Assert.IsNotNull(content); + AssertHelpers.AssertPortalValues(portal); + AssertHelpers.AssertPortalConfigurationValues(portal!.Configuration, acceptNullValues: true); + Assert.AreEqual(0, portal.Apps.Count); // No relational data should be included in this request - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + return portal; + } - if (response.StatusCode != HttpStatusCode.OK) - { - return portalConfiguration; - } + private static async Task AssertGetPortalConfiguration(Guid portalId, UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetPortalConfiguration(portalId, userType); + var content = await response.Content.ReadAsStringAsync(); + var portalConfiguration = JsonConvert.DeserializeObject(content); - Assert.IsNotNull(content); - Assert.IsNotNull(portalConfiguration); - AssertHelpers.AssertPortalConfigurationValues(portalConfiguration, acceptNullValues: false); + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); + if (response.StatusCode != HttpStatusCode.OK) + { return portalConfiguration; } - private static async Task?> AssertGetAppKeysForPortal(Guid portalId, Guid? contextId, UserType userType, HttpStatusCode expectedStatusCode) - { - // Act - var response = await GetAppKeysForPortal(portalId, contextId, userType); - var content = await response.Content.ReadAsStringAsync(); - var appKeys = JsonConvert.DeserializeObject>(content); - - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + Assert.IsNotNull(content); + Assert.IsNotNull(portalConfiguration); + AssertHelpers.AssertPortalConfigurationValues(portalConfiguration, acceptNullValues: false); - if (response.StatusCode != HttpStatusCode.OK) - { - return appKeys; - } + return portalConfiguration; + } - Assert.IsNotNull(content); - Assert.IsNotNull(appKeys); + private static async Task?> AssertGetAppKeysForPortal(Guid portalId, Guid? contextId, UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetAppKeysForPortal(portalId, contextId, userType); + var content = await response.Content.ReadAsStringAsync(); + var appKeys = JsonConvert.DeserializeObject>(content); - foreach (var appKey in appKeys) - { - Assert.IsNotNull(appKey); - Assert.IsInstanceOfType(appKey); - } + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); + if (response.StatusCode != HttpStatusCode.OK) + { return appKeys; } - private static async Task?> AssertGetAppsForPortal(Guid portalId, Guid? contextId, UserType userType, HttpStatusCode expectedStatusCode) - { - // Act - var response = await GetAppsForPortal(portalId, contextId, userType); - var content = await response.Content.ReadAsStringAsync(); - var apps = JsonConvert.DeserializeObject>(content); + Assert.IsNotNull(content); + Assert.IsNotNull(appKeys); - // Assert - Assert.AreEqual(expectedStatusCode, response.StatusCode); + foreach (var appKey in appKeys) + { + Assert.IsNotNull(appKey); + Assert.IsInstanceOfType(appKey); + } - if (response.StatusCode != HttpStatusCode.OK) - { - return apps; - } + return appKeys; + } - Assert.IsNotNull(content); - Assert.IsNotNull(apps); + private static async Task?> AssertGetAppsForPortal(Guid portalId, Guid? contextId, UserType userType, HttpStatusCode expectedStatusCode) + { + // Act + var response = await GetAppsForPortal(portalId, contextId, userType); + var content = await response.Content.ReadAsStringAsync(); + var apps = JsonConvert.DeserializeObject>(content); - foreach (var app in apps) - { - AssertHelpers.AssertPortalAppValues(app); - } + // Assert + Assert.AreEqual(expectedStatusCode, response.StatusCode); + if (response.StatusCode != HttpStatusCode.OK) + { return apps; } - private static async Task CreatePortal(UserType userType, ApiCreatePortalRequest createdPortal) + Assert.IsNotNull(content); + Assert.IsNotNull(apps); + + foreach (var app in apps) { - var serializePayload = JsonConvert.SerializeObject(createdPortal); - var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); + AssertHelpers.AssertPortalAppValues(app); + } - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.PostAsync($"{string.Format(Route)}", content); + return apps; + } - return response; - } + private static async Task CreatePortal(UserType userType, ApiCreatePortalRequest createdPortal) + { + var serializePayload = JsonConvert.SerializeObject(createdPortal); + var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); - private static async Task UpdatePortal(UserType userType, ApiUpdatePortalRequest updatedPortal, Guid portalId) - { - var serializePayload = JsonConvert.SerializeObject(updatedPortal); - var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.PostAsync($"{string.Format(Route)}", content); - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.PutAsync($"{string.Format(Route)}/{portalId}", content); + return response; + } - return response; - } + private static async Task UpdatePortal(UserType userType, ApiUpdatePortalRequest updatedPortal, Guid portalId) + { + var serializePayload = JsonConvert.SerializeObject(updatedPortal); + var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); - private static async Task UpdatePortalConfiguration(UserType userType, ApiUpdatePortalConfigurationRequest updatedPortalConfiguration, Guid portalId) - { - var serializePayload = JsonConvert.SerializeObject(updatedPortalConfiguration); - var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.PutAsync($"{string.Format(Route)}/{portalId}", content); - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.PutAsync($"{string.Format(Route)}/{portalId}/configuration", content); + return response; + } - return response; - } + private static async Task UpdatePortalConfiguration(UserType userType, ApiUpdatePortalConfigurationRequest updatedPortalConfiguration, Guid portalId) + { + var serializePayload = JsonConvert.SerializeObject(updatedPortalConfiguration); + var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); - private static async Task GetAllPortals(UserType userType) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync($"{Route}"); + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.PutAsync($"{string.Format(Route)}/{portalId}/configuration", content); - return response; - } + return response; + } - private static async Task GetPortal(Guid portalId, UserType userType) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync($"{Route}/{portalId}"); + private static async Task GetAllPortals(UserType userType) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync($"{Route}"); - return response; - } + return response; + } - private static async Task GetPortalConfiguration(Guid portalId, UserType userType) - { - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync($"{Route}/{portalId}/configuration"); + private static async Task GetPortal(Guid portalId, UserType userType) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync($"{Route}/{portalId}"); - return response; - } + return response; + } - private static async Task GetAppKeysForPortal(Guid portalId, Guid? contextId, UserType userType) - { - var route = contextId != null ? $"{Route}/{portalId}/contexts/{contextId}/appkeys" : $"{Route}/{portalId}/appkeys"; - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync(route); + private static async Task GetPortalConfiguration(Guid portalId, UserType userType) + { + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync($"{Route}/{portalId}/configuration"); - return response; - } + return response; + } - private static async Task GetAppsForPortal(Guid portalId, Guid? contextId, UserType userType) - { - var route = contextId != null ? $"{Route}/{portalId}/contexts/{contextId}/apps" : $"{Route}/{portalId}/apps"; - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync(route); + private static async Task GetAppKeysForPortal(Guid portalId, Guid? contextId, UserType userType) + { + var route = contextId != null ? $"{Route}/{portalId}/contexts/{contextId}/appkeys" : $"{Route}/{portalId}/appkeys"; + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync(route); - return response; - } + return response; + } - private static async Task GetPortalOnboardedApps(Guid portalId, UserType userType) - { - var route = $"{Route}/{portalId}/onboarded-apps"; - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync(route); + private static async Task GetAppsForPortal(Guid portalId, Guid? contextId, UserType userType) + { + var route = contextId != null ? $"{Route}/{portalId}/contexts/{contextId}/apps" : $"{Route}/{portalId}/apps"; + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync(route); - return response; - } + return response; + } - private static async Task DeletePortal(Guid portalId, UserType userType) - { - var route = $"{Route}/{portalId}"; - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.DeleteAsync(route); + private static async Task GetPortalOnboardedApps(Guid portalId, UserType userType) + { + var route = $"{Route}/{portalId}/onboarded-apps"; + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync(route); - return response; - } + return response; + } - private static async Task GetPortalApp(Guid portalId, string appKey, UserType userType) - { - var route = $"{Route}{portalId}/onboarded-apps/{appKey}"; - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.GetAsync(route); + private static async Task DeletePortal(Guid portalId, UserType userType) + { + var route = $"{Route}/{portalId}"; + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.DeleteAsync(route); - return response; - } + return response; + } - private static async Task DeletePortalApp(Guid portalId, string appId, UserType userType) - { - var route = $"{Route}/{portalId}/apps/{appId}"; - var client = TestFactory.Instance.GetHttpClient(userType); - var response = await client.DeleteAsync(route); + private static async Task GetPortalApp(Guid portalId, string appKey, UserType userType) + { + var route = $"{Route}{portalId}/onboarded-apps/{appKey}"; + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.GetAsync(route); - return response; - } + return response; + } - #endregion Helpers + private static async Task DeletePortalApp(Guid portalId, string appId, UserType userType) + { + var route = $"{Route}/{portalId}/apps/{appId}"; + var client = TestFactory.Instance.GetHttpClient(userType); + var response = await client.DeleteAsync(route); + + return response; } -} + + #endregion Helpers +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Misc/ApplicationDbContextExtension.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Misc/ApplicationDbContextExtension.cs index 0b89a1181..20b1c2538 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Misc/ApplicationDbContextExtension.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Misc/ApplicationDbContextExtension.cs @@ -5,92 +5,91 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Misc +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Misc; + +public static class ApplicationDbContextExtension { - public static class ApplicationDbContextExtension - { - private const string SeederOid = "00000000-0000-0000-0000-999999999999"; + private const string SeederOid = "00000000-0000-0000-0000-999999999999"; - public static void CreateNewDatabaseWithCorrectSchema(this ProjectExecutionPortalContext dbContext) - { - //var migrations = dbContext.Database.GetPendingMigrations(); - //if (migrations.Any()) - //{ - // dbContext.Database.Migrate(); - //} - } + public static void CreateNewDatabaseWithCorrectSchema(this ProjectExecutionPortalContext dbContext) + { + //var migrations = dbContext.Database.GetPendingMigrations(); + //if (migrations.Any()) + //{ + // dbContext.Database.Migrate(); + //} + } - public static void Seed(this ProjectExecutionPortalContext dbContext, IServiceProvider serviceProvider) - { - var userProvider = serviceProvider.GetRequiredService(); - userProvider.SetCurrentUserOid(new Guid(SeederOid)); + public static void Seed(this ProjectExecutionPortalContext dbContext, IServiceProvider serviceProvider) + { + var userProvider = serviceProvider.GetRequiredService(); + userProvider.SetCurrentUserOid(new Guid(SeederOid)); - SeedPortal(dbContext); - } + SeedPortal(dbContext); + } - private static void SeedPortal(DbContext dbContext) - { - // Create portals + private static void SeedPortal(DbContext dbContext) + { + // Create portals - var portalWithoutApps = PortalData.InitialDbSeedData.PortfolioManagement; - var portalWithApps = PortalData.InitialDbSeedData.ProjectExecution; + var portalWithoutApps = PortalData.InitialDbSeedData.PortfolioManagement; + var portalWithApps = PortalData.InitialDbSeedData.ProjectExecution; - dbContext.AddRange(portalWithoutApps, portalWithApps); - dbContext.SaveChanges(); + dbContext.AddRange(portalWithoutApps, portalWithApps); + dbContext.SaveChanges(); - // Add portal configuration + // Add portal configuration - portalWithoutApps.Configuration.Update(PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Router, PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Extension, PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Environment); - portalWithApps.Configuration.Update(PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Router, PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Extension, PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Environment); + portalWithoutApps.Configuration.Update(PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Router, PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Extension, PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Environment); + portalWithApps.Configuration.Update(PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Router, PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Extension, PortalConfigurationData.InitialDbSeedData.GenericPortalConfiguration.Environment); - // Add context types + // Add context types - var contextTypeProjectMaster = ContextTypeData.InitialDbSeedData.ContextType1; - var contextTypeFacility = ContextTypeData.InitialDbSeedData.ContextType2; + var contextTypeProjectMaster = ContextTypeData.InitialDbSeedData.ContextType1; + var contextTypeFacility = ContextTypeData.InitialDbSeedData.ContextType2; - // Connect portal with a context type - portalWithApps.AddContextType(contextTypeProjectMaster); + // Connect portal with a context type + portalWithApps.AddContextType(contextTypeProjectMaster); - dbContext.AddRange(contextTypeProjectMaster, contextTypeFacility); - dbContext.SaveChanges(); + dbContext.AddRange(contextTypeProjectMaster, contextTypeFacility); + dbContext.SaveChanges(); - // Add onboarded apps + // Add onboarded apps - var meetingsApp = OnboardedAppData.InitialDbSeedData.MeetingsApp; - var reviewsApp = OnboardedAppData.InitialDbSeedData.ReviewsApp; - var tasksApp = OnboardedAppData.InitialDbSeedData.TasksApp; - var orgChartApp = OnboardedAppData.InitialDbSeedData.OrgChartApp; - var handoverGardenApp = OnboardedAppData.InitialDbSeedData.HandoverGardenApp; - var workOrderGardenApp = OnboardedAppData.InitialDbSeedData.WorkOrderGardenApp; + var meetingsApp = OnboardedAppData.InitialDbSeedData.MeetingsApp; + var reviewsApp = OnboardedAppData.InitialDbSeedData.ReviewsApp; + var tasksApp = OnboardedAppData.InitialDbSeedData.TasksApp; + var orgChartApp = OnboardedAppData.InitialDbSeedData.OrgChartApp; + var handoverGardenApp = OnboardedAppData.InitialDbSeedData.HandoverGardenApp; + var workOrderGardenApp = OnboardedAppData.InitialDbSeedData.WorkOrderGardenApp; - // Add apps + // Add apps - dbContext.AddRange(meetingsApp, reviewsApp, tasksApp, orgChartApp, handoverGardenApp, workOrderGardenApp); - dbContext.SaveChanges(); + dbContext.AddRange(meetingsApp, reviewsApp, tasksApp, orgChartApp, handoverGardenApp, workOrderGardenApp); + dbContext.SaveChanges(); - // Add onboarded contexts + // Add onboarded contexts - var jcaContext = OnboardedContextData.InitialDbSeedData.JcaContext; - var ogpContext = OnboardedContextData.InitialDbSeedData.OgpContext; + var jcaContext = OnboardedContextData.InitialDbSeedData.JcaContext; + var ogpContext = OnboardedContextData.InitialDbSeedData.OgpContext; - dbContext.AddRange(jcaContext, ogpContext); - dbContext.SaveChanges(); + dbContext.AddRange(jcaContext, ogpContext); + dbContext.SaveChanges(); - // Add apps to portal + // Add apps to portal - var globalMeetingsApp = new PortalApp(meetingsApp.Id, portalWithApps.Id); - var globalReviewsApp = new PortalApp(reviewsApp.Id, portalWithApps.Id); - var globalTasksApp = new PortalApp(tasksApp.Id, portalWithApps.Id); + var globalMeetingsApp = new PortalApp(meetingsApp.Id, portalWithApps.Id); + var globalReviewsApp = new PortalApp(reviewsApp.Id, portalWithApps.Id); + var globalTasksApp = new PortalApp(tasksApp.Id, portalWithApps.Id); - var jcaContextOrgChartApp = new PortalApp(orgChartApp.Id, portalWithApps.Id, jcaContext.Id); - var jcaContextHandoverGardenApp = new PortalApp(handoverGardenApp.Id, portalWithApps.Id, jcaContext.Id); + var jcaContextOrgChartApp = new PortalApp(orgChartApp.Id, portalWithApps.Id, jcaContext.Id); + var jcaContextHandoverGardenApp = new PortalApp(handoverGardenApp.Id, portalWithApps.Id, jcaContext.Id); - var ogpContextWorkOrderGardenApp = new PortalApp(workOrderGardenApp.Id, portalWithApps.Id); + var ogpContextWorkOrderGardenApp = new PortalApp(workOrderGardenApp.Id, portalWithApps.Id); - // Add context specific apps to work surfaces + // Add context specific apps to work surfaces - dbContext.AddRange(globalMeetingsApp, globalReviewsApp, globalTasksApp, jcaContextOrgChartApp, jcaContextHandoverGardenApp, ogpContextWorkOrderGardenApp); - dbContext.SaveChanges(); - } + dbContext.AddRange(globalMeetingsApp, globalReviewsApp, globalTasksApp, jcaContextOrgChartApp, jcaContextHandoverGardenApp, ogpContextWorkOrderGardenApp); + dbContext.SaveChanges(); } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/ITestUser.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/ITestUser.cs index 4a480f691..9f8148f06 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/ITestUser.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/ITestUser.cs @@ -1,8 +1,7 @@ -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup; + +public interface ITestUser { - public interface ITestUser - { - TokenProfile? Profile { get; set; } - HttpClient HttpClient { get; set; } - } -} + TokenProfile? Profile { get; set; } + HttpClient HttpClient { get; set; } +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/IntegrationTestAuthHandler.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/IntegrationTestAuthHandler.cs index 77df091f0..67e88d72f 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/IntegrationTestAuthHandler.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/IntegrationTestAuthHandler.cs @@ -7,93 +7,92 @@ using Microsoft.Extensions.Options; using Newtonsoft.Json; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup; + +internal class IntegrationTestAuthHandler : AuthenticationHandler { - internal class IntegrationTestAuthHandler : AuthenticationHandler + public static string TestAuthenticationScheme = "AuthScheme"; + + private enum AuthType { - public static string TestAuthenticationScheme = "AuthScheme"; + Application, + Delegated + } - private enum AuthType - { - Application, - Delegated - } + public IntegrationTestAuthHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) + : base(options, logger, encoder, clock) + { + } - public IntegrationTestAuthHandler( - IOptionsMonitor options, - ILoggerFactory logger, - UrlEncoder encoder, - ISystemClock clock) - : base(options, logger, encoder, clock) + protected override async Task HandleAuthenticateAsync() + { + try { + var claims = await GatherTestUserClaimsAsync(); + var testIdentity = new ClaimsIdentity(claims, TestAuthenticationScheme); + var testUser = new ClaimsPrincipal(testIdentity); + var ticket = new AuthenticationTicket(testUser, new AuthenticationProperties(), TestAuthenticationScheme); + // Don't think there is any scenario we want to return 401, as if headers is set, the user is requested. + return AuthenticateResult.Success(ticket); } - - protected override async Task HandleAuthenticateAsync() + catch (Exception ex) { - try - { - var claims = await GatherTestUserClaimsAsync(); - var testIdentity = new ClaimsIdentity(claims, TestAuthenticationScheme); - var testUser = new ClaimsPrincipal(testIdentity); - var ticket = new AuthenticationTicket(testUser, new AuthenticationProperties(), TestAuthenticationScheme); - // Don't think there is any scenario we want to return 401, as if headers is set, the user is requested. - return AuthenticateResult.Success(ticket); - } - catch (Exception ex) - { - return AuthenticateResult.Fail(ex); - } + return AuthenticateResult.Fail(ex); } + } - private Task> GatherTestUserClaimsAsync() + private Task> GatherTestUserClaimsAsync() + { + var authorizationHeader = Request.Headers["Authorization"]; + var tokens = authorizationHeader.ToString().Split(' '); + if (tokens == null || tokens.Length <= 1) { - var authorizationHeader = Request.Headers["Authorization"]; - var tokens = authorizationHeader.ToString().Split(' '); - if (tokens == null || tokens.Length <= 1) - { - throw new Exception("[Authorization] header missing"); - } - - TokenProfile? profile; - var tokenPart = tokens[1]; + throw new Exception("[Authorization] header missing"); + } - try - { - var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(tokenPart)); - profile = JsonConvert.DeserializeObject(decoded); - } - catch (Exception ex) - { - throw new Exception( - "Unable to extract test auth token from [Authorization] header. See inner exception for details.", - ex); - } + TokenProfile? profile; + var tokenPart = tokens[1]; - var authType = profile!.IsAppToken ? AuthType.Application : AuthType.Delegated; + try + { + var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(tokenPart)); + profile = JsonConvert.DeserializeObject(decoded); + } + catch (Exception ex) + { + throw new Exception( + "Unable to extract test auth token from [Authorization] header. See inner exception for details.", + ex); + } - var claims = new List { new(ClaimsExtensions.Oid, profile.Oid) }; + var authType = profile!.IsAppToken ? AuthType.Application : AuthType.Delegated; - switch (authType) - { - case AuthType.Delegated: - claims.Add(new Claim(ClaimTypes.GivenName, profile.FirstName)); - claims.Add(new Claim(ClaimTypes.Surname, profile.LastName)); + var claims = new List { new(ClaimsExtensions.Oid, profile.Oid) }; - if (profile.AppRoles != null) - { - claims.AddRange(profile.AppRoles.Select(role => new Claim(ClaimTypes.Role, role))); - } - break; + switch (authType) + { + case AuthType.Delegated: + claims.Add(new Claim(ClaimTypes.GivenName, profile.FirstName)); + claims.Add(new Claim(ClaimTypes.Surname, profile.LastName)); - case AuthType.Application: - if (profile.AppRoles != null) - { - claims.AddRange(profile.AppRoles.Select(role => new Claim(ClaimTypes.Role, role))); - } - break; - } + if (profile.AppRoles != null) + { + claims.AddRange(profile.AppRoles.Select(role => new Claim(ClaimTypes.Role, role))); + } + break; - return Task.FromResult(claims); + case AuthType.Application: + if (profile.AppRoles != null) + { + claims.AddRange(profile.AppRoles.Select(role => new Claim(ClaimTypes.Role, role))); + } + break; } + + return Task.FromResult(claims); } } \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/IntegrationTestAuthOptions.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/IntegrationTestAuthOptions.cs index 7be669141..d02013fdd 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/IntegrationTestAuthOptions.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/IntegrationTestAuthOptions.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Authentication; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup -{ - internal class IntegrationTestAuthOptions : AuthenticationSchemeOptions; -} +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup; + +internal class IntegrationTestAuthOptions : AuthenticationSchemeOptions; \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/TestUser.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/TestUser.cs index 71cbed440..c863f4fb7 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/TestUser.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/TestUser.cs @@ -1,10 +1,9 @@ -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup; + +public class TestUser : ITestUser { - public class TestUser : ITestUser - { - public TokenProfile? Profile { get; set; } - public HttpClient HttpClient { get; set; } = null!; + public TokenProfile? Profile { get; set; } + public HttpClient HttpClient { get; set; } = null!; - public override string? ToString() => Profile?.ToString(); - } -} + public override string? ToString() => Profile?.ToString(); +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/TokenProfile.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/TokenProfile.cs index 4cb98dc79..32daf5bba 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/TokenProfile.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/TokenProfile.cs @@ -1,31 +1,30 @@ using System.Text; using Newtonsoft.Json; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup; + +public class TokenProfile { - public class TokenProfile - { - public string Oid { get; set; } = null!; - public string FirstName { get; set; } = null!; - public string LastName { get; set; } = null!; - public string FullName => $"{FirstName} {LastName}"; - public bool IsAppToken { get; set; } = false; - public string[]? AppRoles { get; set; } + public string Oid { get; set; } = null!; + public string FirstName { get; set; } = null!; + public string LastName { get; set; } = null!; + public string FullName => $"{FirstName} {LastName}"; + public bool IsAppToken { get; set; } = false; + public string[]? AppRoles { get; set; } - public override string ToString() => $"{FullName} {Oid}"; + public override string ToString() => $"{FullName} {Oid}"; - /// - /// Wraps profile by serializing, encoding and then converting to base 64 string. - /// "Bearer" is also added, making it ready to be added as Authorization header - /// - /// Serialized, encoded string ready for authorization header - public string CreateBearerToken() - { - var serialized = JsonConvert.SerializeObject(this); - var tokenBytes = Encoding.UTF8.GetBytes(serialized); - var tokenString = Convert.ToBase64String(tokenBytes); + /// + /// Wraps profile by serializing, encoding and then converting to base 64 string. + /// "Bearer" is also added, making it ready to be added as Authorization header + /// + /// Serialized, encoded string ready for authorization header + public string CreateBearerToken() + { + var serialized = JsonConvert.SerializeObject(this); + var tokenBytes = Encoding.UTF8.GetBytes(serialized); + var tokenString = Convert.ToBase64String(tokenBytes); - return $"Bearer {tokenString}"; - } + return $"Bearer {tokenString}"; } -} +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/UserType.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/UserType.cs index c0713c2a8..50aec3ffe 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/UserType.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/Setup/UserType.cs @@ -1,9 +1,8 @@ -namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup +namespace Equinor.ProjectExecutionPortal.Tests.WebApi.Setup; + +public enum UserType { - public enum UserType - { - Anonymous, - Authenticated, - Administrator - } -} + Anonymous, + Authenticated, + Administrator +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/TestBase.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/TestBase.cs index b2b084829..0e2072691 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/TestBase.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/TestBase.cs @@ -1,11 +1,10 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi +namespace Equinor.ProjectExecutionPortal.Tests.WebApi; + +[TestClass] +public abstract class TestBase { - [TestClass] - public abstract class TestBase - { - //[AssemblyCleanup] - //public static void AssemblyCleanup() => TestFactory.Instance.Dispose(); - } -} + //[AssemblyCleanup] + //public static void AssemblyCleanup() => TestFactory.Instance.Dispose(); +} \ No newline at end of file diff --git a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/TestFactory.cs b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/TestFactory.cs index 4c4a8e4eb..8fdd810b0 100644 --- a/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/TestFactory.cs +++ b/backend/src/tests/Equinor.ProjectExecutionPortal.Tests.WebApi/TestFactory.cs @@ -15,273 +15,271 @@ using Microsoft.Extensions.DependencyInjection; using Moq; -namespace Equinor.ProjectExecutionPortal.Tests.WebApi +namespace Equinor.ProjectExecutionPortal.Tests.WebApi; +public sealed class TestFactory : WebApplicationFactory { - public sealed class TestFactory : WebApplicationFactory + private const string AuthenticatedUserOid = "00000000-0000-0000-0000-000000000007"; + private const string IntegrationTestEnvironment = "IntegrationTests"; + private readonly string _localDbConnectionString; + private readonly string _configPath; + private readonly List _teardownList = new(); + private readonly List _disposables = new(); + private readonly Mock _fusionContextResolverMock = new(); + private readonly Mock _fusionAppsClientMock = new(); + public static Dictionary TestUsersDictionary = new(); + private static TestFactory? _sInstance; + private static readonly object _sPadlock = new(); + + public static TestFactory Instance { - private const string AuthenticatedUserOid = "00000000-0000-0000-0000-000000000007"; - private const string IntegrationTestEnvironment = "IntegrationTests"; - private readonly string _localDbConnectionString; - private readonly string _configPath; - private readonly List _teardownList = new(); - private readonly List _disposables = new(); - private readonly Mock _fusionContextResolverMock = new(); - private readonly Mock _fusionAppsClientMock = new(); - public static Dictionary TestUsersDictionary = new(); - private static TestFactory? _sInstance; - private static readonly object _sPadlock = new(); - - public static TestFactory Instance + get { - get + if (_sInstance == null) { - if (_sInstance == null) + lock (_sPadlock) { - lock (_sPadlock) + if (_sInstance == null) { - if (_sInstance == null) - { - _sInstance = new TestFactory(); - } + _sInstance = new TestFactory(); } } - - return _sInstance; } + + return _sInstance; } + } - private TestFactory() + private TestFactory() + { + var projectDir = Directory.GetCurrentDirectory(); + _localDbConnectionString = GetTestLocalDbConnectionString(projectDir); + _configPath = Path.Combine(projectDir, "appsettings.json"); + SetupTestUsers(); + } + + public new void Dispose() + { + // Run teardown + foreach (var action in _teardownList) { - var projectDir = Directory.GetCurrentDirectory(); - _localDbConnectionString = GetTestLocalDbConnectionString(projectDir); - _configPath = Path.Combine(projectDir, "appsettings.json"); - SetupTestUsers(); + action(); } - public new void Dispose() + foreach (var testUser in TestUsersDictionary) { - // Run teardown - foreach (var action in _teardownList) - { - action(); - } - - foreach (var testUser in TestUsersDictionary) - { - testUser.Value.HttpClient.Dispose(); - } - - foreach (var disposable in _disposables) - { - try { disposable.Dispose(); } catch { /* Ignore */ } - } - - //lock (s_padlock) - //{ - // s_instance = null; - //} - - base.Dispose(); + testUser.Value.HttpClient.Dispose(); } - public HttpClient GetHttpClient(UserType userType) + foreach (var disposable in _disposables) { - var testUser = TestUsersDictionary[userType]; + try { disposable.Dispose(); } catch { /* Ignore */ } + } - SetupServiceMock(); + //lock (s_padlock) + //{ + // s_instance = null; + //} - return testUser.HttpClient; - } + base.Dispose(); + } - public TokenProfile? GetTestProfile(UserType userType) => TestUsersDictionary[userType].Profile; + public HttpClient GetHttpClient(UserType userType) + { + var testUser = TestUsersDictionary[userType]; - protected override void ConfigureWebHost(IWebHostBuilder builder) - { - builder.ConfigureTestServices(services => - { - services.AddAuthentication() - .AddScheme( - IntegrationTestAuthHandler.TestAuthenticationScheme, _ => { }); + SetupServiceMock(); - services.PostConfigureAll(jwtBearerOptions => - jwtBearerOptions.ForwardAuthenticate = IntegrationTestAuthHandler.TestAuthenticationScheme); + return testUser.HttpClient; + } - services.AddScoped(_ => _fusionContextResolverMock.Object); - services.AddScoped(_ => _fusionAppsClientMock.Object); - }); + public TokenProfile? GetTestProfile(UserType userType) => TestUsersDictionary[userType].Profile; - builder.ConfigureServices(services => - { - ReplaceRealDbContextWithTestDbContext(services); + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureTestServices(services => + { + services.AddAuthentication() + .AddScheme( + IntegrationTestAuthHandler.TestAuthenticationScheme, _ => { }); - CreateSeededTestDatabase(services); + services.PostConfigureAll(jwtBearerOptions => + jwtBearerOptions.ForwardAuthenticate = IntegrationTestAuthHandler.TestAuthenticationScheme); - EnsureTestDatabaseDeletedAtTeardown(services); - }); - } + services.AddScoped(_ => _fusionContextResolverMock.Object); + services.AddScoped(_ => _fusionAppsClientMock.Object); + }); - private void ReplaceRealDbContextWithTestDbContext(IServiceCollection services) + builder.ConfigureServices(services => { - var descriptor = services.SingleOrDefault - (d => d.ServiceType == typeof(DbContextOptions)); + ReplaceRealDbContextWithTestDbContext(services); - if (descriptor != null) - { - services.Remove(descriptor); - } + CreateSeededTestDatabase(services); - services.AddDbContext(options => options.UseSqlServer(_localDbConnectionString)); - } + EnsureTestDatabaseDeletedAtTeardown(services); + }); + } + + private void ReplaceRealDbContextWithTestDbContext(IServiceCollection services) + { + var descriptor = services.SingleOrDefault + (d => d.ServiceType == typeof(DbContextOptions)); - private static void CreateSeededTestDatabase(IServiceCollection services) + if (descriptor != null) { - using var serviceProvider = services.BuildServiceProvider(); - using var scope = serviceProvider.CreateScope(); - var scopeServiceProvider = scope.ServiceProvider; - var dbContext = scopeServiceProvider.GetRequiredService(); + services.Remove(descriptor); + } - dbContext.Database.EnsureDeleted(); + services.AddDbContext(options => options.UseSqlServer(_localDbConnectionString)); + } - dbContext.Database.SetCommandTimeout(TimeSpan.FromMinutes(5)); + private static void CreateSeededTestDatabase(IServiceCollection services) + { + using var serviceProvider = services.BuildServiceProvider(); + using var scope = serviceProvider.CreateScope(); + var scopeServiceProvider = scope.ServiceProvider; + var dbContext = scopeServiceProvider.GetRequiredService(); - dbContext.CreateNewDatabaseWithCorrectSchema(); + dbContext.Database.EnsureDeleted(); - var migrations = dbContext.Database.GetPendingMigrations(); + dbContext.Database.SetCommandTimeout(TimeSpan.FromMinutes(5)); - if (migrations.Any()) - { - dbContext.Database.Migrate(); - } + dbContext.CreateNewDatabaseWithCorrectSchema(); - SeedData(dbContext, scopeServiceProvider); - } + var migrations = dbContext.Database.GetPendingMigrations(); - private static void SeedData(ProjectExecutionPortalContext dbContext, IServiceProvider scopeServiceProvider) + if (migrations.Any()) { - dbContext.Seed(scopeServiceProvider); + dbContext.Database.Migrate(); } - private void EnsureTestDatabaseDeletedAtTeardown(IServiceCollection services) - => _teardownList.Add(() => - { - using var dbContext = DatabaseContext(services); - dbContext.Database.EnsureDeleted(); - }); + SeedData(dbContext, scopeServiceProvider); + } - private ProjectExecutionPortalContext DatabaseContext(IServiceCollection services) - { - services.AddDbContext(options => options.UseSqlServer(_localDbConnectionString)); + private static void SeedData(ProjectExecutionPortalContext dbContext, IServiceProvider scopeServiceProvider) + { + dbContext.Seed(scopeServiceProvider); + } - var sp = services.BuildServiceProvider(); - _disposables.Add(sp); + private void EnsureTestDatabaseDeletedAtTeardown(IServiceCollection services) + => _teardownList.Add(() => + { + using var dbContext = DatabaseContext(services); + dbContext.Database.EnsureDeleted(); + }); - var spScope = sp.CreateScope(); - _disposables.Add(spScope); + private ProjectExecutionPortalContext DatabaseContext(IServiceCollection services) + { + services.AddDbContext(options => options.UseSqlServer(_localDbConnectionString)); - return spScope.ServiceProvider.GetRequiredService(); - } + var sp = services.BuildServiceProvider(); + _disposables.Add(sp); - private static string GetTestLocalDbConnectionString(string projectDir) - { - const string DbName = "ProjectPortalIntegrationTestsDB2"; - var dbPath = Path.Combine(projectDir, $"{DbName}.mdf"); + var spScope = sp.CreateScope(); + _disposables.Add(spScope); - // Set Initial Catalog to be able to delete database! - return $"Server=(LocalDB)\\MSSQLLocalDB;Initial Catalog={DbName};Integrated Security=true;AttachDbFileName={dbPath}"; - } + return spScope.ServiceProvider.GetRequiredService(); + } - //private string GetSqlLiteConnectionString() - //{ - // return "\"Filename=:memory:\""; - //} + private static string GetTestLocalDbConnectionString(string projectDir) + { + const string DbName = "ProjectPortalIntegrationTestsDB2"; + var dbPath = Path.Combine(projectDir, $"{DbName}.mdf"); - private void SetupServiceMock() - { - _fusionAppsClientMock.Setup(service => service.GetAppsAsync(default)) - .Returns(Task.FromResult>(FusionAppApiData.ValidFusionApps)); + // Set Initial Catalog to be able to delete database! + return $"Server=(LocalDB)\\MSSQLLocalDB;Initial Catalog={DbName};Integrated Security=true;AttachDbFileName={dbPath}"; + } - _fusionAppsClientMock.Setup(service => service.GetAppAsync(It.IsAny(), default)) - .Returns((string appKey, CancellationToken token) => - { - return Task.FromResult(FusionAppApiData.ValidFusionApps.FirstOrDefault(x => x.AppKey == appKey))!; - }); + //private string GetSqlLiteConnectionString() + //{ + // return "\"Filename=:memory:\""; + //} - _fusionContextResolverMock.Setup(service => service.ResolveContextAsync(It.IsAny(), It.IsAny())) - .Returns((ContextIdentifier contextIdentifier, FusionContextType type) => - { - return Task.FromResult(FusionContextApiData.ValidFusionContexts.FirstOrDefault(x => x.ExternalId == contextIdentifier.Identifier)); - }); + private void SetupServiceMock() + { + _fusionAppsClientMock.Setup(service => service.GetAppsAsync(default)) + .Returns(Task.FromResult>(FusionAppApiData.ValidFusionApps)); - _fusionContextResolverMock.Setup(service => service.GetContextAsync(It.IsAny())) - .Returns((Guid contextId) => - { - return Task.FromResult(FusionContextApiData.ValidFusionContexts.FirstOrDefault(x => x.Id == contextId))!; - }); - } + _fusionAppsClientMock.Setup(service => service.GetAppAsync(It.IsAny(), default)) + .Returns((string appKey, CancellationToken token) => + { + return Task.FromResult(FusionAppApiData.ValidFusionApps.FirstOrDefault(x => x.AppKey == appKey))!; + }); - private void SetupTestUsers() - { - SetupAnonymousUser(); - SetupAuthenticatedUser(); - SetupAdministratorUser(); + _fusionContextResolverMock.Setup(service => service.ResolveContextAsync(It.IsAny(), It.IsAny())) + .Returns((ContextIdentifier contextIdentifier, FusionContextType type) => + { + return Task.FromResult(FusionContextApiData.ValidFusionContexts.FirstOrDefault(x => x.ExternalId == contextIdentifier.Identifier)); + }); - var webHostBuilder = WithWebHostBuilder(builder => + _fusionContextResolverMock.Setup(service => service.GetContextAsync(It.IsAny())) + .Returns((Guid contextId) => { - builder.UseEnvironment(IntegrationTestEnvironment); - builder.ConfigureAppConfiguration((_, conf) => conf - .AddJsonFile(_configPath) - .AddUserSecrets()); + return Task.FromResult(FusionContextApiData.ValidFusionContexts.FirstOrDefault(x => x.Id == contextId))!; }); + } - CreateAuthenticatedHttpClients(webHostBuilder); - } + private void SetupTestUsers() + { + SetupAnonymousUser(); + SetupAuthenticatedUser(); + SetupAdministratorUser(); - private static void CreateAuthenticatedHttpClients(WebApplicationFactory webHostBuilder) + var webHostBuilder = WithWebHostBuilder(builder => { - foreach (var testUser in TestUsersDictionary.Values) - { - testUser.HttpClient = webHostBuilder.CreateClient(); + builder.UseEnvironment(IntegrationTestEnvironment); + builder.ConfigureAppConfiguration((_, conf) => conf + .AddJsonFile(_configPath) + .AddUserSecrets()); + }); - AuthenticateUser(testUser); - } - } + CreateAuthenticatedHttpClients(webHostBuilder); + } - private static void SetupAuthenticatedUser() - => TestUsersDictionary.Add(UserType.Authenticated, - new TestUser - { - Profile = - new TokenProfile - { - FirstName = "Authenticated", - LastName = "Authenticated", - Oid = AuthenticatedUserOid - }, - }); - - private static void SetupAdministratorUser() - => TestUsersDictionary.Add(UserType.Administrator, - new TestUser - { - Profile = - new TokenProfile - { - FirstName = "Admin", - LastName = "Straterson", - Oid = AuthenticatedUserOid, - AppRoles = new[] { Scopes.ProjectPortalAdmin } - }, - }); - - private static void SetupAnonymousUser() => TestUsersDictionary.Add(UserType.Anonymous, new TestUser { Profile = null }); - - private static void AuthenticateUser(ITestUser user) + private static void CreateAuthenticatedHttpClients(WebApplicationFactory webHostBuilder) + { + foreach (var testUser in TestUsersDictionary.Values) { - if (user.Profile != null) + testUser.HttpClient = webHostBuilder.CreateClient(); + + AuthenticateUser(testUser); + } + } + + private static void SetupAuthenticatedUser() + => TestUsersDictionary.Add(UserType.Authenticated, + new TestUser { - user.HttpClient.DefaultRequestHeaders.Add("Authorization", user.Profile.CreateBearerToken()); - } + Profile = + new TokenProfile + { + FirstName = "Authenticated", + LastName = "Authenticated", + Oid = AuthenticatedUserOid + }, + }); + + private static void SetupAdministratorUser() + => TestUsersDictionary.Add(UserType.Administrator, + new TestUser + { + Profile = + new TokenProfile + { + FirstName = "Admin", + LastName = "Straterson", + Oid = AuthenticatedUserOid, + AppRoles = new[] { Scopes.ProjectPortalAdmin } + }, + }); + + private static void SetupAnonymousUser() => TestUsersDictionary.Add(UserType.Anonymous, new TestUser { Profile = null }); + + private static void AuthenticateUser(ITestUser user) + { + if (user.Profile != null) + { + user.HttpClient.DefaultRequestHeaders.Add("Authorization", user.Profile.CreateBearerToken()); } } -} +} \ No newline at end of file