diff --git a/backend/api/ApiEndpointTransformer.cs b/backend/api/ApiEndpointTransformer.cs index 9209715f1..a123db319 100644 --- a/backend/api/ApiEndpointTransformer.cs +++ b/backend/api/ApiEndpointTransformer.cs @@ -10,6 +10,6 @@ public class ApiEndpointTransformer : IOutboundParameterTransformer return string.Empty; } var endpoint = value.ToString(); - return Regex.Replace(endpoint!, "([a-z])([A-Z])", o => string.Format("{0}-{1}", o.Groups[1].Value, o.Groups[2].Value)); + return Regex.Replace(endpoint!, "([a-z])([A-Z])", o => $"{o.Groups[1].Value}-{o.Groups[2].Value}"); } } diff --git a/backend/api/Authorization/ApplicationRoleAuthorizationHandler.cs b/backend/api/Authorization/ApplicationRoleAuthorizationHandler.cs index aad8504dd..3fb865b62 100644 --- a/backend/api/Authorization/ApplicationRoleAuthorizationHandler.cs +++ b/backend/api/Authorization/ApplicationRoleAuthorizationHandler.cs @@ -11,30 +11,18 @@ namespace api.Authorization; -public class ApplicationRoleAuthorizationHandler : AuthorizationHandler +public class ApplicationRoleAuthorizationHandler( + IProjectAccessRepository projectAccessRepository, + IHttpContextAccessor httpContextAccessor, + ILogger logger) + : AuthorizationHandler { - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IProjectAccessRepository _projectAccessRepository; - private readonly ILogger _logger; - - - - public ApplicationRoleAuthorizationHandler( - IProjectAccessRepository projectAccessRepository, - IHttpContextAccessor httpContextAccessor, - ILogger logger - ) - { - _httpContextAccessor = httpContextAccessor; - _logger = logger; - _projectAccessRepository = projectAccessRepository; - } protected override async Task HandleRequirementAsync( AuthorizationHandlerContext context, ApplicationRoleRequirement requirement ) { - var requestPath = _httpContextAccessor.HttpContext?.Request.Path; + var requestPath = httpContextAccessor.HttpContext?.Request.Path; // Accessing the swagger documentation is always allowed. if (IsAccessingSwagger(requestPath)) @@ -134,7 +122,7 @@ List userRoles private ActionType? GetActionTypeFromEndpoint() { - var endpoint = _httpContextAccessor.HttpContext?.GetEndpoint(); + var endpoint = httpContextAccessor.HttpContext?.GetEndpoint(); if (endpoint == null) { return null; } var controllerActionDescriptor = endpoint.Metadata.GetMetadata(); @@ -149,7 +137,7 @@ List userRoles private async Task GetCurrentProject(AuthorizationHandlerContext context) { - var projectId = _httpContextAccessor.HttpContext?.Request.RouteValues["projectId"]; + var projectId = httpContextAccessor.HttpContext?.Request.RouteValues["projectId"]; if (projectId == null) { return null; @@ -160,7 +148,7 @@ List userRoles return null; } - var project = await _projectAccessRepository.GetProjectById(projectIdGuid); + var project = await projectAccessRepository.GetProjectById(projectIdGuid); // /* // Some projects have the external id set as the id. @@ -186,7 +174,7 @@ List userRoles { context.Fail(); var username = context.User.Identity!.Name; - _logger.LogWarning( + logger.LogWarning( "User '{Username}' attempted to access '{RequestPath}' but was not authorized " + "- one of the following roles '{RequiredRoles}' is required , while user has the roles '{UserRoles}'", username, @@ -198,7 +186,7 @@ List userRoles private void HandleUnauthenticatedRequest(AuthorizationHandlerContext context, PathString? requestPath) { - _logger.LogWarning("An unauthenticated user attempted to access '{RequestPath}'", requestPath); + logger.LogWarning("An unauthenticated user attempted to access '{RequestPath}'", requestPath); context.Fail(); } } diff --git a/backend/api/Authorization/ApplicationRolePolicyProvider.cs b/backend/api/Authorization/ApplicationRolePolicyProvider.cs index 0c7c7f23d..057480cff 100644 --- a/backend/api/Authorization/ApplicationRolePolicyProvider.cs +++ b/backend/api/Authorization/ApplicationRolePolicyProvider.cs @@ -1,5 +1,3 @@ -using System.Diagnostics; - using Microsoft.AspNetCore.Authorization; namespace api.Authorization; diff --git a/backend/api/Authorization/ApplicationRoleRequirement.cs b/backend/api/Authorization/ApplicationRoleRequirement.cs index 625e7a532..0ba9b80d8 100644 --- a/backend/api/Authorization/ApplicationRoleRequirement.cs +++ b/backend/api/Authorization/ApplicationRoleRequirement.cs @@ -2,14 +2,9 @@ namespace api.Authorization; -public class ApplicationRoleRequirement : IAuthorizationRequirement +public class ApplicationRoleRequirement(List roles) : IAuthorizationRequirement { - public ApplicationRoleRequirement(List roles) - { - Roles = roles; - } - public static ApplicationRole DefaultApplicationRole { get; } = ApplicationRole.Admin; - public List Roles { get; private set; } + public List Roles { get; private set; } = roles; } diff --git a/backend/api/Authorization/ClaimsMiddleware.cs b/backend/api/Authorization/ClaimsMiddleware.cs index d0066ab25..76403dc40 100644 --- a/backend/api/Authorization/ClaimsMiddleware.cs +++ b/backend/api/Authorization/ClaimsMiddleware.cs @@ -6,23 +6,17 @@ namespace api.Authorization; -public class ClaimsMiddleware +public class ClaimsMiddleware( + RequestDelegate nextMiddleware, + ILogger logger) { - public static readonly string ApplicationRoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; - private readonly ILogger _logger; - private readonly RequestDelegate _nextMiddleware; - public ClaimsMiddleware(RequestDelegate nextMiddleware, - ILogger logger, - IConfiguration configuration) - { - _nextMiddleware = nextMiddleware; - _logger = logger; - } + public const string ApplicationRoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; + public async Task InvokeAsync(HttpContext httpContext, CurrentUser currentUser) { if (httpContext.User == null) { - _logger.LogError("User null"); + logger.LogError("User null"); } currentUser.Username = httpContext.User?.Identity?.Name; @@ -34,10 +28,10 @@ public async Task InvokeAsync(HttpContext httpContext, CurrentUser currentUser) } else { - _logger.LogError("Unauthenticated access attempted on: " + httpContext.Request.Path); + logger.LogError("Unauthenticated access attempted on: " + httpContext.Request.Path); } - await _nextMiddleware(httpContext); + await nextMiddleware(httpContext); } private void SetAppRoleClaims(HttpContext httpContext) @@ -50,7 +44,7 @@ private void SetAppRoleClaims(HttpContext httpContext) var fusionApplicationRole = RoleForAccountType(httpContext); if (fusionApplicationRole != null) { - _logger.LogInformation("Fusion Application Role: " + fusionApplicationRole.Value); + logger.LogInformation("Fusion Application Role: " + fusionApplicationRole.Value); } var applicationRoleClaims = applicationRoles @@ -59,12 +53,12 @@ private void SetAppRoleClaims(HttpContext httpContext) var rolesAsString = string.Join(",", applicationRoleClaims.Select(x => x.Value.ToString())); - _logger.LogInformation("Application Roles for User {UserName}: {roles}", httpContext.User?.Identity?.Name, rolesAsString); + logger.LogInformation("Application Roles for User {UserName}: {roles}", httpContext.User?.Identity?.Name, rolesAsString); var claimsIdentity = httpContext.User?.Identity as ClaimsIdentity; if (claimsIdentity == null) { - _logger.LogError("ClaimsIdentity null"); + logger.LogError("ClaimsIdentity null"); return; } claimsIdentity.AddClaims(applicationRoleClaims); @@ -81,23 +75,23 @@ private void SetAppRoleClaims(HttpContext httpContext) } if (httpContext.User.IsAccountType(FusionAccountType.Employee)) { - _logger.LogInformation("Check for Fusion Account Type: " + ApplicationRole.User); + logger.LogInformation("Check for Fusion Account Type: " + ApplicationRole.User); return ApplicationRole.User; } if (httpContext.User.IsAccountType(FusionAccountType.External)) { - _logger.LogInformation("Check for Fusion Account Type: " + ApplicationRole.User); + logger.LogInformation("Check for Fusion Account Type: " + ApplicationRole.User); return ApplicationRole.Admin; } if (httpContext.User.IsAccountType(FusionAccountType.Consultant)) { - _logger.LogInformation("Check for Fusion Account Type: " + ApplicationRole.User); + logger.LogInformation("Check for Fusion Account Type: " + ApplicationRole.User); return ApplicationRole.ReadOnly; } - _logger.LogInformation("Check for Fusion Account Type: null"); + logger.LogInformation("Check for Fusion Account Type: null"); return null; } diff --git a/backend/api/Context/ChangeLogService.cs b/backend/api/Context/ChangeLogService.cs index 778a0e5d9..b08f8ab32 100644 --- a/backend/api/Context/ChangeLogService.cs +++ b/backend/api/Context/ChangeLogService.cs @@ -12,7 +12,7 @@ namespace api.Context; public static class ChangeLogService { - private static readonly IReadOnlyList PropertyNamesToIgnore = new List { "ModifyTime", "Bar", "Baz" }; + private static readonly IReadOnlyList PropertyNamesToIgnore = new List { "ModifyTime" }; public static List GenerateChangeLogs(DcdDbContext dbContext, CurrentUser? currentUser, DateTime utcNow) { var changes = dbContext.ChangeTracker diff --git a/backend/api/Controllers/Assets/DrainageStrategiesController.cs b/backend/api/Controllers/Assets/DrainageStrategiesController.cs index ffa56c6dd..f7a8d6682 100644 --- a/backend/api/Controllers/Assets/DrainageStrategiesController.cs +++ b/backend/api/Controllers/Assets/DrainageStrategiesController.cs @@ -15,20 +15,11 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class DrainageStrategiesController : ControllerBase +public class DrainageStrategiesController( + IDrainageStrategyService drainageStrategyService, + IDrainageStrategyTimeSeriesService drainageStrategyTimeSeriesService) + : ControllerBase { - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IDrainageStrategyTimeSeriesService _drainageStrategyTimeSeriesService; - - public DrainageStrategiesController( - IDrainageStrategyService drainageStrategyService, - IDrainageStrategyTimeSeriesService drainageStrategyTimeSeriesService - ) - { - _drainageStrategyService = drainageStrategyService; - _drainageStrategyTimeSeriesService = drainageStrategyTimeSeriesService; - } - [HttpPut("{drainageStrategyId}")] public async Task UpdateDrainageStrategy( [FromRoute] Guid projectId, @@ -36,7 +27,7 @@ public async Task UpdateDrainageStrategy( [FromRoute] Guid drainageStrategyId, [FromBody] UpdateDrainageStrategyDto dto) { - return await _drainageStrategyService.UpdateDrainageStrategy(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyService.UpdateDrainageStrategy(projectId, caseId, drainageStrategyId, dto); } [HttpPost("{drainageStrategyId}/production-profile-oil/")] @@ -46,7 +37,7 @@ public async Task CreateProductionProfileOil( [FromRoute] Guid drainageStrategyId, [FromBody] CreateProductionProfileOilDto dto) { - return await _drainageStrategyTimeSeriesService.CreateProductionProfileOil(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateProductionProfileOil(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/production-profile-oil/{profileId}")] @@ -57,7 +48,7 @@ public async Task UpdateProductionProfileOil( [FromRoute] Guid profileId, [FromBody] UpdateProductionProfileOilDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateProductionProfileOil(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateProductionProfileOil(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/additional-production-profile-oil/")] @@ -67,7 +58,7 @@ public async Task CreateAdditionalProductionP [FromRoute] Guid drainageStrategyId, [FromBody] CreateAdditionalProductionProfileOilDto dto) { - return await _drainageStrategyTimeSeriesService.CreateAdditionalProductionProfileOil(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateAdditionalProductionProfileOil(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/additional-production-profile-oil/{profileId}")] @@ -78,7 +69,7 @@ public async Task UpdateAdditionalProductionP [FromRoute] Guid profileId, [FromBody] UpdateAdditionalProductionProfileOilDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateAdditionalProductionProfileOil(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateAdditionalProductionProfileOil(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/production-profile-gas/")] @@ -88,7 +79,7 @@ public async Task CreateProductionProfileGas( [FromRoute] Guid drainageStrategyId, [FromBody] CreateProductionProfileGasDto dto) { - return await _drainageStrategyTimeSeriesService.CreateProductionProfileGas(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateProductionProfileGas(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/production-profile-gas/{profileId}")] @@ -99,7 +90,7 @@ public async Task UpdateProductionProfileGas( [FromRoute] Guid profileId, [FromBody] UpdateProductionProfileGasDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateProductionProfileGas(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateProductionProfileGas(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/additional-production-profile-gas/")] @@ -109,7 +100,7 @@ public async Task CreateAdditionalProductionP [FromRoute] Guid drainageStrategyId, [FromBody] CreateAdditionalProductionProfileGasDto dto) { - return await _drainageStrategyTimeSeriesService.CreateAdditionalProductionProfileGas(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateAdditionalProductionProfileGas(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/additional-production-profile-gas/{profileId}")] @@ -120,7 +111,7 @@ public async Task UpdateAdditionalProductionP [FromRoute] Guid profileId, [FromBody] UpdateAdditionalProductionProfileGasDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateAdditionalProductionProfileGas(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateAdditionalProductionProfileGas(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/production-profile-water/")] @@ -130,7 +121,7 @@ public async Task CreateProductionProfileWater( [FromRoute] Guid drainageStrategyId, [FromBody] CreateProductionProfileWaterDto dto) { - return await _drainageStrategyTimeSeriesService.CreateProductionProfileWater(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateProductionProfileWater(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/production-profile-water/{profileId}")] @@ -141,7 +132,7 @@ public async Task UpdateProductionProfileWater( [FromRoute] Guid profileId, [FromBody] UpdateProductionProfileWaterDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateProductionProfileWater(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateProductionProfileWater(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/production-profile-water-injection/")] @@ -151,7 +142,7 @@ public async Task CreateProductionProfileWat [FromRoute] Guid drainageStrategyId, [FromBody] CreateProductionProfileWaterInjectionDto dto) { - return await _drainageStrategyTimeSeriesService.CreateProductionProfileWaterInjection(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateProductionProfileWaterInjection(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/production-profile-water-injection/{profileId}")] @@ -162,7 +153,7 @@ public async Task UpdateProductionProfileWat [FromRoute] Guid profileId, [FromBody] UpdateProductionProfileWaterInjectionDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateProductionProfileWaterInjection(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateProductionProfileWaterInjection(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/fuel-flaring-and-losses-override/")] @@ -172,7 +163,7 @@ public async Task CreateFuelFlaringAndLossesOve [FromRoute] Guid drainageStrategyId, [FromBody] CreateFuelFlaringAndLossesOverrideDto dto) { - return await _drainageStrategyTimeSeriesService.CreateFuelFlaringAndLossesOverride(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateFuelFlaringAndLossesOverride(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/fuel-flaring-and-losses-override/{profileId}")] @@ -183,7 +174,7 @@ public async Task UpdateFuelFlaringAndLossesOve [FromRoute] Guid profileId, [FromBody] UpdateFuelFlaringAndLossesOverrideDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateFuelFlaringAndLossesOverride(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateFuelFlaringAndLossesOverride(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/net-sales-gas-override/")] @@ -193,7 +184,7 @@ public async Task CreateNetSalesGasOverride( [FromRoute] Guid drainageStrategyId, [FromBody] CreateNetSalesGasOverrideDto dto) { - return await _drainageStrategyTimeSeriesService.CreateNetSalesGasOverride(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateNetSalesGasOverride(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/net-sales-gas-override/{profileId}")] @@ -204,7 +195,7 @@ public async Task UpdateNetSalesGasOverride( [FromRoute] Guid profileId, [FromBody] UpdateNetSalesGasOverrideDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateNetSalesGasOverride(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateNetSalesGasOverride(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/co2-emissions-override/")] @@ -214,7 +205,7 @@ public async Task CreateCo2EmissionsOverride( [FromRoute] Guid drainageStrategyId, [FromBody] CreateCo2EmissionsOverrideDto dto) { - return await _drainageStrategyTimeSeriesService.CreateCo2EmissionsOverride(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateCo2EmissionsOverride(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/co2-emissions-override/{profileId}")] @@ -225,7 +216,7 @@ public async Task UpdateCo2EmissionsOverride( [FromRoute] Guid profileId, [FromBody] UpdateCo2EmissionsOverrideDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateCo2EmissionsOverride(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateCo2EmissionsOverride(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/imported-electricity-override/")] @@ -235,7 +226,7 @@ public async Task CreateImportedElectricityOverr [FromRoute] Guid drainageStrategyId, [FromBody] CreateImportedElectricityOverrideDto dto) { - return await _drainageStrategyTimeSeriesService.CreateImportedElectricityOverride(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateImportedElectricityOverride(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/imported-electricity-override/{profileId}")] @@ -246,7 +237,7 @@ public async Task UpdateImportedElectricityOverr [FromRoute] Guid profileId, [FromBody] UpdateImportedElectricityOverrideDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateImportedElectricityOverride(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateImportedElectricityOverride(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/deferred-oil-production/")] @@ -256,7 +247,7 @@ public async Task CreateDeferredOilProduction( [FromRoute] Guid drainageStrategyId, [FromBody] CreateDeferredOilProductionDto dto) { - return await _drainageStrategyTimeSeriesService.CreateDeferredOilProduction(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateDeferredOilProduction(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/deferred-oil-production/{profileId}")] @@ -267,7 +258,7 @@ public async Task UpdateDeferredOilProduction( [FromRoute] Guid profileId, [FromBody] UpdateDeferredOilProductionDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateDeferredOilProduction(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateDeferredOilProduction(projectId, caseId, drainageStrategyId, profileId, dto); } [HttpPost("{drainageStrategyId}/deferred-gas-production/")] @@ -277,7 +268,7 @@ public async Task CreateDeferredGasProduction( [FromRoute] Guid drainageStrategyId, [FromBody] CreateDeferredGasProductionDto dto) { - return await _drainageStrategyTimeSeriesService.CreateDeferredGasProduction(projectId, caseId, drainageStrategyId, dto); + return await drainageStrategyTimeSeriesService.CreateDeferredGasProduction(projectId, caseId, drainageStrategyId, dto); } [HttpPut("{drainageStrategyId}/deferred-gas-production/{profileId}")] @@ -288,6 +279,6 @@ public async Task UpdateDeferredGasProduction( [FromRoute] Guid profileId, [FromBody] UpdateDeferredGasProductionDto dto) { - return await _drainageStrategyTimeSeriesService.UpdateDeferredGasProduction(projectId, caseId, drainageStrategyId, profileId, dto); + return await drainageStrategyTimeSeriesService.UpdateDeferredGasProduction(projectId, caseId, drainageStrategyId, profileId, dto); } } diff --git a/backend/api/Controllers/Assets/ExplorationsController.cs b/backend/api/Controllers/Assets/ExplorationsController.cs index acf208e03..cae8844b5 100644 --- a/backend/api/Controllers/Assets/ExplorationsController.cs +++ b/backend/api/Controllers/Assets/ExplorationsController.cs @@ -2,7 +2,6 @@ using api.Dtos; using api.Services; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -16,20 +15,11 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class ExplorationsController : ControllerBase +public class ExplorationsController( + IExplorationService explorationService, + IExplorationTimeSeriesService explorationTimeSeriesService) + : ControllerBase { - private readonly IExplorationService _explorationService; - private readonly IExplorationTimeSeriesService _explorationTimeSeriesService; - - public ExplorationsController( - IExplorationService explorationService, - IExplorationTimeSeriesService explorationTimeSeriesService - ) - { - _explorationService = explorationService; - _explorationTimeSeriesService = explorationTimeSeriesService; - } - [HttpPut("{explorationId}")] public async Task UpdateExploration( [FromRoute] Guid projectId, @@ -37,7 +27,7 @@ public async Task UpdateExploration( [FromRoute] Guid explorationId, [FromBody] UpdateExplorationDto dto) { - return await _explorationService.UpdateExploration(projectId, caseId, explorationId, dto); + return await explorationService.UpdateExploration(projectId, caseId, explorationId, dto); } [HttpPut("{explorationId}/wells/{wellId}/drilling-schedule/{drillingScheduleId}")] @@ -49,7 +39,7 @@ public async Task UpdateExplorationWellDrillingSchedule( [FromRoute] Guid drillingScheduleId, [FromBody] UpdateDrillingScheduleDto dto) { - return await _explorationService.UpdateExplorationWellDrillingSchedule(projectId, caseId, explorationId, wellId, drillingScheduleId, dto); + return await explorationService.UpdateExplorationWellDrillingSchedule(projectId, caseId, explorationId, wellId, drillingScheduleId, dto); } [HttpPost("{explorationId}/wells/{wellId}/drilling-schedule")] @@ -60,7 +50,7 @@ public async Task CreateExplorationWellDrillingSchedule( [FromRoute] Guid wellId, [FromBody] CreateDrillingScheduleDto dto) { - return await _explorationService.CreateExplorationWellDrillingSchedule(projectId, caseId, explorationId, wellId, dto); + return await explorationService.CreateExplorationWellDrillingSchedule(projectId, caseId, explorationId, wellId, dto); } @@ -73,7 +63,7 @@ public async Task UpdateGAndGAdminCostOverride( [FromRoute] Guid costProfileId, [FromBody] UpdateGAndGAdminCostOverrideDto dto) { - return await _explorationTimeSeriesService.UpdateGAndGAdminCostOverride(projectId, caseId, explorationId, costProfileId, dto); + return await explorationTimeSeriesService.UpdateGAndGAdminCostOverride(projectId, caseId, explorationId, costProfileId, dto); } [HttpPost("{explorationId}/g-and-g-and-admin-cost-override")] @@ -83,7 +73,7 @@ public async Task CreateGAndGAdminCostOverride( [FromRoute] Guid explorationId, [FromBody] CreateGAndGAdminCostOverrideDto dto) { - return await _explorationTimeSeriesService.CreateGAndGAdminCostOverride(projectId, caseId, explorationId, dto); + return await explorationTimeSeriesService.CreateGAndGAdminCostOverride(projectId, caseId, explorationId, dto); } [HttpPut("{explorationId}/seismic-acquisition-and-processing/{costProfileId}")] @@ -94,7 +84,7 @@ public async Task UpdateSeismicAcquisitionAn [FromRoute] Guid costProfileId, [FromBody] UpdateSeismicAcquisitionAndProcessingDto dto) { - return await _explorationTimeSeriesService.UpdateSeismicAcquisitionAndProcessing(projectId, caseId, explorationId, costProfileId, dto); + return await explorationTimeSeriesService.UpdateSeismicAcquisitionAndProcessing(projectId, caseId, explorationId, costProfileId, dto); } [HttpPost("{explorationId}/seismic-acquisition-and-processing")] @@ -104,7 +94,7 @@ public async Task CreateSeismicAcquisitionAn [FromRoute] Guid explorationId, [FromBody] CreateSeismicAcquisitionAndProcessingDto dto) { - return await _explorationTimeSeriesService.CreateSeismicAcquisitionAndProcessing(projectId, caseId, explorationId, dto); + return await explorationTimeSeriesService.CreateSeismicAcquisitionAndProcessing(projectId, caseId, explorationId, dto); } [HttpPut("{explorationId}/country-office-cost/{costProfileId}")] @@ -115,7 +105,7 @@ public async Task UpdateCountryOfficeCost( [FromRoute] Guid costProfileId, [FromBody] UpdateCountryOfficeCostDto dto) { - return await _explorationTimeSeriesService.UpdateCountryOfficeCost(projectId, caseId, explorationId, costProfileId, dto); + return await explorationTimeSeriesService.UpdateCountryOfficeCost(projectId, caseId, explorationId, costProfileId, dto); } [HttpPost("{explorationId}/country-office-cost")] @@ -125,6 +115,6 @@ public async Task CreateCountryOfficeCost( [FromRoute] Guid explorationId, [FromBody] CreateCountryOfficeCostDto dto) { - return await _explorationTimeSeriesService.CreateCountryOfficeCost(projectId, caseId, explorationId, dto); + return await explorationTimeSeriesService.CreateCountryOfficeCost(projectId, caseId, explorationId, dto); } } diff --git a/backend/api/Controllers/Assets/SubstructuresController.cs b/backend/api/Controllers/Assets/SubstructuresController.cs index 769e46325..9ebc75bdd 100644 --- a/backend/api/Controllers/Assets/SubstructuresController.cs +++ b/backend/api/Controllers/Assets/SubstructuresController.cs @@ -2,7 +2,6 @@ using api.Dtos; using api.Services; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -16,20 +15,11 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class SubstructuresController : ControllerBase +public class SubstructuresController( + ISubstructureService substructureService, + ISubstructureTimeSeriesService substructureTimeSeriesService) + : ControllerBase { - private readonly ISubstructureService _substructureService; - private readonly ISubstructureTimeSeriesService _substructureTimeSeriesService; - - public SubstructuresController( - ISubstructureService substructureService, - ISubstructureTimeSeriesService substructureTimeSeriesService - ) - { - _substructureService = substructureService; - _substructureTimeSeriesService = substructureTimeSeriesService; - } - [HttpPut("{substructureId}")] public async Task UpdateSubstructure( [FromRoute] Guid projectId, @@ -37,7 +27,7 @@ public async Task UpdateSubstructure( [FromRoute] Guid substructureId, [FromBody] APIUpdateSubstructureDto dto) { - return await _substructureService.UpdateSubstructure(projectId, caseId, substructureId, dto); + return await substructureService.UpdateSubstructure(projectId, caseId, substructureId, dto); } [HttpPost("{substructureId}/cost-profile-override")] @@ -47,7 +37,7 @@ public async Task CreateSubstructureCostProf [FromRoute] Guid substructureId, [FromBody] CreateSubstructureCostProfileOverrideDto dto) { - return await _substructureTimeSeriesService.CreateSubstructureCostProfileOverride(projectId, caseId, substructureId, dto); + return await substructureTimeSeriesService.CreateSubstructureCostProfileOverride(projectId, caseId, substructureId, dto); } [HttpPut("{substructureId}/cost-profile-override/{costProfileId}")] @@ -58,6 +48,6 @@ public async Task UpdateSubstructureCostProf [FromRoute] Guid costProfileId, [FromBody] UpdateSubstructureCostProfileOverrideDto dto) { - return await _substructureTimeSeriesService.UpdateSubstructureCostProfileOverride(projectId, caseId, substructureId, costProfileId, dto); + return await substructureTimeSeriesService.UpdateSubstructureCostProfileOverride(projectId, caseId, substructureId, costProfileId, dto); } } diff --git a/backend/api/Controllers/Assets/SurfsController.cs b/backend/api/Controllers/Assets/SurfsController.cs index a2aefeefe..46076a6cd 100644 --- a/backend/api/Controllers/Assets/SurfsController.cs +++ b/backend/api/Controllers/Assets/SurfsController.cs @@ -2,7 +2,6 @@ using api.Dtos; using api.Services; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -16,20 +15,10 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class SurfsController : ControllerBase +public class SurfsController( + ISurfService surfService, + ISurfTimeSeriesService surfTimeSeriesService) : ControllerBase { - private readonly ISurfService _surfService; - private readonly ISurfTimeSeriesService _surfTimeSeriesService; - - public SurfsController( - ISurfService surfService, - ISurfTimeSeriesService surfTimeSeriesService - ) - { - _surfService = surfService; - _surfTimeSeriesService = surfTimeSeriesService; - } - [HttpPut("{surfId}")] public async Task UpdateSurf( [FromRoute] Guid projectId, @@ -37,7 +26,7 @@ public async Task UpdateSurf( [FromRoute] Guid surfId, [FromBody] APIUpdateSurfDto dto) { - return await _surfService.UpdateSurf(projectId, caseId, surfId, dto); + return await surfService.UpdateSurf(projectId, caseId, surfId, dto); } [HttpPost("{surfId}/cost-profile-override/")] @@ -47,7 +36,7 @@ public async Task CreateSurfCostProfileOverride( [FromRoute] Guid surfId, [FromBody] CreateSurfCostProfileOverrideDto dto) { - return await _surfTimeSeriesService.CreateSurfCostProfileOverride(projectId, caseId, surfId, dto); + return await surfTimeSeriesService.CreateSurfCostProfileOverride(projectId, caseId, surfId, dto); } [HttpPut("{surfId}/cost-profile-override/{costProfileId}")] @@ -58,6 +47,6 @@ public async Task UpdateSurfCostProfileOverride( [FromRoute] Guid costProfileId, [FromBody] UpdateSurfCostProfileOverrideDto dto) { - return await _surfTimeSeriesService.UpdateSurfCostProfileOverride(projectId, caseId, surfId, costProfileId, dto); + return await surfTimeSeriesService.UpdateSurfCostProfileOverride(projectId, caseId, surfId, costProfileId, dto); } } diff --git a/backend/api/Controllers/Assets/TopsidesController.cs b/backend/api/Controllers/Assets/TopsidesController.cs index 85186d7bc..e82572294 100644 --- a/backend/api/Controllers/Assets/TopsidesController.cs +++ b/backend/api/Controllers/Assets/TopsidesController.cs @@ -2,7 +2,6 @@ using api.Dtos; using api.Services; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -16,20 +15,10 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class TopsidesController : ControllerBase +public class TopsidesController( + ITopsideService topsideService, + ITopsideTimeSeriesService topsideTimeSeriesService) : ControllerBase { - private readonly ITopsideService _topsideService; - private readonly ITopsideTimeSeriesService _topsideTimeSeriesService; - - public TopsidesController( - ITopsideService topsideService, - ITopsideTimeSeriesService topsideTimeSeriesService - ) - { - _topsideService = topsideService; - _topsideTimeSeriesService = topsideTimeSeriesService; - } - [HttpPut("{topsideId}")] public async Task UpdateTopside( [FromRoute] Guid projectId, @@ -37,7 +26,7 @@ public async Task UpdateTopside( [FromRoute] Guid topsideId, [FromBody] APIUpdateTopsideDto dto) { - return await _topsideService.UpdateTopside(projectId, caseId, topsideId, dto); + return await topsideService.UpdateTopside(projectId, caseId, topsideId, dto); } [HttpPost("{topsideId}/cost-profile-override/")] @@ -47,7 +36,7 @@ public async Task CreateTopsideCostProfileOverrid [FromRoute] Guid topsideId, [FromBody] CreateTopsideCostProfileOverrideDto dto) { - return await _topsideTimeSeriesService.CreateTopsideCostProfileOverride(projectId, caseId, topsideId, dto); + return await topsideTimeSeriesService.CreateTopsideCostProfileOverride(projectId, caseId, topsideId, dto); } [HttpPut("{topsideId}/cost-profile-override/{costProfileId}")] @@ -58,6 +47,6 @@ public async Task UpdateTopsideCostProfileOverrid [FromRoute] Guid costProfileId, [FromBody] UpdateTopsideCostProfileOverrideDto dto) { - return await _topsideTimeSeriesService.UpdateTopsideCostProfileOverride(projectId, caseId, topsideId, costProfileId, dto); + return await topsideTimeSeriesService.UpdateTopsideCostProfileOverride(projectId, caseId, topsideId, costProfileId, dto); } } diff --git a/backend/api/Controllers/Assets/TransportsController.cs b/backend/api/Controllers/Assets/TransportsController.cs index cbcf36b51..6c2e349f8 100644 --- a/backend/api/Controllers/Assets/TransportsController.cs +++ b/backend/api/Controllers/Assets/TransportsController.cs @@ -2,7 +2,6 @@ using api.Dtos; using api.Services; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -16,20 +15,10 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class TransportsController : ControllerBase +public class TransportsController( + ITransportService transportService, + ITransportTimeSeriesService transportTimeSeriesService) : ControllerBase { - private readonly ITransportService _transportService; - private readonly ITransportTimeSeriesService _transportTimeSeriesService; - - public TransportsController( - ITransportService transportService, - ITransportTimeSeriesService transportTimeSeriesService - ) - { - _transportService = transportService; - _transportTimeSeriesService = transportTimeSeriesService; - } - [HttpPut("{transportId}")] public async Task UpdateTransport( [FromRoute] Guid projectId, @@ -37,7 +26,7 @@ public async Task UpdateTransport( [FromRoute] Guid transportId, [FromBody] APIUpdateTransportDto dto) { - return await _transportService.UpdateTransport(projectId, caseId, transportId, dto); + return await transportService.UpdateTransport(projectId, caseId, transportId, dto); } [HttpPost("{transportId}/cost-profile-override")] @@ -47,7 +36,7 @@ public async Task CreateTransportCostProfileOve [FromRoute] Guid transportId, [FromBody] CreateTransportCostProfileOverrideDto dto) { - return await _transportTimeSeriesService.CreateTransportCostProfileOverride(projectId, caseId, transportId, dto); + return await transportTimeSeriesService.CreateTransportCostProfileOverride(projectId, caseId, transportId, dto); } [HttpPut("{transportId}/cost-profile-override/{costProfileId}")] @@ -58,6 +47,6 @@ public async Task UpdateTransportCostProfileOve [FromRoute] Guid costProfileId, [FromBody] UpdateTransportCostProfileOverrideDto dto) { - return await _transportTimeSeriesService.UpdateTransportCostProfileOverride(projectId, caseId, transportId, costProfileId, dto); + return await transportTimeSeriesService.UpdateTransportCostProfileOverride(projectId, caseId, transportId, costProfileId, dto); } } diff --git a/backend/api/Controllers/Assets/WellProjectsController.cs b/backend/api/Controllers/Assets/WellProjectsController.cs index dcb4230aa..5c0dec0ab 100644 --- a/backend/api/Controllers/Assets/WellProjectsController.cs +++ b/backend/api/Controllers/Assets/WellProjectsController.cs @@ -2,7 +2,6 @@ using api.Dtos; using api.Services; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -16,20 +15,11 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class WellProjectsController : ControllerBase +public class WellProjectsController( + IWellProjectService wellProjectService, + IWellProjectTimeSeriesService wellProjectTimeSeriesService) + : ControllerBase { - private readonly IWellProjectService _wellProjectService; - private readonly IWellProjectTimeSeriesService _wellProjectTimeSeriesService; - - public WellProjectsController( - IWellProjectService wellProjectService, - IWellProjectTimeSeriesService wellProjectTimeSeriesService - ) - { - _wellProjectService = wellProjectService; - _wellProjectTimeSeriesService = wellProjectTimeSeriesService; - } - [HttpPut("{wellProjectId}")] public async Task UpdateWellProject( [FromRoute] Guid projectId, @@ -37,7 +27,7 @@ public async Task UpdateWellProject( [FromRoute] Guid wellProjectId, [FromBody] UpdateWellProjectDto dto) { - return await _wellProjectService.UpdateWellProject(projectId, caseId, wellProjectId, dto); + return await wellProjectService.UpdateWellProject(projectId, caseId, wellProjectId, dto); } [HttpPut("{wellProjectId}/wells/{wellId}/drilling-schedule/{drillingScheduleId}")] @@ -49,7 +39,7 @@ public async Task UpdateWellProjectWellDrillingSchedule( [FromRoute] Guid drillingScheduleId, [FromBody] UpdateDrillingScheduleDto dto) { - return await _wellProjectService.UpdateWellProjectWellDrillingSchedule(projectId, caseId, wellProjectId, wellId, drillingScheduleId, dto); + return await wellProjectService.UpdateWellProjectWellDrillingSchedule(projectId, caseId, wellProjectId, wellId, drillingScheduleId, dto); } [HttpPost("{wellProjectId}/wells/{wellId}/drilling-schedule")] @@ -60,7 +50,7 @@ public async Task CreateWellProjectWellDrillingSchedule( [FromRoute] Guid wellId, [FromBody] CreateDrillingScheduleDto dto) { - return await _wellProjectService.CreateWellProjectWellDrillingSchedule(projectId, caseId, wellProjectId, wellId, dto); + return await wellProjectService.CreateWellProjectWellDrillingSchedule(projectId, caseId, wellProjectId, wellId, dto); } [HttpPut("{wellProjectId}/oil-producer-cost-profile-override/{costProfileId}")] @@ -71,7 +61,7 @@ public async Task UpdateOilProducerCostProfil [FromRoute] Guid costProfileId, [FromBody] UpdateOilProducerCostProfileOverrideDto dto) { - return await _wellProjectTimeSeriesService.UpdateOilProducerCostProfileOverride(projectId, caseId, wellProjectId, costProfileId, dto); + return await wellProjectTimeSeriesService.UpdateOilProducerCostProfileOverride(projectId, caseId, wellProjectId, costProfileId, dto); } [HttpPut("{wellProjectId}/gas-producer-cost-profile-override/{costProfileId}")] @@ -82,7 +72,7 @@ public async Task UpdateGasProducerCostProfil [FromRoute] Guid costProfileId, [FromBody] UpdateGasProducerCostProfileOverrideDto dto) { - return await _wellProjectTimeSeriesService.UpdateGasProducerCostProfileOverride(projectId, caseId, wellProjectId, costProfileId, dto); + return await wellProjectTimeSeriesService.UpdateGasProducerCostProfileOverride(projectId, caseId, wellProjectId, costProfileId, dto); } [HttpPut("{wellProjectId}/water-injector-cost-profile-override/{costProfileId}")] @@ -93,7 +83,7 @@ public async Task UpdateWaterInjectorCostPr [FromRoute] Guid costProfileId, [FromBody] UpdateWaterInjectorCostProfileOverrideDto dto) { - return await _wellProjectTimeSeriesService.UpdateWaterInjectorCostProfileOverride(projectId, caseId, wellProjectId, costProfileId, dto); + return await wellProjectTimeSeriesService.UpdateWaterInjectorCostProfileOverride(projectId, caseId, wellProjectId, costProfileId, dto); } [HttpPut("{wellProjectId}/gas-injector-cost-profile-override/{costProfileId}")] @@ -104,7 +94,7 @@ public async Task UpdateGasInjectorCostProfil [FromRoute] Guid costProfileId, [FromBody] UpdateGasInjectorCostProfileOverrideDto dto) { - return await _wellProjectTimeSeriesService.UpdateGasInjectorCostProfileOverride(projectId, caseId, wellProjectId, costProfileId, dto); + return await wellProjectTimeSeriesService.UpdateGasInjectorCostProfileOverride(projectId, caseId, wellProjectId, costProfileId, dto); } [HttpPost("{wellProjectId}/oil-producer-cost-profile-override")] @@ -114,7 +104,7 @@ public async Task CreateOilProducerCostProfil [FromRoute] Guid wellProjectId, [FromBody] CreateOilProducerCostProfileOverrideDto dto) { - return await _wellProjectTimeSeriesService.CreateOilProducerCostProfileOverride(projectId, caseId, wellProjectId, dto); + return await wellProjectTimeSeriesService.CreateOilProducerCostProfileOverride(projectId, caseId, wellProjectId, dto); } [HttpPost("{wellProjectId}/gas-producer-cost-profile-override")] @@ -124,7 +114,7 @@ public async Task CreateGasProducerCostProfil [FromRoute] Guid wellProjectId, [FromBody] CreateGasProducerCostProfileOverrideDto dto) { - return await _wellProjectTimeSeriesService.CreateGasProducerCostProfileOverride(projectId, caseId, wellProjectId, dto); + return await wellProjectTimeSeriesService.CreateGasProducerCostProfileOverride(projectId, caseId, wellProjectId, dto); } [HttpPost("{wellProjectId}/water-injector-cost-profile-override")] @@ -134,7 +124,7 @@ public async Task CreateWaterInjectorCostPr [FromRoute] Guid wellProjectId, [FromBody] CreateWaterInjectorCostProfileOverrideDto dto) { - return await _wellProjectTimeSeriesService.CreateWaterInjectorCostProfileOverride(projectId, caseId, wellProjectId, dto); + return await wellProjectTimeSeriesService.CreateWaterInjectorCostProfileOverride(projectId, caseId, wellProjectId, dto); } [HttpPost("{wellProjectId}/gas-injector-cost-profile-override")] @@ -144,6 +134,6 @@ public async Task CreateGasInjectorCostProfil [FromRoute] Guid wellProjectId, [FromBody] CreateGasInjectorCostProfileOverrideDto dto) { - return await _wellProjectTimeSeriesService.CreateGasInjectorCostProfileOverride(projectId, caseId, wellProjectId, dto); + return await wellProjectTimeSeriesService.CreateGasInjectorCostProfileOverride(projectId, caseId, wellProjectId, dto); } } diff --git a/backend/api/Controllers/Attributes/ActionTypeAttribute.cs b/backend/api/Controllers/Attributes/ActionTypeAttribute.cs index b5a8fe5bd..9d738af45 100644 --- a/backend/api/Controllers/Attributes/ActionTypeAttribute.cs +++ b/backend/api/Controllers/Attributes/ActionTypeAttribute.cs @@ -7,12 +7,7 @@ public enum ActionType } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] -public class ActionTypeAttribute : Attribute +public class ActionTypeAttribute(ActionType actionType) : Attribute { - public ActionType ActionType { get; } - - public ActionTypeAttribute(ActionType actionType) - { - ActionType = actionType; - } + public ActionType ActionType { get; } = actionType; } diff --git a/backend/api/Controllers/BlobStorageController.cs b/backend/api/Controllers/BlobStorageController.cs index b2fcbe97a..e53eae2ce 100644 --- a/backend/api/Controllers/BlobStorageController.cs +++ b/backend/api/Controllers/BlobStorageController.cs @@ -10,15 +10,8 @@ ApplicationRole.Admin, ApplicationRole.User )] -public class BlobStorageController : ControllerBase +public class BlobStorageController(IBlobStorageService blobStorageService) : ControllerBase { - private readonly IBlobStorageService _blobStorageService; - - public BlobStorageController(IBlobStorageService blobStorageService) - { - _blobStorageService = blobStorageService; - } - private async Task> UploadImage(Guid projectId, string projectName, Guid? caseId, IFormFile image) { const int maxFileSize = 5 * 1024 * 1024; // 5MB @@ -44,12 +37,12 @@ private async Task> UploadImage(Guid projectId, string pr { if (caseId.HasValue) { - var imageDto = await _blobStorageService.SaveImage(projectId, projectName, image, caseId.Value); + var imageDto = await blobStorageService.SaveImage(projectId, projectName, image, caseId.Value); return Ok(imageDto); } else { - var imageDto = await _blobStorageService.SaveImage(projectId, projectName, image); + var imageDto = await blobStorageService.SaveImage(projectId, projectName, image); return Ok(imageDto); } } @@ -77,7 +70,7 @@ public async Task>> GetImages(Guid projectId, Guid c { try { - var imageDtos = await _blobStorageService.GetCaseImages(caseId); + var imageDtos = await blobStorageService.GetCaseImages(caseId); return Ok(imageDtos); } catch (Exception) @@ -92,7 +85,7 @@ public async Task DeleteCaseImage(Guid imageId) { try { - await _blobStorageService.DeleteImage(imageId); + await blobStorageService.DeleteImage(imageId); return NoContent(); } catch (Exception) @@ -119,7 +112,7 @@ public async Task>> GetProjectImages(Guid projectId) { try { - var imageDtos = await _blobStorageService.GetProjectImages(projectId); + var imageDtos = await blobStorageService.GetProjectImages(projectId); return Ok(imageDtos); } catch (Exception) @@ -134,7 +127,7 @@ public async Task DeleteProjectImage(Guid imageId) { try { - await _blobStorageService.DeleteImage(imageId); + await blobStorageService.DeleteImage(imageId); return NoContent(); } catch (Exception) diff --git a/backend/api/Controllers/CaseGeneratedProfileController.cs b/backend/api/Controllers/CaseGeneratedProfileController.cs index adc9e912b..957625f0f 100644 --- a/backend/api/Controllers/CaseGeneratedProfileController.cs +++ b/backend/api/Controllers/CaseGeneratedProfileController.cs @@ -1,12 +1,7 @@ -using System.Net; - using api.Authorization; using api.Dtos; -using api.Exceptions; -using api.Services; using api.Services.GenerateCostProfiles; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -21,37 +16,27 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Read)] -public class CaseGeneratedProfileController : ControllerBase +public class CaseGeneratedProfileController( + ICo2IntensityProfileService generateCo2IntensityProfile, + ICo2IntensityTotalService generateCo2IntensityTotal, + ICo2DrillingFlaringFuelTotalsService generateCo2DrillingFlaringFuelTotals) + : ControllerBase { - private readonly ICo2IntensityProfileService _generateCo2IntensityProfile; - private readonly ICo2IntensityTotalService _generateCo2IntensityTotal; - private readonly ICo2DrillingFlaringFuelTotalsService _generateCo2DrillingFlaringFuelTotals; - - public CaseGeneratedProfileController( - ICo2IntensityProfileService generateCo2IntensityProfile, - ICo2IntensityTotalService generateCo2IntensityTotal, - ICo2DrillingFlaringFuelTotalsService generateCo2DrillingFlaringFuelTotals) - { - _generateCo2IntensityProfile = generateCo2IntensityProfile; - _generateCo2IntensityTotal = generateCo2IntensityTotal; - _generateCo2DrillingFlaringFuelTotals = generateCo2DrillingFlaringFuelTotals; - } - [HttpGet("co2Intensity")] public async Task GenerateCo2Intensity(Guid caseId) { - return await _generateCo2IntensityProfile.Generate(caseId); + return await generateCo2IntensityProfile.Generate(caseId); } [HttpGet("co2IntensityTotal")] public async Task GenerateCo2IntensityTotal(Guid caseId) { - return await _generateCo2IntensityTotal.Calculate(caseId); + return await generateCo2IntensityTotal.Calculate(caseId); } [HttpGet("co2DrillingFlaringFuelTotals")] public async Task GenerateCo2DrillingFlaringFuelTotals(Guid caseId) { - return await _generateCo2DrillingFlaringFuelTotals.Generate(caseId); + return await generateCo2DrillingFlaringFuelTotals.Generate(caseId); } } diff --git a/backend/api/Controllers/CaseWithAssetsController.cs b/backend/api/Controllers/CaseWithAssetsController.cs index c7ebabf4e..1c9ad078b 100644 --- a/backend/api/Controllers/CaseWithAssetsController.cs +++ b/backend/api/Controllers/CaseWithAssetsController.cs @@ -2,7 +2,6 @@ using api.Dtos; using api.Services; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -16,17 +15,8 @@ namespace api.Controllers; ApplicationRole.ReadOnly, ApplicationRole.User )] -public class CaseWithAssetsController : ControllerBase +public class CaseWithAssetsController(ICaseWithAssetsService caseWithAssetsService) : ControllerBase { - private readonly ICaseWithAssetsService _caseWithAssetsService; - - public CaseWithAssetsController( - ICaseWithAssetsService caseWithAssetsService - ) - { - _caseWithAssetsService = caseWithAssetsService; - } - [HttpGet] [ActionType(ActionType.Read)] public async Task> GetCaseWithAssets( @@ -34,7 +24,7 @@ public async Task> GetCaseWithAssets( [FromRoute] Guid caseId ) { - var dto = await _caseWithAssetsService.GetCaseWithAssetsNoTracking(projectId, caseId); + var dto = await caseWithAssetsService.GetCaseWithAssetsNoTracking(projectId, caseId); return Ok(dto); } } diff --git a/backend/api/Controllers/CasesController.cs b/backend/api/Controllers/CasesController.cs index 0f754e2a2..c819c9d6a 100644 --- a/backend/api/Controllers/CasesController.cs +++ b/backend/api/Controllers/CasesController.cs @@ -2,9 +2,6 @@ using api.Dtos; using api.Services; -using AutoMapper; - -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -18,39 +15,24 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class CasesController : ControllerBase +public class CasesController( + ICaseService caseService, + ICreateCaseService createCaseService, + ICaseTimeSeriesService caseTimeSeriesService, + IDuplicateCaseService duplicateCaseService, + IBlobStorageService blobStorageService) + : ControllerBase { - private readonly ICaseService _caseService; - private readonly ICreateCaseService _createCaseService; - private readonly ICaseTimeSeriesService _caseTimeSeriesService; - private readonly IDuplicateCaseService _duplicateCaseService; - private readonly IBlobStorageService _blobStorageService; - - public CasesController( - ICaseService caseService, - ICreateCaseService createCaseService, - ICaseTimeSeriesService caseTimeSeriesService, - IDuplicateCaseService duplicateCaseService, - IBlobStorageService blobStorageService - ) - { - _caseService = caseService; - _createCaseService = createCaseService; - _caseTimeSeriesService = caseTimeSeriesService; - _duplicateCaseService = duplicateCaseService; - _blobStorageService = blobStorageService; - } - [HttpPost] public async Task CreateCase([FromRoute] Guid projectId, [FromBody] CreateCaseDto caseDto) { - return await _createCaseService.CreateCase(projectId, caseDto); + return await createCaseService.CreateCase(projectId, caseDto); } [HttpPost("copy", Name = "Duplicate")] public async Task DuplicateCase([FromQuery] Guid copyCaseId) { - return await _duplicateCaseService.DuplicateCase(copyCaseId); + return await duplicateCaseService.DuplicateCase(copyCaseId); } [HttpPut("{caseId}")] @@ -60,7 +42,7 @@ public async Task UpdateCase( [FromBody] APIUpdateCaseDto caseDto ) { - return await _caseService.UpdateCase(projectId, caseId, caseDto); + return await caseService.UpdateCase(projectId, caseId, caseDto); } [HttpDelete("{caseId}")] @@ -69,12 +51,12 @@ public async Task DeleteCase( [FromRoute] Guid caseId ) { - var images = await _blobStorageService.GetCaseImages(caseId); + var images = await blobStorageService.GetCaseImages(caseId); foreach (var image in images) { - await _blobStorageService.DeleteImage(image.Id); + await blobStorageService.DeleteImage(image.Id); } - return await _caseService.DeleteCase(projectId, caseId); + return await caseService.DeleteCase(projectId, caseId); } [HttpPut("{caseId}/cessation-wells-cost-override/{costProfileId}")] @@ -85,7 +67,7 @@ public async Task UpdateCessationWellsCostOverrid [FromBody] UpdateCessationWellsCostOverrideDto dto ) { - return await _caseTimeSeriesService.UpdateCessationWellsCostOverride(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateCessationWellsCostOverride(projectId, caseId, costProfileId, dto); } [HttpPut("{caseId}/cessation-offshore-facilities-cost-override/{costProfileId}")] @@ -96,7 +78,7 @@ public async Task UpdateCessationOff [FromBody] UpdateCessationOffshoreFacilitiesCostOverrideDto dto ) { - return await _caseTimeSeriesService.UpdateCessationOffshoreFacilitiesCostOverride(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateCessationOffshoreFacilitiesCostOverride(projectId, caseId, costProfileId, dto); } [HttpPost("{caseId}/cessation-offshore-facilities-cost-override")] @@ -106,7 +88,7 @@ public async Task CreateCessationOff [FromBody] CreateCessationOffshoreFacilitiesCostOverrideDto dto ) { - return await _caseTimeSeriesService.CreateCessationOffshoreFacilitiesCostOverride(projectId, caseId, dto); + return await caseTimeSeriesService.CreateCessationOffshoreFacilitiesCostOverride(projectId, caseId, dto); } [HttpPut("{caseId}/cessation-onshore-facilities-cost-profile/{costProfileId}")] @@ -117,7 +99,7 @@ public async Task UpdateCessationOnsho [FromBody] UpdateCessationOnshoreFacilitiesCostProfileDto dto ) { - return await _caseTimeSeriesService.UpdateCessationOnshoreFacilitiesCostProfile(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateCessationOnshoreFacilitiesCostProfile(projectId, caseId, costProfileId, dto); } [HttpPost("{caseId}/cessation-onshore-facilities-cost-profile")] @@ -127,7 +109,7 @@ public async Task CreateCessationOnsho [FromBody] CreateCessationOnshoreFacilitiesCostProfileDto dto ) { - return await _caseTimeSeriesService.CreateCessationOnshoreFacilitiesCostProfile(projectId, caseId, dto); + return await caseTimeSeriesService.CreateCessationOnshoreFacilitiesCostProfile(projectId, caseId, dto); } [HttpPost("{caseId}/cessation-wells-cost-override")] @@ -137,7 +119,7 @@ public async Task CreateCessationWellsCostOverrid [FromBody] CreateCessationWellsCostOverrideDto dto ) { - return await _caseTimeSeriesService.CreateCessationWellsCostOverride(projectId, caseId, dto); + return await caseTimeSeriesService.CreateCessationWellsCostOverride(projectId, caseId, dto); } [HttpPost("{caseId}/total-feasibility-and-concept-studies-override")] @@ -147,7 +129,7 @@ public async Task CreateTotalFeasi [FromBody] CreateTotalFeasibilityAndConceptStudiesOverrideDto dto ) { - return await _caseTimeSeriesService.CreateTotalFeasibilityAndConceptStudiesOverride(projectId, caseId, dto); + return await caseTimeSeriesService.CreateTotalFeasibilityAndConceptStudiesOverride(projectId, caseId, dto); } [HttpPost("{caseId}/total-feed-studies-override")] @@ -157,7 +139,7 @@ public async Task CreateTotalFEEDStudiesOverride( [FromBody] CreateTotalFEEDStudiesOverrideDto dto ) { - return await _caseTimeSeriesService.CreateTotalFEEDStudiesOverride(projectId, caseId, dto); + return await caseTimeSeriesService.CreateTotalFEEDStudiesOverride(projectId, caseId, dto); } [HttpPost("{caseId}/total-other-studies-cost-profile")] @@ -167,7 +149,7 @@ public async Task CreateTotalOtherStudiesCostPr [FromBody] CreateTotalOtherStudiesCostProfileDto dto ) { - return await _caseTimeSeriesService.CreateTotalOtherStudiesCostProfile(projectId, caseId, dto); + return await caseTimeSeriesService.CreateTotalOtherStudiesCostProfile(projectId, caseId, dto); } [HttpPost("{caseId}/historic-cost-cost-profile")] @@ -177,7 +159,7 @@ public async Task CreateHistoricCostCostProfile( [FromBody] CreateHistoricCostCostProfileDto dto ) { - return await _caseTimeSeriesService.CreateHistoricCostCostProfile(projectId, caseId, dto); + return await caseTimeSeriesService.CreateHistoricCostCostProfile(projectId, caseId, dto); } [HttpPost("{caseId}/well-intervention-cost-profile-override")] @@ -187,7 +169,7 @@ public async Task CreateWellIntervention [FromBody] CreateWellInterventionCostProfileOverrideDto dto ) { - return await _caseTimeSeriesService.CreateWellInterventionCostProfileOverride(projectId, caseId, dto); + return await caseTimeSeriesService.CreateWellInterventionCostProfileOverride(projectId, caseId, dto); } [HttpPost("{caseId}/offshore-facilities-operations-cost-profile-override")] @@ -197,7 +179,7 @@ public async Task CreateOffs [FromBody] CreateOffshoreFacilitiesOperationsCostProfileOverrideDto dto ) { - return await _caseTimeSeriesService.CreateOffshoreFacilitiesOperationsCostProfileOverride(projectId, caseId, dto); + return await caseTimeSeriesService.CreateOffshoreFacilitiesOperationsCostProfileOverride(projectId, caseId, dto); } [HttpPost("{caseId}/onshore-related-opex-cost-profile")] @@ -207,7 +189,7 @@ public async Task CreateOnshoreRelatedOPEXCost [FromBody] CreateOnshoreRelatedOPEXCostProfileDto dto ) { - return await _caseTimeSeriesService.CreateOnshoreRelatedOPEXCostProfile(projectId, caseId, dto); + return await caseTimeSeriesService.CreateOnshoreRelatedOPEXCostProfile(projectId, caseId, dto); } [HttpPost("{caseId}/additional-opex-cost-profile")] @@ -217,7 +199,7 @@ public async Task CreateAdditionalOPEXCostProfile( [FromBody] CreateAdditionalOPEXCostProfileDto dto ) { - return await _caseTimeSeriesService.CreateAdditionalOPEXCostProfile(projectId, caseId, dto); + return await caseTimeSeriesService.CreateAdditionalOPEXCostProfile(projectId, caseId, dto); } [HttpPut("{caseId}/total-feasibility-and-concept-studies-override/{costProfileId}")] @@ -228,7 +210,7 @@ public async Task UpdateTotalFeasi [FromBody] UpdateTotalFeasibilityAndConceptStudiesOverrideDto dto ) { - return await _caseTimeSeriesService.UpdateTotalFeasibilityAndConceptStudiesOverride(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateTotalFeasibilityAndConceptStudiesOverride(projectId, caseId, costProfileId, dto); } [HttpPut("{caseId}/total-feed-studies-override/{costProfileId}")] @@ -239,7 +221,7 @@ public async Task UpdateTotalFEEDStudiesOverride( [FromBody] UpdateTotalFEEDStudiesOverrideDto dto ) { - return await _caseTimeSeriesService.UpdateTotalFEEDStudiesOverride(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateTotalFEEDStudiesOverride(projectId, caseId, costProfileId, dto); } [HttpPut("{caseId}/total-other-studies-cost-profile/{costProfileId}")] @@ -250,7 +232,7 @@ public async Task UpdateTotalOtherStudiesCostPr [FromBody] UpdateTotalOtherStudiesCostProfileDto dto ) { - return await _caseTimeSeriesService.UpdateTotalOtherStudiesCostProfile(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateTotalOtherStudiesCostProfile(projectId, caseId, costProfileId, dto); } [HttpPut("{caseId}/historic-cost-cost-profile/{costProfileId}")] @@ -261,7 +243,7 @@ public async Task UpdateHistoricCostCostProfile( [FromBody] UpdateHistoricCostCostProfileDto dto ) { - return await _caseTimeSeriesService.UpdateHistoricCostCostProfile(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateHistoricCostCostProfile(projectId, caseId, costProfileId, dto); } [HttpPut("{caseId}/well-intervention-cost-profile-override/{costProfileId}")] @@ -272,7 +254,7 @@ public async Task UpdateWellIntervention [FromBody] UpdateWellInterventionCostProfileOverrideDto dto ) { - return await _caseTimeSeriesService.UpdateWellInterventionCostProfileOverride(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateWellInterventionCostProfileOverride(projectId, caseId, costProfileId, dto); } [HttpPut("{caseId}/offshore-facilities-operations-cost-profile-override/{costProfileId}")] @@ -283,7 +265,7 @@ public async Task UpdateOffs [FromBody] UpdateOffshoreFacilitiesOperationsCostProfileOverrideDto dto ) { - return await _caseTimeSeriesService.UpdateOffshoreFacilitiesOperationsCostProfileOverride(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateOffshoreFacilitiesOperationsCostProfileOverride(projectId, caseId, costProfileId, dto); } [HttpPut("{caseId}/onshore-related-opex-cost-profile/{costProfileId}")] @@ -294,7 +276,7 @@ public async Task UpdateOnshoreRelatedOPEXCost [FromBody] UpdateOnshoreRelatedOPEXCostProfileDto dto ) { - return await _caseTimeSeriesService.UpdateOnshoreRelatedOPEXCostProfile(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateOnshoreRelatedOPEXCostProfile(projectId, caseId, costProfileId, dto); } [HttpPut("{caseId}/additional-opex-cost-profile/{costProfileId}")] @@ -305,6 +287,6 @@ public async Task UpdateAdditionalOPEXCostProfile( [FromBody] UpdateAdditionalOPEXCostProfileDto dto ) { - return await _caseTimeSeriesService.UpdateAdditionalOPEXCostProfile(projectId, caseId, costProfileId, dto); + return await caseTimeSeriesService.UpdateAdditionalOPEXCostProfile(projectId, caseId, costProfileId, dto); } } diff --git a/backend/api/Controllers/PROSPController.cs b/backend/api/Controllers/PROSPController.cs index f2c525462..c7c6121c9 100644 --- a/backend/api/Controllers/PROSPController.cs +++ b/backend/api/Controllers/PROSPController.cs @@ -2,7 +2,6 @@ using api.Dtos; using api.Services; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Graph; @@ -15,32 +14,12 @@ namespace api.Controllers; ApplicationRole.User )] [ActionType(ActionType.Edit)] -public class PROSPController : ControllerBase +public class PROSPController( + ProspSharepointImportService prospSharepointImportImportService, + IProjectService projectService, + ILogger logger) + : ControllerBase { - private const string isCheckedAsset = "true"; - private readonly IConfiguration _config; - private readonly GraphServiceClient _graphServiceClient; - private readonly ILogger _logger; - private readonly IProjectService _projectService; - private readonly ProspExcelImportService _prospExcelImportService; - private readonly ProspSharepointImportService _prospSharepointImportService; - - - public PROSPController(ProspExcelImportService prospExcelImportService, - GraphServiceClient graphService, - IConfiguration config, - ProspSharepointImportService prospSharepointImportImportService, - IProjectService projectService, - ILoggerFactory loggerFactory) - { - _prospExcelImportService = prospExcelImportService; - _graphServiceClient = graphService; - _config = config; - _prospSharepointImportService = prospSharepointImportImportService; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - } - [HttpPost("sharepoint", Name = nameof(GetSharePointFileNamesAndId))] public async Task>> GetSharePointFileNamesAndId([FromBody] urlDto urlDto) { @@ -51,22 +30,22 @@ public async Task>> GetSharePointFileNamesAndId( try { - var driveItems = await _prospSharepointImportService.GetDeltaDriveItemCollectionFromSite(urlDto.url); + var driveItems = await prospSharepointImportImportService.GetDeltaDriveItemCollectionFromSite(urlDto.url); return Ok(driveItems); } catch (ServiceException ex) when (ex.StatusCode == System.Net.HttpStatusCode.Forbidden) { - _logger.LogError(ex, "Access Denied when attempting to access SharePoint site: {Url}", urlDto.url); + logger.LogError(ex, "Access Denied when attempting to access SharePoint site: {Url}", urlDto.url); return StatusCode(StatusCodes.Status403Forbidden, "Access to SharePoint resource was denied."); } catch (ProspSharepointImportService.AccessDeniedException ex) { - _logger.LogError(ex, "Custom Access Denied when attempting to access SharePoint site: {Url}", urlDto.url); + logger.LogError(ex, "Custom Access Denied when attempting to access SharePoint site: {Url}", urlDto.url); return StatusCode(StatusCodes.Status403Forbidden, ex.Message); } catch (Exception ex) { - _logger.LogError(ex, "An error occurred while processing your request for URL: {Url}", urlDto.url); + logger.LogError(ex, "An error occurred while processing your request for URL: {Url}", urlDto.url); return StatusCode(StatusCodes.Status500InternalServerError, "An internal server error occurred."); } } @@ -78,20 +57,20 @@ public async Task> ImportFilesFromSharepointA { try { - await _prospSharepointImportService.ConvertSharepointFilesToProjectDto(projectId, dtos); - var projectDto = await _projectService.GetProjectDto(projectId); + await prospSharepointImportImportService.ConvertSharepointFilesToProjectDto(projectId, dtos); + var projectDto = await projectService.GetProjectDto(projectId); return Ok(projectDto); } catch (ServiceException ex) when (ex.StatusCode == System.Net.HttpStatusCode.Forbidden) { - _logger.LogError($"Access denied when trying to import files from SharePoint for project {projectId}: {ex.Message}"); + logger.LogError($"Access denied when trying to import files from SharePoint for project {projectId}: {ex.Message}"); return StatusCode(StatusCodes.Status403Forbidden, "Access to SharePoint resource was denied."); } // Handle other potential ServiceException cases, if necessary catch (Exception e) { - _logger.LogError($"An error occurred while importing files from SharePoint for project {projectId}: {e.Message}"); + logger.LogError($"An error occurred while importing files from SharePoint for project {projectId}: {e.Message}"); // Consider returning a more generic error message to avoid exposing sensitive details // and ensure it's a client-friendly message return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request."); diff --git a/backend/api/Controllers/ProjectMembersController.cs b/backend/api/Controllers/ProjectMembersController.cs index aa79a2c86..1ff66a4af 100644 --- a/backend/api/Controllers/ProjectMembersController.cs +++ b/backend/api/Controllers/ProjectMembersController.cs @@ -10,17 +10,8 @@ namespace api.Controllers; [ApiController] [Route("projects/{projectId}/members")] [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] -public class ProjectMembersController : ControllerBase +public class ProjectMembersController(IProjectMemberService projectMemberService) : ControllerBase { - private readonly IProjectMemberService _projectMemberService; - - public ProjectMembersController( - IProjectMemberService projectMemberService - ) - { - _projectMemberService = projectMemberService; - } - [RequiresApplicationRoles( ApplicationRole.Admin, ApplicationRole.User @@ -29,7 +20,7 @@ IProjectMemberService projectMemberService [ActionType(ActionType.Edit)] public async Task Get(Guid projectId, Guid userId) { - await _projectMemberService.DeleteProjectMember(projectId, userId); + await projectMemberService.DeleteProjectMember(projectId, userId); } [HttpPost] @@ -40,7 +31,7 @@ public async Task Get(Guid projectId, Guid userId) [ActionType(ActionType.Edit)] public async Task CreateProjectMember([FromRoute] Guid projectId, [FromBody] CreateProjectMemberDto createProjectMemberDto) { - return await _projectMemberService.CreateProjectMember(projectId, createProjectMemberDto); + return await projectMemberService.CreateProjectMember(projectId, createProjectMemberDto); } } diff --git a/backend/api/Controllers/ProjectsController.cs b/backend/api/Controllers/ProjectsController.cs index ff3a829d5..d4cdf472c 100644 --- a/backend/api/Controllers/ProjectsController.cs +++ b/backend/api/Controllers/ProjectsController.cs @@ -11,26 +11,13 @@ namespace api.Controllers; [ApiController] [Route("projects")] [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] -public class ProjectsController : ControllerBase +public class ProjectsController( + IProjectService projectService, + IProjectAccessService projectAccessService, + ICompareCasesService compareCasesService, + ITechnicalInputService technicalInputService) + : ControllerBase { - private readonly IProjectService _projectService; - private readonly IProjectAccessService _projectAccessService; - private readonly ICompareCasesService _compareCasesService; - private readonly ITechnicalInputService _technicalInputService; - - public ProjectsController( - IProjectService projectService, - IProjectAccessService projectAccessService, - ICompareCasesService compareCasesService, - ITechnicalInputService technicalInputService - ) - { - _projectService = projectService; - _projectAccessService = projectAccessService; - _compareCasesService = compareCasesService; - _technicalInputService = technicalInputService; - } - [RequiresApplicationRoles( ApplicationRole.Admin, ApplicationRole.ReadOnly, @@ -40,7 +27,7 @@ ITechnicalInputService technicalInputService [ActionType(ActionType.Read)] public async Task Get(Guid projectId) { - return await _projectService.GetProjectDto(projectId); + return await projectService.GetProjectDto(projectId); } [HttpPost] @@ -51,7 +38,7 @@ public async Task Get(Guid projectId) [ActionType(ActionType.Edit)] public async Task CreateProject([FromQuery] Guid contextId) { - return await _projectService.CreateProject(contextId); + return await projectService.CreateProject(contextId); } [RequiresApplicationRoles( @@ -62,7 +49,7 @@ public async Task CreateProject([FromQuery] Guid contextId [ActionType(ActionType.Edit)] public async Task UpdateProject([FromRoute] Guid projectId, [FromBody] UpdateProjectDto projectDto) { - return await _projectService.UpdateProject(projectId, projectDto); + return await projectService.UpdateProject(projectId, projectDto); } [RequiresApplicationRoles( @@ -73,7 +60,7 @@ public async Task UpdateProject([FromRoute] Guid projectId, [ActionType(ActionType.Edit)] public async Task UpdateExplorationOperationalWellCosts([FromRoute] Guid projectId, [FromRoute] Guid explorationOperationalWellCostsId, [FromBody] UpdateExplorationOperationalWellCostsDto dto) { - return await _projectService.UpdateExplorationOperationalWellCosts(projectId, explorationOperationalWellCostsId, dto); + return await projectService.UpdateExplorationOperationalWellCosts(projectId, explorationOperationalWellCostsId, dto); } [RequiresApplicationRoles( @@ -84,7 +71,7 @@ public async Task UpdateExplorationOperation [ActionType(ActionType.Edit)] public async Task UpdateDevelopmentOperationalWellCosts([FromRoute] Guid projectId, [FromRoute] Guid developmentOperationalWellCostsId, [FromBody] UpdateDevelopmentOperationalWellCostsDto dto) { - return await _projectService.UpdateDevelopmentOperationalWellCosts(projectId, developmentOperationalWellCostsId, dto); + return await projectService.UpdateDevelopmentOperationalWellCosts(projectId, developmentOperationalWellCostsId, dto); } [RequiresApplicationRoles( @@ -96,7 +83,7 @@ public async Task UpdateDevelopmentOperation [ActionType(ActionType.Read)] public async Task> CaseComparison(Guid projectId) { - return new List(await _compareCasesService.Calculate(projectId)); + return new List(await compareCasesService.Calculate(projectId)); } [RequiresApplicationRoles( @@ -108,7 +95,7 @@ public async Task> CaseComparison(Guid projectId) [ActionType(ActionType.Read)] public async Task GetAccess(Guid projectId) { - return await _projectAccessService.GetUserProjectAccess(projectId); + return await projectAccessService.GetUserProjectAccess(projectId); } [RequiresApplicationRoles( @@ -119,6 +106,6 @@ public async Task GetAccess(Guid projectId) [ActionType(ActionType.Edit)] public async Task UpdateTechnicalInput([FromRoute] Guid projectId, [FromBody] UpdateTechnicalInputDto dto) { - return await _technicalInputService.UpdateTehnicalInput(projectId, dto); + return await technicalInputService.UpdateTehnicalInput(projectId, dto); } } diff --git a/backend/api/Controllers/RevisionsController.cs b/backend/api/Controllers/RevisionsController.cs index 2129e0869..af8f27865 100644 --- a/backend/api/Controllers/RevisionsController.cs +++ b/backend/api/Controllers/RevisionsController.cs @@ -10,17 +10,8 @@ namespace api.Controllers; [ApiController] [Route("projects/{projectId}/revisions")] [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] -public class RevisionsController : ControllerBase +public class RevisionsController(IRevisionService revisionService) : ControllerBase { - private readonly IRevisionService _revisionService; - - public RevisionsController( - IRevisionService revisionService - ) - { - _revisionService = revisionService; - } - [HttpGet("{revisionId}")] [RequiresApplicationRoles( ApplicationRole.Admin, @@ -31,7 +22,7 @@ IRevisionService revisionService public async Task Get(Guid projectId, Guid revisionId) { // TODO: Need to verify that the project from the URL is the same as the project of the resource - return await _revisionService.GetRevision(revisionId); + return await revisionService.GetRevision(revisionId); } [HttpPost] @@ -42,6 +33,6 @@ IRevisionService revisionService [ActionType(ActionType.Edit)] public async Task CreateProject([FromRoute] Guid projectId, [FromBody] CreateRevisionDto createRevisionDto) { - return await _revisionService.CreateRevision(projectId, createRevisionDto); + return await revisionService.CreateRevision(projectId, createRevisionDto); } } diff --git a/backend/api/Controllers/STEAController.cs b/backend/api/Controllers/STEAController.cs index c2e147937..08c5e7883 100644 --- a/backend/api/Controllers/STEAController.cs +++ b/backend/api/Controllers/STEAController.cs @@ -5,7 +5,6 @@ using ClosedXML.Excel; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -21,21 +20,12 @@ namespace api.Controllers; )] [ActionType(ActionType.Read)] -public class STEAController : ControllerBase +public class STEAController(ISTEAService sTeaService) : ControllerBase { - private readonly ISTEAService _sTEAService; - private readonly ILogger _logger; - - public STEAController(ILogger logger, ISTEAService sTEAService) - { - _logger = logger; - _sTEAService = sTEAService; - } - [HttpGet("{ProjectId}", Name = "GetInputToSTEA")] public async Task GetInputToSTEA(Guid ProjectId) { - return await _sTEAService.GetInputToSTEA(ProjectId); + return await sTeaService.GetInputToSTEA(ProjectId); } [HttpPost("{ProjectId}", Name = "ExcelToSTEA")] diff --git a/backend/api/Controllers/WellsController.cs b/backend/api/Controllers/WellsController.cs index bf1790ef9..2ffbe3380 100644 --- a/backend/api/Controllers/WellsController.cs +++ b/backend/api/Controllers/WellsController.cs @@ -2,8 +2,6 @@ using api.Dtos; using api.Services; - -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web.Resource; @@ -16,43 +14,33 @@ namespace api.Controllers; ApplicationRole.Admin, ApplicationRole.User )] -public class WellsController : ControllerBase +public class WellsController(IWellService wellService) : ControllerBase { - - private readonly IWellService _wellService; - - public WellsController( - IWellService wellService - ) - { - _wellService = wellService; - } - [HttpPut("{wellId}")] [ActionType(ActionType.Edit)] public async Task UpdateWell([FromRoute] Guid projectId, [FromRoute] Guid wellId, [FromBody] UpdateWellDto wellDto) { - return await _wellService.UpdateWell(projectId, wellId, wellDto); + return await wellService.UpdateWell(projectId, wellId, wellDto); } [HttpPost] [ActionType(ActionType.Edit)] public async Task CreateWell([FromRoute] Guid projectId, [FromBody] CreateWellDto wellDto) { - return await _wellService.CreateWell(projectId, wellDto); + return await wellService.CreateWell(projectId, wellDto); } [HttpDelete("{wellId}")] [ActionType(ActionType.Edit)] public async Task DeleteWell([FromRoute] Guid projectId, [FromRoute] Guid wellId) { - await _wellService.DeleteWell(projectId, wellId); + await wellService.DeleteWell(projectId, wellId); } [HttpGet("{wellId}/affected-cases")] [ActionType(ActionType.Edit)] public async Task> GetAffectedCases([FromRoute] Guid projectId, [FromRoute] Guid wellId) { - return await _wellService.GetAffectedCases(wellId); + return await wellService.GetAffectedCases(wellId); } } diff --git a/backend/api/Dtos/AssetWell/CreateDrillingScheduleDto.cs b/backend/api/Dtos/AssetWell/CreateDrillingScheduleDto.cs index bea6cd3cc..dcc7483e9 100644 --- a/backend/api/Dtos/AssetWell/CreateDrillingScheduleDto.cs +++ b/backend/api/Dtos/AssetWell/CreateDrillingScheduleDto.cs @@ -1,6 +1,4 @@ -using System.ComponentModel.DataAnnotations; - namespace api.Dtos; public class CreateDrillingScheduleDto : CreateTimeSeriesScheduleDto diff --git a/backend/api/Dtos/Case/CaseDto.cs b/backend/api/Dtos/Case/CaseDto.cs index efd47dedb..dfabf4639 100644 --- a/backend/api/Dtos/Case/CaseDto.cs +++ b/backend/api/Dtos/Case/CaseDto.cs @@ -1,6 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Dtos; using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Case/CaseWithAssetsDto.cs b/backend/api/Dtos/Case/CaseWithAssetsDto.cs index 563990da0..8bb075b8a 100644 --- a/backend/api/Dtos/Case/CaseWithAssetsDto.cs +++ b/backend/api/Dtos/Case/CaseWithAssetsDto.cs @@ -1,8 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Dtos; -using api.Models; - namespace api.Dtos; public class CaseWithAssetsDto diff --git a/backend/api/Dtos/Case/CaseWithProfilesDto.cs b/backend/api/Dtos/Case/CaseWithProfilesDto.cs index 19cda0eb2..8b91119ae 100644 --- a/backend/api/Dtos/Case/CaseWithProfilesDto.cs +++ b/backend/api/Dtos/Case/CaseWithProfilesDto.cs @@ -1,6 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Dtos; using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Case/Update/BaseUpdateCaseDto.cs b/backend/api/Dtos/Case/Update/BaseUpdateCaseDto.cs index 8e198d380..b1581c557 100644 --- a/backend/api/Dtos/Case/Update/BaseUpdateCaseDto.cs +++ b/backend/api/Dtos/Case/Update/BaseUpdateCaseDto.cs @@ -1,5 +1,3 @@ -using api.Models; - namespace api.Dtos; public abstract class BaseUpdateCaseDto diff --git a/backend/api/Dtos/CompareCasesDto.cs b/backend/api/Dtos/CompareCasesDto.cs index 424ee45b8..1e6a84629 100644 --- a/backend/api/Dtos/CompareCasesDto.cs +++ b/backend/api/Dtos/CompareCasesDto.cs @@ -1,7 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Models; - namespace api.Dtos; public class CompareCasesDto diff --git a/backend/api/Dtos/DrainageStrategy/CreateDrainageStrategyDto.cs b/backend/api/Dtos/DrainageStrategy/CreateDrainageStrategyDto.cs index c79a7c6ec..dc35a6470 100644 --- a/backend/api/Dtos/DrainageStrategy/CreateDrainageStrategyDto.cs +++ b/backend/api/Dtos/DrainageStrategy/CreateDrainageStrategyDto.cs @@ -1,7 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Models; - namespace api.Dtos; public class CreateDrainageStrategyDto diff --git a/backend/api/Dtos/DrainageStrategy/UpdateDrainageStrategyWithProfilesDto.cs b/backend/api/Dtos/DrainageStrategy/UpdateDrainageStrategyWithProfilesDto.cs index c5fc00c0c..dd07c04ef 100644 --- a/backend/api/Dtos/DrainageStrategy/UpdateDrainageStrategyWithProfilesDto.cs +++ b/backend/api/Dtos/DrainageStrategy/UpdateDrainageStrategyWithProfilesDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/DriveItemDto.cs b/backend/api/Dtos/DriveItemDto.cs index 92abb4236..9b32637fe 100644 --- a/backend/api/Dtos/DriveItemDto.cs +++ b/backend/api/Dtos/DriveItemDto.cs @@ -1,7 +1,5 @@ using Microsoft.Graph; -using File = Microsoft.Graph.File; - namespace api.Dtos; public class DriveItemDto diff --git a/backend/api/Dtos/Exploration/CreateExplorationDto.cs b/backend/api/Dtos/Exploration/CreateExplorationDto.cs index 7d5fb8145..8c6127f1c 100644 --- a/backend/api/Dtos/Exploration/CreateExplorationDto.cs +++ b/backend/api/Dtos/Exploration/CreateExplorationDto.cs @@ -1,7 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Models; - namespace api.Dtos; public class CreateExplorationDto diff --git a/backend/api/Dtos/Exploration/UpdateExplorationDto.cs b/backend/api/Dtos/Exploration/UpdateExplorationDto.cs index 328334dbb..e02b17907 100644 --- a/backend/api/Dtos/Exploration/UpdateExplorationDto.cs +++ b/backend/api/Dtos/Exploration/UpdateExplorationDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Exploration/UpdateExplorationWithProfilesDto.cs b/backend/api/Dtos/Exploration/UpdateExplorationWithProfilesDto.cs index 8027c797e..62b8db8bc 100644 --- a/backend/api/Dtos/Exploration/UpdateExplorationWithProfilesDto.cs +++ b/backend/api/Dtos/Exploration/UpdateExplorationWithProfilesDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Image/imageDto.cs b/backend/api/Dtos/Image/imageDto.cs index c867c8fb6..24f2effe0 100644 --- a/backend/api/Dtos/Image/imageDto.cs +++ b/backend/api/Dtos/Image/imageDto.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; namespace api.Dtos; diff --git a/backend/api/Dtos/Project/ProjectWithAssetsDto.cs b/backend/api/Dtos/Project/ProjectWithAssetsDto.cs index 72e79ac6e..39aa3f632 100644 --- a/backend/api/Dtos/Project/ProjectWithAssetsDto.cs +++ b/backend/api/Dtos/Project/ProjectWithAssetsDto.cs @@ -1,7 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Models; - namespace api.Dtos; public class ProjectWithAssetsDto : ProjectDto, IEquatable diff --git a/backend/api/Dtos/Project/ProjectWithCasesDto.cs b/backend/api/Dtos/Project/ProjectWithCasesDto.cs index 860edca3b..94d4831cb 100644 --- a/backend/api/Dtos/Project/ProjectWithCasesDto.cs +++ b/backend/api/Dtos/Project/ProjectWithCasesDto.cs @@ -1,7 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Models; - namespace api.Dtos; public class ProjectWithCasesDto : ProjectDto diff --git a/backend/api/Dtos/Project/UpdateDevelopmentOperationalWellCostsDto.cs b/backend/api/Dtos/Project/UpdateDevelopmentOperationalWellCostsDto.cs index 39e0aa894..167dffefe 100644 --- a/backend/api/Dtos/Project/UpdateDevelopmentOperationalWellCostsDto.cs +++ b/backend/api/Dtos/Project/UpdateDevelopmentOperationalWellCostsDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - namespace api.Dtos; public class UpdateDevelopmentOperationalWellCostsDto diff --git a/backend/api/Dtos/Project/UpdateExplorationOperationalWellCostsDto.cs b/backend/api/Dtos/Project/UpdateExplorationOperationalWellCostsDto.cs index 37712b11b..e2a213680 100644 --- a/backend/api/Dtos/Project/UpdateExplorationOperationalWellCostsDto.cs +++ b/backend/api/Dtos/Project/UpdateExplorationOperationalWellCostsDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - namespace api.Dtos; public class UpdateExplorationOperationalWellCostsDto diff --git a/backend/api/Dtos/Project/UpdateProjectDto.cs b/backend/api/Dtos/Project/UpdateProjectDto.cs index e992702fa..72beb4b7c 100644 --- a/backend/api/Dtos/Project/UpdateProjectDto.cs +++ b/backend/api/Dtos/Project/UpdateProjectDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Substructure/Update/APIUpdateSubstructureDto.cs b/backend/api/Dtos/Substructure/Update/APIUpdateSubstructureDto.cs index 0ba576902..e52522d35 100644 --- a/backend/api/Dtos/Substructure/Update/APIUpdateSubstructureDto.cs +++ b/backend/api/Dtos/Substructure/Update/APIUpdateSubstructureDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Substructure/Update/APIUpdateSubstructureWithProfilesDto.cs b/backend/api/Dtos/Substructure/Update/APIUpdateSubstructureWithProfilesDto.cs index c969d3f79..9d01eb487 100644 --- a/backend/api/Dtos/Substructure/Update/APIUpdateSubstructureWithProfilesDto.cs +++ b/backend/api/Dtos/Substructure/Update/APIUpdateSubstructureWithProfilesDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Substructure/Update/BaseUpdateSubstructureDto.cs b/backend/api/Dtos/Substructure/Update/BaseUpdateSubstructureDto.cs index bcea0555d..6157521f4 100644 --- a/backend/api/Dtos/Substructure/Update/BaseUpdateSubstructureDto.cs +++ b/backend/api/Dtos/Substructure/Update/BaseUpdateSubstructureDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Substructure/Update/PROSPUpdateSubstructureDto.cs b/backend/api/Dtos/Substructure/Update/PROSPUpdateSubstructureDto.cs index 53d664fae..c8f715985 100644 --- a/backend/api/Dtos/Substructure/Update/PROSPUpdateSubstructureDto.cs +++ b/backend/api/Dtos/Substructure/Update/PROSPUpdateSubstructureDto.cs @@ -1,7 +1,3 @@ -using System.ComponentModel.DataAnnotations; - -using api.Models; - namespace api.Dtos; public class PROSPUpdateSubstructureDto : BaseUpdateSubstructureDto diff --git a/backend/api/Dtos/Surf/Update/APIUpdateSurfWithProfilesDto.cs b/backend/api/Dtos/Surf/Update/APIUpdateSurfWithProfilesDto.cs index b83399ee4..ad50749e5 100644 --- a/backend/api/Dtos/Surf/Update/APIUpdateSurfWithProfilesDto.cs +++ b/backend/api/Dtos/Surf/Update/APIUpdateSurfWithProfilesDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Surf/Update/BaseUpdateSurfDto.cs b/backend/api/Dtos/Surf/Update/BaseUpdateSurfDto.cs index d2d2450d3..70b65db05 100644 --- a/backend/api/Dtos/Surf/Update/BaseUpdateSurfDto.cs +++ b/backend/api/Dtos/Surf/Update/BaseUpdateSurfDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/Surf/Update/PROSPUpdateSurfDto.cs b/backend/api/Dtos/Surf/Update/PROSPUpdateSurfDto.cs index 4727f1a08..4c3da0c52 100644 --- a/backend/api/Dtos/Surf/Update/PROSPUpdateSurfDto.cs +++ b/backend/api/Dtos/Surf/Update/PROSPUpdateSurfDto.cs @@ -1,6 +1,3 @@ -using System.ComponentModel.DataAnnotations; - -using api.Models; namespace api.Dtos; public class PROSPUpdateSurfDto : BaseUpdateSurfDto diff --git a/backend/api/Dtos/TechnicalInput/TechnicalInputDto.cs b/backend/api/Dtos/TechnicalInput/TechnicalInputDto.cs index c65785f11..047205e9c 100644 --- a/backend/api/Dtos/TechnicalInput/TechnicalInputDto.cs +++ b/backend/api/Dtos/TechnicalInput/TechnicalInputDto.cs @@ -1,5 +1,3 @@ -using api.Models; - namespace api.Dtos; public class TechnicalInputDto diff --git a/backend/api/Dtos/TechnicalInput/UpdateTechnicalInputDto.cs b/backend/api/Dtos/TechnicalInput/UpdateTechnicalInputDto.cs index fc89a0029..5d1590bc2 100644 --- a/backend/api/Dtos/TechnicalInput/UpdateTechnicalInputDto.cs +++ b/backend/api/Dtos/TechnicalInput/UpdateTechnicalInputDto.cs @@ -1,5 +1,3 @@ -using api.Models; - namespace api.Dtos; public class UpdateTechnicalInputDto diff --git a/backend/api/Dtos/TimeSeries/TimeSeriesDto.cs b/backend/api/Dtos/TimeSeries/TimeSeriesDto.cs index b783ff294..3ab180ed0 100644 --- a/backend/api/Dtos/TimeSeries/TimeSeriesDto.cs +++ b/backend/api/Dtos/TimeSeries/TimeSeriesDto.cs @@ -3,8 +3,6 @@ using api.Helpers; using api.Models; -using Microsoft.IdentityModel.Tokens; - namespace api.Dtos; public class TimeSeriesDto diff --git a/backend/api/Dtos/Topside/Update/PROSPUpdateTopsideDto.cs b/backend/api/Dtos/Topside/Update/PROSPUpdateTopsideDto.cs index af763a869..c696191e7 100644 --- a/backend/api/Dtos/Topside/Update/PROSPUpdateTopsideDto.cs +++ b/backend/api/Dtos/Topside/Update/PROSPUpdateTopsideDto.cs @@ -1,5 +1,3 @@ -using api.Models; - namespace api.Dtos; public class PROSPUpdateTopsideDto : BaseUpdateTopsideDto diff --git a/backend/api/Dtos/Transport/Update/PROSPUpdateTransportDto.cs b/backend/api/Dtos/Transport/Update/PROSPUpdateTransportDto.cs index e40b1c19e..a88068b6d 100644 --- a/backend/api/Dtos/Transport/Update/PROSPUpdateTransportDto.cs +++ b/backend/api/Dtos/Transport/Update/PROSPUpdateTransportDto.cs @@ -1,4 +1,3 @@ -using api.Models; namespace api.Dtos; public class PROSPUpdateTransportDto : BaseUpdateTransportDto diff --git a/backend/api/Dtos/Well/DeleteWellDto.cs b/backend/api/Dtos/Well/DeleteWellDto.cs index 4abdb6a27..7a7131b0e 100644 --- a/backend/api/Dtos/Well/DeleteWellDto.cs +++ b/backend/api/Dtos/Well/DeleteWellDto.cs @@ -1,7 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Models; - namespace api.Dtos; public class DeleteWellDto diff --git a/backend/api/Dtos/WellProject/CreateWellProjectDto.cs b/backend/api/Dtos/WellProject/CreateWellProjectDto.cs index cfe91e319..0184e4f00 100644 --- a/backend/api/Dtos/WellProject/CreateWellProjectDto.cs +++ b/backend/api/Dtos/WellProject/CreateWellProjectDto.cs @@ -1,7 +1,5 @@ using System.ComponentModel.DataAnnotations; -using api.Models; - namespace api.Dtos; public class CreateWellProjectDto diff --git a/backend/api/Dtos/WellProject/UpdateWellProjectDto.cs b/backend/api/Dtos/WellProject/UpdateWellProjectDto.cs index f84f6b5e9..9706c2daf 100644 --- a/backend/api/Dtos/WellProject/UpdateWellProjectDto.cs +++ b/backend/api/Dtos/WellProject/UpdateWellProjectDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Dtos/WellProject/UpdateWellProjectWithProfilesDto.cs b/backend/api/Dtos/WellProject/UpdateWellProjectWithProfilesDto.cs index 63cbab815..dd9cc0dbb 100644 --- a/backend/api/Dtos/WellProject/UpdateWellProjectWithProfilesDto.cs +++ b/backend/api/Dtos/WellProject/UpdateWellProjectWithProfilesDto.cs @@ -1,5 +1,3 @@ -using System.ComponentModel.DataAnnotations; - using api.Models; namespace api.Dtos; diff --git a/backend/api/Exceptions/InvalidInputException.cs b/backend/api/Exceptions/InvalidInputException.cs index aa461857c..2202f0516 100644 --- a/backend/api/Exceptions/InvalidInputException.cs +++ b/backend/api/Exceptions/InvalidInputException.cs @@ -1,12 +1,6 @@ namespace api.Exceptions; -public class InvalidInputException : Exception +public class InvalidInputException(string message, Guid entityId) : Exception(message) { - public Guid EntityId { get; } - - public InvalidInputException(string message, Guid entityId) - : base(message) - { - EntityId = entityId; - } + public Guid EntityId { get; } = entityId; } diff --git a/backend/api/Exceptions/MappingException.cs b/backend/api/Exceptions/MappingException.cs index 3532257f4..f017c0690 100644 --- a/backend/api/Exceptions/MappingException.cs +++ b/backend/api/Exceptions/MappingException.cs @@ -1,12 +1,6 @@ namespace api.Exceptions; -public class MappingException : Exception +public class MappingException(string message, Guid entityId) : Exception(message) { - public Guid EntityId { get; } - - public MappingException(string message, Guid entityId) - : base(message) - { - EntityId = entityId; - } + public Guid EntityId { get; } = entityId; } diff --git a/backend/api/Exceptions/ModifyRevisionException.cs b/backend/api/Exceptions/ModifyRevisionException.cs index f2b56a525..d0c909b2b 100644 --- a/backend/api/Exceptions/ModifyRevisionException.cs +++ b/backend/api/Exceptions/ModifyRevisionException.cs @@ -1,12 +1,6 @@ namespace api.Exceptions; -public class ModifyRevisionException : Exception +public class ModifyRevisionException(string message, Guid entityId) : Exception(message) { - public Guid EntityId { get; } - - public ModifyRevisionException(string message, Guid entityId) - : base(message) - { - EntityId = entityId; - } + public Guid EntityId { get; } = entityId; } diff --git a/backend/api/Exceptions/ProjectAccessMismatchException.cs b/backend/api/Exceptions/ProjectAccessMismatchException.cs index 37b48c769..a6161f3d0 100644 --- a/backend/api/Exceptions/ProjectAccessMismatchException.cs +++ b/backend/api/Exceptions/ProjectAccessMismatchException.cs @@ -5,8 +5,7 @@ public class ProjectAccessMismatchException : Exception public Guid EntityId { get; } public Guid UrlProjectId { get; } - public ProjectAccessMismatchException(string message) -: base(message) + public ProjectAccessMismatchException(string message) : base(message) { } diff --git a/backend/api/Exceptions/ProjectAlreadyExistsException.cs b/backend/api/Exceptions/ProjectAlreadyExistsException.cs index 1222ec802..cb69e0aa7 100644 --- a/backend/api/Exceptions/ProjectAlreadyExistsException.cs +++ b/backend/api/Exceptions/ProjectAlreadyExistsException.cs @@ -1,8 +1,3 @@ namespace api.Exceptions; -public class ProjectAlreadyExistsException : Exception -{ - public ProjectAlreadyExistsException(string message) : base(message) - { - } -} +public class ProjectAlreadyExistsException(string message) : Exception(message); diff --git a/backend/api/Exceptions/ProjectClassificationException.cs b/backend/api/Exceptions/ProjectClassificationException.cs index e6d6395e0..74a63b267 100644 --- a/backend/api/Exceptions/ProjectClassificationException.cs +++ b/backend/api/Exceptions/ProjectClassificationException.cs @@ -1,12 +1,6 @@ namespace api.Exceptions; -public class ProjectClassificationException : Exception +public class ProjectClassificationException(string message, Guid entityId) : Exception(message) { - public Guid EntityId { get; } - - public ProjectClassificationException(string message, Guid entityId) - : base(message) - { - EntityId = entityId; - } + public Guid EntityId { get; } = entityId; } diff --git a/backend/api/Exceptions/ProjectMembershipException.cs b/backend/api/Exceptions/ProjectMembershipException.cs index fe75aecdb..7d8c621a1 100644 --- a/backend/api/Exceptions/ProjectMembershipException.cs +++ b/backend/api/Exceptions/ProjectMembershipException.cs @@ -1,12 +1,6 @@ namespace api.Exceptions; -public class ProjectMembershipException : Exception +public class ProjectMembershipException(string message, Guid entityId) : Exception(message) { - public Guid EntityId { get; } - - public ProjectMembershipException(string message, Guid entityId) - : base(message) - { - EntityId = entityId; - } + public Guid EntityId { get; } = entityId; } diff --git a/backend/api/Exceptions/WellChangeTypeException.cs b/backend/api/Exceptions/WellChangeTypeException.cs index b64fcae7b..cffee56bc 100644 --- a/backend/api/Exceptions/WellChangeTypeException.cs +++ b/backend/api/Exceptions/WellChangeTypeException.cs @@ -1,12 +1,6 @@ namespace api.Exceptions; -public class WellChangeTypeException : Exception +public class WellChangeTypeException(string message, Guid entityId) : Exception(message) { - public Guid EntityId { get; } - - public WellChangeTypeException(string message, Guid entityId) - : base(message) - { - EntityId = entityId; - } + public Guid EntityId { get; } = entityId; } diff --git a/backend/api/FusionIntegration/FusionService.cs b/backend/api/FusionIntegration/FusionService.cs index dc6d86749..742ccefcc 100644 --- a/backend/api/FusionIntegration/FusionService.cs +++ b/backend/api/FusionIntegration/FusionService.cs @@ -6,19 +6,10 @@ namespace api.Services.FusionIntegration; -public class FusionService : IFusionService +public class FusionService( + IFusionContextResolver fusionContextResolver, + ILogger logger) : IFusionService { - private readonly IFusionContextResolver _fusionContextResolver; - private readonly ILogger _logger; - - public FusionService( - IFusionContextResolver fusionContextResolver, - ILogger logger) - { - _fusionContextResolver = fusionContextResolver; - _logger = logger; - } - public async Task GetProjectMasterFromFusionContextId(Guid contextId) { var projectMasterContext = await ResolveProjectMasterContext(contextId); @@ -28,7 +19,7 @@ public FusionService( { // -> No, still not found. Then we log this and fail hard, as the callee should have provided with a // valid ProjectMaster (context) ID. - _logger.LogInformation($"Could not resolve ProjectMaster context from Fusion using GUID '{{contextId}}'", contextId); + logger.LogInformation($"Could not resolve ProjectMaster context from Fusion using GUID '{{contextId}}'", contextId); return null; } @@ -37,7 +28,7 @@ public FusionService( if (fusionProjectMaster == null) { - _logger.LogError("Project Master with ID '{contextId}' was obtained from Fusion, but conversion to explicit type failed", contextId); + logger.LogError("Project Master with ID '{contextId}' was obtained from Fusion, but conversion to explicit type failed", contextId); return null; } @@ -46,7 +37,7 @@ public FusionService( private async Task ResolveProjectMasterContext(Guid contextId) { - FusionContext? projectMasterContext = await _fusionContextResolver.ResolveContextAsync(contextId, FusionContextType.ProjectMaster); + FusionContext? projectMasterContext = await fusionContextResolver.ResolveContextAsync(contextId, FusionContextType.ProjectMaster); Console.WriteLine("ResolveProjectMasterContext - contextId: " + contextId); Console.WriteLine("ResolveProjectMasterContext - projectMasterContext: " + projectMasterContext); @@ -54,7 +45,7 @@ public FusionService( // thus attempt to query for the ProjectMaster "directly" if not found. if (projectMasterContext == null) { - IEnumerable queryContextsAsync = await _fusionContextResolver.QueryContextsAsync( + IEnumerable queryContextsAsync = await fusionContextResolver.QueryContextsAsync( query => { query diff --git a/backend/api/Helpers/CommonLibraryHelper.cs b/backend/api/Helpers/CommonLibraryHelper.cs index 5e2af3961..f1166974b 100644 --- a/backend/api/Helpers/CommonLibraryHelper.cs +++ b/backend/api/Helpers/CommonLibraryHelper.cs @@ -30,7 +30,7 @@ public static ProjectCategory ConvertCategory(string category) "TIE-IN" => ProjectCategory.TieIn, "RENEWABLE_OTHER" => ProjectCategory.RenewableOther, "CCS" => ProjectCategory.Ccs, - _ => throw new ArgumentException(string.Format("Category {0} does not exist in DCD.", category)), + _ => throw new ArgumentException($"Category {category} does not exist in DCD."), }; } @@ -48,7 +48,7 @@ public static ProjectPhase ConvertPhase(string phase) "Execution" => ProjectPhase.Execution, "Operation" => ProjectPhase.Operation, "Screening business opportunities" => ProjectPhase.ScreeningBusinessOpportunities, - _ => throw new ArgumentException(string.Format("Phase {0} does not exist in DCD.", phase)), + _ => throw new ArgumentException($"Phase {phase} does not exist in DCD."), }; } } diff --git a/backend/api/Helpers/EmissionCalculationHelper.cs b/backend/api/Helpers/EmissionCalculationHelper.cs index 2b5cfdb05..8960d0ea1 100644 --- a/backend/api/Helpers/EmissionCalculationHelper.cs +++ b/backend/api/Helpers/EmissionCalculationHelper.cs @@ -1,4 +1,3 @@ -using api.Dtos; using api.Models; namespace api.Helpers; diff --git a/backend/api/Helpers/Prosp/ProspImportSettings.cs b/backend/api/Helpers/Prosp/ProspImportSettings.cs index 3de463196..3bed24b33 100644 --- a/backend/api/Helpers/Prosp/ProspImportSettings.cs +++ b/backend/api/Helpers/Prosp/ProspImportSettings.cs @@ -2,18 +2,10 @@ namespace api.Helpers.Prosp; public class Prosp { - public SubStructure SubStructure; - public Surf Surf; - public TopSide TopSide; - public Transport Transport; - - public Prosp() - { - Surf = new Surf(); - TopSide = new TopSide(); - SubStructure = new SubStructure(); - Transport = new Transport(); - } + public SubStructure SubStructure = new(); + public Surf Surf = new(); + public TopSide TopSide = new(); + public Transport Transport = new(); } public class Surf diff --git a/backend/api/Middleware/ExceptionHandlingMiddleware.cs b/backend/api/Middleware/ExceptionHandlingMiddleware.cs index 84ef8e640..4ee403401 100644 --- a/backend/api/Middleware/ExceptionHandlingMiddleware.cs +++ b/backend/api/Middleware/ExceptionHandlingMiddleware.cs @@ -5,25 +5,17 @@ namespace api.Middleware; -public class ExceptionHandlingMiddleware +public class ExceptionHandlingMiddleware( + RequestDelegate requestDelegate, + ILogger logger) { - private readonly RequestDelegate _next; - private readonly ILogger _logger; - - public ExceptionHandlingMiddleware( - RequestDelegate requestDelegate, - ILogger logger - ) - { - _next = requestDelegate; - _logger = logger; - } + private readonly ILogger _logger = logger; public async Task Invoke(HttpContext context) { try { - await _next(context); + await requestDelegate(context); } catch (Exception ex) { diff --git a/backend/api/Models/Image.cs b/backend/api/Models/Image.cs index ad51026db..3a6ef5e83 100644 --- a/backend/api/Models/Image.cs +++ b/backend/api/Models/Image.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; diff --git a/backend/api/Repositories/BaseRepository.cs b/backend/api/Repositories/BaseRepository.cs index 9b617975b..a3343821f 100644 --- a/backend/api/Repositories/BaseRepository.cs +++ b/backend/api/Repositories/BaseRepository.cs @@ -1,33 +1,25 @@ using System.Linq.Expressions; using api.Context; -using api.Models; using Microsoft.EntityFrameworkCore; namespace api.Repositories; -public class BaseRepository : IBaseRepository +public class BaseRepository(DcdDbContext context) : IBaseRepository { - protected readonly DcdDbContext _context; - - public BaseRepository( - DcdDbContext context - ) - { - _context = context; - } + protected readonly DcdDbContext Context = context; protected async Task Get(Guid id) where T : class { - return await _context.Set().FindAsync(id); + return await Context.Set().FindAsync(id); } protected async Task GetWithIncludes(Guid id, params Expression>[] includes) where T : class { - IQueryable query = _context.Set(); + IQueryable query = Context.Set(); foreach (var include in includes) { @@ -39,17 +31,17 @@ DcdDbContext context protected T Update(T updated) where T : class { - _context.Set().Update(updated); + Context.Set().Update(updated); return updated; } public async Task SaveChangesAndRecalculateAsync(Guid caseId) { - await _context.SaveChangesAndRecalculateAsync(caseId); + await Context.SaveChangesAndRecalculateAsync(caseId); } public async Task SaveChangesAsync() { - await _context.SaveChangesAsync(); + await Context.SaveChangesAsync(); } } diff --git a/backend/api/Repositories/Case/CaseRepository.cs b/backend/api/Repositories/Case/CaseRepository.cs index d73cce0de..08757d79c 100644 --- a/backend/api/Repositories/Case/CaseRepository.cs +++ b/backend/api/Repositories/Case/CaseRepository.cs @@ -8,22 +8,12 @@ namespace api.Repositories; -public class CaseRepository : BaseRepository, ICaseRepository +public class CaseRepository(DcdDbContext context) : BaseRepository(context), ICaseRepository { - private readonly ILogger _logger; - - public CaseRepository( - DcdDbContext context, - ILogger logger - ) : base(context) - { - _logger = logger; - } - public async Task AddCase(Case caseItem) { - _context.Cases.Add(caseItem); - await _context.SaveChangesAsync(); + Context.Cases.Add(caseItem); + await Context.SaveChangesAsync(); return caseItem; } @@ -57,7 +47,7 @@ public async Task CaseHasProfile(Guid caseId, CaseProfileNames profileType CaseProfileNames.CalculatedTotalCostCostProfile => d => d.CalculatedTotalCostCostProfile != null, }; - bool hasProfile = await _context.Cases + bool hasProfile = await Context.Cases .Where(d => d.Id == caseId) .AnyAsync(profileExistsExpression); @@ -76,7 +66,7 @@ public async Task UpdateModifyTime(Guid caseId) throw new ArgumentException("The case id cannot be empty.", nameof(caseId)); } - var caseItem = await _context.Cases.SingleOrDefaultAsync(c => c.Id == caseId) + var caseItem = await Context.Cases.SingleOrDefaultAsync(c => c.Id == caseId) ?? throw new KeyNotFoundException($"Case with id {caseId} not found."); caseItem.ModifyTime = DateTimeOffset.UtcNow; diff --git a/backend/api/Repositories/Case/CaseTimeSeriesRepository.cs b/backend/api/Repositories/Case/CaseTimeSeriesRepository.cs index 6a2632c40..9e3fd79e8 100644 --- a/backend/api/Repositories/Case/CaseTimeSeriesRepository.cs +++ b/backend/api/Repositories/Case/CaseTimeSeriesRepository.cs @@ -1,89 +1,74 @@ -using System.Linq.Expressions; - using api.Context; -using api.Enums; using api.Models; -using Microsoft.EntityFrameworkCore; - namespace api.Repositories; -public class CaseTimeSeriesRepository : BaseRepository, ICaseTimeSeriesRepository +public class CaseTimeSeriesRepository(DcdDbContext context) : BaseRepository(context), ICaseTimeSeriesRepository { - private readonly ILogger _logger; - - public CaseTimeSeriesRepository( - DcdDbContext context, - ILogger logger - ) : base(context) - { - _logger = logger; - } - public CessationWellsCostOverride CreateCessationWellsCostOverride(CessationWellsCostOverride profile) { - _context.CessationWellsCostOverride.Add(profile); + Context.CessationWellsCostOverride.Add(profile); return profile; } public CessationOffshoreFacilitiesCostOverride CreateCessationOffshoreFacilitiesCostOverride(CessationOffshoreFacilitiesCostOverride profile) { - _context.CessationOffshoreFacilitiesCostOverride.Add(profile); + Context.CessationOffshoreFacilitiesCostOverride.Add(profile); return profile; } public CessationOnshoreFacilitiesCostProfile CreateCessationOnshoreFacilitiesCostProfile(CessationOnshoreFacilitiesCostProfile profile) { - _context.CessationOnshoreFacilitiesCostProfile.Add(profile); + Context.CessationOnshoreFacilitiesCostProfile.Add(profile); return profile; } public TotalFeasibilityAndConceptStudiesOverride CreateTotalFeasibilityAndConceptStudiesOverride(TotalFeasibilityAndConceptStudiesOverride profile) { - _context.TotalFeasibilityAndConceptStudiesOverride.Add(profile); + Context.TotalFeasibilityAndConceptStudiesOverride.Add(profile); return profile; } public TotalFEEDStudiesOverride CreateTotalFEEDStudiesOverride(TotalFEEDStudiesOverride profile) { - _context.TotalFEEDStudiesOverride.Add(profile); + Context.TotalFEEDStudiesOverride.Add(profile); return profile; } public TotalOtherStudiesCostProfile CreateTotalOtherStudiesCostProfile(TotalOtherStudiesCostProfile profile) { - _context.TotalOtherStudiesCostProfile.Add(profile); + Context.TotalOtherStudiesCostProfile.Add(profile); return profile; } public HistoricCostCostProfile CreateHistoricCostCostProfile(HistoricCostCostProfile profile) { - _context.HistoricCostCostProfile.Add(profile); + Context.HistoricCostCostProfile.Add(profile); return profile; } public WellInterventionCostProfileOverride CreateWellInterventionCostProfileOverride(WellInterventionCostProfileOverride profile) { - _context.WellInterventionCostProfileOverride.Add(profile); + Context.WellInterventionCostProfileOverride.Add(profile); return profile; } public OffshoreFacilitiesOperationsCostProfileOverride CreateOffshoreFacilitiesOperationsCostProfileOverride(OffshoreFacilitiesOperationsCostProfileOverride profile) { - _context.OffshoreFacilitiesOperationsCostProfileOverride.Add(profile); + Context.OffshoreFacilitiesOperationsCostProfileOverride.Add(profile); return profile; } public OnshoreRelatedOPEXCostProfile CreateOnshoreRelatedOPEXCostProfile(OnshoreRelatedOPEXCostProfile profile) { - _context.OnshoreRelatedOPEXCostProfile.Add(profile); + Context.OnshoreRelatedOPEXCostProfile.Add(profile); return profile; } public AdditionalOPEXCostProfile CreateAdditionalOPEXCostProfile(AdditionalOPEXCostProfile profile) { - _context.AdditionalOPEXCostProfile.Add(profile); + Context.AdditionalOPEXCostProfile.Add(profile); return profile; } diff --git a/backend/api/Repositories/Case/CaseWithAssetsRepository.cs b/backend/api/Repositories/Case/CaseWithAssetsRepository.cs index 694719b5b..c547a31b4 100644 --- a/backend/api/Repositories/Case/CaseWithAssetsRepository.cs +++ b/backend/api/Repositories/Case/CaseWithAssetsRepository.cs @@ -7,20 +7,8 @@ namespace api.Repositories; -public class CaseWithAssetsRepository : ICaseWithAssetsRepository +public class CaseWithAssetsRepository(DcdDbContext context) : ICaseWithAssetsRepository { - private readonly DcdDbContext _context; - private readonly ILogger _logger; - - public CaseWithAssetsRepository( - DcdDbContext context, - ILogger logger - ) - { - _context = context; - _logger = logger; - } - public async Task<( Case CaseItem, DrainageStrategy DrainageStrategy, @@ -46,7 +34,7 @@ WellProject WellProject private async Task GetCaseNoTracking(Guid id) { - return await _context.Cases + return await context.Cases .Include(c => c.TotalFeasibilityAndConceptStudies) .Include(c => c.TotalFeasibilityAndConceptStudiesOverride) .Include(c => c.TotalFEEDStudies) @@ -74,7 +62,7 @@ private async Task GetCaseNoTracking(Guid id) private async Task GetTransportNoTracking(Guid id) { - return await _context.Transports + return await context.Transports .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -85,7 +73,7 @@ private async Task GetTransportNoTracking(Guid id) private async Task GetSurfNoTracking(Guid id) { - return await _context.Surfs + return await context.Surfs .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -96,7 +84,7 @@ private async Task GetSurfNoTracking(Guid id) private async Task GetSubstructureNoTracking(Guid id) { - return await _context.Substructures + return await context.Substructures .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -107,7 +95,7 @@ private async Task GetSubstructureNoTracking(Guid id) private async Task GetDrainageStrategyNoTracking(Guid id) { - return await _context.DrainageStrategies + return await context.DrainageStrategies .Include(c => c.ProductionProfileOil) .Include(c => c.AdditionalProductionProfileOil) .Include(c => c.ProductionProfileGas) @@ -132,7 +120,7 @@ private async Task GetDrainageStrategyNoTracking(Guid id) private async Task GetTopsideNoTracking(Guid id) { - return await _context.Topsides + return await context.Topsides .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -143,7 +131,7 @@ private async Task GetTopsideNoTracking(Guid id) private async Task GetWellProjectNoTracking(Guid id) { - return await _context.WellProjects + return await context.WellProjects .Include(c => c.WellProjectWells)!.ThenInclude(c => c.DrillingSchedule) .Include(c => c.OilProducerCostProfile) .Include(c => c.OilProducerCostProfileOverride) @@ -160,7 +148,7 @@ private async Task GetWellProjectNoTracking(Guid id) private async Task GetExplorationNoTracking(Guid id) { - return await _context.Explorations + return await context.Explorations .Include(c => c.ExplorationWells)!.ThenInclude(c => c.DrillingSchedule) .Include(c => c.ExplorationWellCostProfile) .Include(c => c.AppraisalWellCostProfile) diff --git a/backend/api/Repositories/Case/ICaseTimeSeriesRepository.cs b/backend/api/Repositories/Case/ICaseTimeSeriesRepository.cs index 50fb8ff50..4af356c03 100644 --- a/backend/api/Repositories/Case/ICaseTimeSeriesRepository.cs +++ b/backend/api/Repositories/Case/ICaseTimeSeriesRepository.cs @@ -1,4 +1,3 @@ -using api.Enums; using api.Models; namespace api.Repositories; diff --git a/backend/api/Repositories/DrainageStrategy/DrainageStrategyRepository.cs b/backend/api/Repositories/DrainageStrategy/DrainageStrategyRepository.cs index 25ce60ea7..a07a9026a 100644 --- a/backend/api/Repositories/DrainageStrategy/DrainageStrategyRepository.cs +++ b/backend/api/Repositories/DrainageStrategy/DrainageStrategyRepository.cs @@ -9,13 +9,8 @@ namespace api.Repositories; -public class DrainageStrategyRepository : BaseRepository, IDrainageStrategyRepository +public class DrainageStrategyRepository(DcdDbContext context) : BaseRepository(context), IDrainageStrategyRepository { - - public DrainageStrategyRepository(DcdDbContext context) : base(context) - { - } - public async Task GetDrainageStrategy(Guid drainageStrategyId) { return await Get(drainageStrategyId); @@ -44,7 +39,7 @@ public async Task DrainageStrategyHasProfile(Guid drainageStrategyId, Drai DrainageStrategyProfileNames.DeferredGasProduction => d => d.DeferredGasProduction != null, }; - bool hasProfile = await _context.DrainageStrategies + bool hasProfile = await Context.DrainageStrategies .Where(d => d.Id == drainageStrategyId) .AnyAsync(profileExistsExpression); diff --git a/backend/api/Repositories/DrainageStrategy/DrainageStrategyTimeSeriesRepository.cs b/backend/api/Repositories/DrainageStrategy/DrainageStrategyTimeSeriesRepository.cs index 4052c976e..fc4c59249 100644 --- a/backend/api/Repositories/DrainageStrategy/DrainageStrategyTimeSeriesRepository.cs +++ b/backend/api/Repositories/DrainageStrategy/DrainageStrategyTimeSeriesRepository.cs @@ -1,24 +1,14 @@ -using System.Linq.Expressions; - using api.Context; -using api.Enums; using api.Models; -using Microsoft.EntityFrameworkCore; - namespace api.Repositories; -public class DrainageStrategyTimeSeriesRepository : BaseRepository, IDrainageStrategyTimeSeriesRepository +public class DrainageStrategyTimeSeriesRepository(DcdDbContext context) : BaseRepository(context), IDrainageStrategyTimeSeriesRepository { - - public DrainageStrategyTimeSeriesRepository(DcdDbContext context) : base(context) - { - } - public ProductionProfileOil CreateProductionProfileOil(ProductionProfileOil productionProfileOil) { - _context.ProductionProfileOil.Add(productionProfileOil); + Context.ProductionProfileOil.Add(productionProfileOil); return productionProfileOil; } @@ -34,7 +24,7 @@ public ProductionProfileOil UpdateProductionProfileOil(ProductionProfileOil prod public AdditionalProductionProfileOil CreateAdditionalProductionProfileOil(AdditionalProductionProfileOil additionalProductionProfileOil) { - _context.AdditionalProductionProfileOil.Add(additionalProductionProfileOil); + Context.AdditionalProductionProfileOil.Add(additionalProductionProfileOil); return additionalProductionProfileOil; } @@ -50,7 +40,7 @@ public AdditionalProductionProfileOil UpdateAdditionalProductionProfileOil(Addit public ProductionProfileGas CreateProductionProfileGas(ProductionProfileGas profile) { - _context.ProductionProfileGas.Add(profile); + Context.ProductionProfileGas.Add(profile); return profile; } @@ -66,7 +56,7 @@ public ProductionProfileGas UpdateProductionProfileGas(ProductionProfileGas prod public AdditionalProductionProfileGas CreateAdditionalProductionProfileGas(AdditionalProductionProfileGas profile) { - _context.AdditionalProductionProfileGas.Add(profile); + Context.AdditionalProductionProfileGas.Add(profile); return profile; } @@ -82,7 +72,7 @@ public AdditionalProductionProfileGas UpdateAdditionalProductionProfileGas(Addit public ProductionProfileWater CreateProductionProfileWater(ProductionProfileWater profile) { - _context.ProductionProfileWater.Add(profile); + Context.ProductionProfileWater.Add(profile); return profile; } @@ -98,7 +88,7 @@ public ProductionProfileWater UpdateProductionProfileWater(ProductionProfileWate public ProductionProfileWaterInjection CreateProductionProfileWaterInjection(ProductionProfileWaterInjection profile) { - _context.ProductionProfileWaterInjection.Add(profile); + Context.ProductionProfileWaterInjection.Add(profile); return profile; } public async Task GetProductionProfileWaterInjection(Guid productionProfileId) @@ -114,7 +104,7 @@ public ProductionProfileWaterInjection UpdateProductionProfileWaterInjection(Pro public FuelFlaringAndLossesOverride CreateFuelFlaringAndLossesOverride(FuelFlaringAndLossesOverride profile) { - _context.FuelFlaringAndLossesOverride.Add(profile); + Context.FuelFlaringAndLossesOverride.Add(profile); return profile; } @@ -131,7 +121,7 @@ public FuelFlaringAndLossesOverride UpdateFuelFlaringAndLossesOverride(FuelFlari public NetSalesGasOverride CreateNetSalesGasOverride(NetSalesGasOverride profile) { - _context.NetSalesGasOverride.Add(profile); + Context.NetSalesGasOverride.Add(profile); return profile; } @@ -148,7 +138,7 @@ public NetSalesGasOverride UpdateNetSalesGasOverride(NetSalesGasOverride profile public Co2EmissionsOverride CreateCo2EmissionsOverride(Co2EmissionsOverride profile) { - _context.Co2EmissionsOverride.Add(profile); + Context.Co2EmissionsOverride.Add(profile); return profile; } @@ -165,7 +155,7 @@ public Co2EmissionsOverride UpdateCo2EmissionsOverride(Co2EmissionsOverride prof public ImportedElectricityOverride CreateImportedElectricityOverride(ImportedElectricityOverride profile) { - _context.ImportedElectricityOverride.Add(profile); + Context.ImportedElectricityOverride.Add(profile); return profile; } @@ -182,7 +172,7 @@ public ImportedElectricityOverride UpdateImportedElectricityOverride(ImportedEle public DeferredOilProduction CreateDeferredOilProduction(DeferredOilProduction profile) { - _context.DeferredOilProduction.Add(profile); + Context.DeferredOilProduction.Add(profile); return profile; } @@ -199,7 +189,7 @@ public DeferredOilProduction UpdateDeferredOilProduction(DeferredOilProduction p public DeferredGasProduction CreateDeferredGasProduction(DeferredGasProduction profile) { - _context.DeferredGasProduction.Add(profile); + Context.DeferredGasProduction.Add(profile); return profile; } diff --git a/backend/api/Repositories/DrainageStrategy/IDrainageStrategyTimeSeriesRepository.cs b/backend/api/Repositories/DrainageStrategy/IDrainageStrategyTimeSeriesRepository.cs index 6c7b6f8d2..b586dea5c 100644 --- a/backend/api/Repositories/DrainageStrategy/IDrainageStrategyTimeSeriesRepository.cs +++ b/backend/api/Repositories/DrainageStrategy/IDrainageStrategyTimeSeriesRepository.cs @@ -1,4 +1,3 @@ -using api.Enums; using api.Models; namespace api.Repositories; diff --git a/backend/api/Repositories/Exploration/ExplorationRepository.cs b/backend/api/Repositories/Exploration/ExplorationRepository.cs index 7b19808b9..f8998f7f5 100644 --- a/backend/api/Repositories/Exploration/ExplorationRepository.cs +++ b/backend/api/Repositories/Exploration/ExplorationRepository.cs @@ -9,13 +9,8 @@ namespace api.Repositories; -public class ExplorationRepository : BaseRepository, IExplorationRepository +public class ExplorationRepository(DcdDbContext context) : BaseRepository(context), IExplorationRepository { - - public ExplorationRepository(DcdDbContext context) : base(context) - { - } - public async Task GetExploration(Guid explorationId) { return await Get(explorationId); @@ -40,7 +35,7 @@ public async Task ExplorationHasProfile(Guid ExplorationId, ExplorationPro ExplorationProfileNames.CountryOfficeCost => d => d.CountryOfficeCost != null, }; - bool hasProfile = await _context.Explorations + bool hasProfile = await Context.Explorations .Where(d => d.Id == ExplorationId) .AnyAsync(profileExistsExpression); @@ -54,7 +49,7 @@ public Exploration UpdateExploration(Exploration exploration) public async Task GetExplorationWell(Guid explorationId, Guid wellId) { - return await _context.ExplorationWell.FindAsync(explorationId, wellId); + return await Context.ExplorationWell.FindAsync(explorationId, wellId); } public async Task GetExplorationWellDrillingSchedule(Guid drillingScheduleId) @@ -64,7 +59,7 @@ public Exploration UpdateExploration(Exploration exploration) public async Task GetExplorationWithDrillingSchedule(Guid drillingScheduleId) { - var exploration = await _context.Explorations + var exploration = await Context.Explorations .Include(e => e.ExplorationWells)! .ThenInclude(w => w.DrillingSchedule) .FirstOrDefaultAsync(e => e.ExplorationWells != null && e.ExplorationWells.Any(w => w.DrillingScheduleId == drillingScheduleId)); @@ -79,7 +74,7 @@ public DrillingSchedule UpdateExplorationWellDrillingSchedule(DrillingSchedule d public ExplorationWell CreateExplorationWellDrillingSchedule(ExplorationWell explorationWellWithDrillingSchedule) { - _context.ExplorationWell.Add(explorationWellWithDrillingSchedule); + Context.ExplorationWell.Add(explorationWellWithDrillingSchedule); return explorationWellWithDrillingSchedule; } } diff --git a/backend/api/Repositories/Exploration/ExplorationTimeSeriesRepository.cs b/backend/api/Repositories/Exploration/ExplorationTimeSeriesRepository.cs index 3ad009b61..07a699be6 100644 --- a/backend/api/Repositories/Exploration/ExplorationTimeSeriesRepository.cs +++ b/backend/api/Repositories/Exploration/ExplorationTimeSeriesRepository.cs @@ -1,23 +1,14 @@ -using System.Linq.Expressions; - using api.Context; -using api.Enums; using api.Models; -using Microsoft.EntityFrameworkCore; - namespace api.Repositories; -public class ExplorationTimeSeriesRepository : BaseRepository, IExplorationTimeSeriesRepository +public class ExplorationTimeSeriesRepository(DcdDbContext context) : BaseRepository(context), IExplorationTimeSeriesRepository { - - public ExplorationTimeSeriesRepository(DcdDbContext context) : base(context) - { - } public GAndGAdminCostOverride CreateGAndGAdminCostOverride(GAndGAdminCostOverride profile) { - _context.GAndGAdminCostOverride.Add(profile); + Context.GAndGAdminCostOverride.Add(profile); return profile; } public async Task GetGAndGAdminCostOverride(Guid profileId) @@ -37,13 +28,13 @@ public GAndGAdminCostOverride UpdateGAndGAdminCostOverride(GAndGAdminCostOverrid public SeismicAcquisitionAndProcessing CreateSeismicAcquisitionAndProcessing(SeismicAcquisitionAndProcessing profile) { - _context.SeismicAcquisitionAndProcessing.Add(profile); + Context.SeismicAcquisitionAndProcessing.Add(profile); return profile; } public CountryOfficeCost CreateCountryOfficeCost(CountryOfficeCost profile) { - _context.CountryOfficeCost.Add(profile); + Context.CountryOfficeCost.Add(profile); return profile; } diff --git a/backend/api/Repositories/Exploration/IExplorationTimeSeriesRepository.cs b/backend/api/Repositories/Exploration/IExplorationTimeSeriesRepository.cs index 6dfa57a3e..b4f6e5269 100644 --- a/backend/api/Repositories/Exploration/IExplorationTimeSeriesRepository.cs +++ b/backend/api/Repositories/Exploration/IExplorationTimeSeriesRepository.cs @@ -1,4 +1,3 @@ -using api.Enums; using api.Models; namespace api.Repositories; diff --git a/backend/api/Repositories/Project/ProjectRepository.cs b/backend/api/Repositories/Project/ProjectRepository.cs index 49d590ef6..5e48ae59f 100644 --- a/backend/api/Repositories/Project/ProjectRepository.cs +++ b/backend/api/Repositories/Project/ProjectRepository.cs @@ -6,46 +6,36 @@ namespace api.Repositories; -public class ProjectRepository : BaseRepository, IProjectRepository +public class ProjectRepository(DcdDbContext context) : BaseRepository(context), IProjectRepository { - private readonly ILogger _logger; - - public ProjectRepository( - DcdDbContext context, - ILogger logger - ) : base(context) - { - _logger = logger; - } - public async Task GetProject(Guid id) { - return await _context.Projects + return await Context.Projects .FirstOrDefaultAsync(p => (p.Id == id || p.FusionProjectId == id) && !p.IsRevision); } public async Task GetProjectByIdOrExternalId(Guid id) { - return await _context.Projects + return await Context.Projects .FirstOrDefaultAsync(p => p.Id == id || p.FusionProjectId == id); } public async Task GetProjectWithMembersByIdOrExternalId(Guid id) { - return await _context.Projects + return await Context.Projects .Include(p => p.ProjectMembers) .FirstOrDefaultAsync(p => p.Id == id || p.FusionProjectId == id); } public async Task GetProjectByExternalId(Guid id) { - return await _context.Projects + return await Context.Projects .FirstOrDefaultAsync(p => p.FusionProjectId == id); } public async Task GetProjectWithCases(Guid projectId) { - return await _context.Projects + return await Context.Projects .Include(p => p.Cases) .FirstOrDefaultAsync(p => p.Id == projectId); } @@ -72,7 +62,7 @@ public async Task UpdateModifyTime(Guid projectId) throw new ArgumentException("The project id cannot be empty.", nameof(projectId)); } - var project = await _context.Projects.SingleOrDefaultAsync(c => c.Id == projectId) + var project = await Context.Projects.SingleOrDefaultAsync(c => c.Id == projectId) ?? throw new KeyNotFoundException($"Project with id {projectId} not found."); project.ModifyTime = DateTimeOffset.UtcNow; diff --git a/backend/api/Repositories/Project/RevisionRepository.cs b/backend/api/Repositories/Project/RevisionRepository.cs index 736c4d7f6..7a4baa2d9 100644 --- a/backend/api/Repositories/Project/RevisionRepository.cs +++ b/backend/api/Repositories/Project/RevisionRepository.cs @@ -7,29 +7,19 @@ namespace api.Repositories; -public class RevisionRepository : BaseRepository, IRevisionRepository +public class RevisionRepository(DcdDbContext context) : BaseRepository(context), IRevisionRepository { - private readonly ILogger _logger; - - public RevisionRepository( - DcdDbContext context, - ILogger logger - ) : base(context) - { - _logger = logger; - } - public async Task AddRevision(Project project) { - _context.Projects.Add(project); - await _context.SaveChangesAsync(); + Context.Projects.Add(project); + await Context.SaveChangesAsync(); return project; } public async Task GetProjectAndAssetsNoTracking(Guid id) { - var projectQuery = _context.Projects.AsQueryable(); + var projectQuery = Context.Projects.AsQueryable(); projectQuery = IncludeProjectDetails(projectQuery); projectQuery = IncludeCaseDetails(projectQuery); projectQuery = IncludeDrainageStrategyDetails(projectQuery); diff --git a/backend/api/Repositories/ProjectMemberRepository.cs b/backend/api/Repositories/ProjectMemberRepository.cs index 606273eea..9156c19dd 100644 --- a/backend/api/Repositories/ProjectMemberRepository.cs +++ b/backend/api/Repositories/ProjectMemberRepository.cs @@ -6,31 +6,21 @@ namespace api.Repositories; -public class ProjectMemberRepository : BaseRepository, IProjectMemberRepository +public class ProjectMemberRepository(DcdDbContext context) : BaseRepository(context), IProjectMemberRepository { - private readonly ILogger _logger; - - public ProjectMemberRepository( - DcdDbContext context, - ILogger logger - ) : base(context) - { - _logger = logger; - } - public async Task CreateProjectMember(ProjectMember projectMember) { - return (await _context.ProjectMembers.AddAsync(projectMember)).Entity; + return (await Context.ProjectMembers.AddAsync(projectMember)).Entity; } public void DeleteProjectMember(ProjectMember projectMember) { - _context.ProjectMembers.Remove(projectMember); + Context.ProjectMembers.Remove(projectMember); } public async Task GetProjectMember(Guid projectId, Guid userId) { - return await _context.ProjectMembers + return await Context.ProjectMembers .SingleOrDefaultAsync(c => c.ProjectId == projectId && c.UserId == userId); } } diff --git a/backend/api/Repositories/Substructure/SubstructureRepository.cs b/backend/api/Repositories/Substructure/SubstructureRepository.cs index 3cf96e95e..6513e1e94 100644 --- a/backend/api/Repositories/Substructure/SubstructureRepository.cs +++ b/backend/api/Repositories/Substructure/SubstructureRepository.cs @@ -8,13 +8,8 @@ namespace api.Repositories; -public class SubstructureRepository : BaseRepository, ISubstructureRepository +public class SubstructureRepository(DcdDbContext context) : BaseRepository(context), ISubstructureRepository { - - public SubstructureRepository(DcdDbContext context) : base(context) - { - } - public async Task GetSubstructure(Guid substructureId) { return await Get(substructureId); @@ -27,14 +22,14 @@ public SubstructureRepository(DcdDbContext context) : base(context) public async Task GetSubstructureWithCostProfile(Guid substructureId) { - return await _context.Substructures + return await Context.Substructures .Include(t => t.CostProfile) .FirstOrDefaultAsync(t => t.Id == substructureId); } public async Task SubstructureHasCostProfileOverride(Guid substructureId) { - return await _context.Substructures + return await Context.Substructures .AnyAsync(t => t.Id == substructureId && t.CostProfileOverride != null); } diff --git a/backend/api/Repositories/Substructure/SubstructureTimeSeriesRepository.cs b/backend/api/Repositories/Substructure/SubstructureTimeSeriesRepository.cs index 93646812b..b5a4d6969 100644 --- a/backend/api/Repositories/Substructure/SubstructureTimeSeriesRepository.cs +++ b/backend/api/Repositories/Substructure/SubstructureTimeSeriesRepository.cs @@ -1,21 +1,14 @@ using api.Context; using api.Models; -using Microsoft.EntityFrameworkCore; - namespace api.Repositories; -public class SubstructureTimeSeriesRepository : BaseRepository, ISubstructureTimeSeriesRepository +public class SubstructureTimeSeriesRepository(DcdDbContext context) : BaseRepository(context), ISubstructureTimeSeriesRepository { - - public SubstructureTimeSeriesRepository(DcdDbContext context) : base(context) - { - } - public SubstructureCostProfile CreateSubstructureCostProfile(SubstructureCostProfile substructureCostProfile) { - _context.SubstructureCostProfiles.Add(substructureCostProfile); + Context.SubstructureCostProfiles.Add(substructureCostProfile); return substructureCostProfile; } @@ -31,7 +24,7 @@ public SubstructureCostProfile UpdateSubstructureCostProfile(SubstructureCostPro public SubstructureCostProfileOverride CreateSubstructureCostProfileOverride(SubstructureCostProfileOverride profile) { - _context.SubstructureCostProfileOverride.Add(profile); + Context.SubstructureCostProfileOverride.Add(profile); return profile; } diff --git a/backend/api/Repositories/Surf/SurfRepository.cs b/backend/api/Repositories/Surf/SurfRepository.cs index a9d836357..378462d58 100644 --- a/backend/api/Repositories/Surf/SurfRepository.cs +++ b/backend/api/Repositories/Surf/SurfRepository.cs @@ -8,13 +8,8 @@ namespace api.Repositories; -public class SurfRepository : BaseRepository, ISurfRepository +public class SurfRepository(DcdDbContext context) : BaseRepository(context), ISurfRepository { - - public SurfRepository(DcdDbContext context) : base(context) - { - } - public async Task GetSurf(Guid surfId) { return await Get(surfId); @@ -27,14 +22,14 @@ public SurfRepository(DcdDbContext context) : base(context) public async Task GetSurfWithCostProfile(Guid surfId) { - return await _context.Surfs + return await Context.Surfs .Include(t => t.CostProfile) .FirstOrDefaultAsync(t => t.Id == surfId); } public async Task SurfHasCostProfileOverride(Guid surfId) { - return await _context.Surfs + return await Context.Surfs .AnyAsync(t => t.Id == surfId && t.CostProfileOverride != null); } diff --git a/backend/api/Repositories/Surf/SurfTimeSeriesRepository.cs b/backend/api/Repositories/Surf/SurfTimeSeriesRepository.cs index edcf8e4c0..6600df745 100644 --- a/backend/api/Repositories/Surf/SurfTimeSeriesRepository.cs +++ b/backend/api/Repositories/Surf/SurfTimeSeriesRepository.cs @@ -1,21 +1,14 @@ using api.Context; using api.Models; -using Microsoft.EntityFrameworkCore; - namespace api.Repositories; -public class SurfTimeSeriesRepository : BaseRepository, ISurfTimeSeriesRepository +public class SurfTimeSeriesRepository(DcdDbContext context) : BaseRepository(context), ISurfTimeSeriesRepository { - - public SurfTimeSeriesRepository(DcdDbContext context) : base(context) - { - } - public SurfCostProfile CreateSurfCostProfile(SurfCostProfile surfCostProfile) { - _context.SurfCostProfile.Add(surfCostProfile); + Context.SurfCostProfile.Add(surfCostProfile); return surfCostProfile; } @@ -31,7 +24,7 @@ public SurfCostProfile UpdateSurfCostProfile(SurfCostProfile surfCostProfile) public SurfCostProfileOverride CreateSurfCostProfileOverride(SurfCostProfileOverride profile) { - _context.SurfCostProfileOverride.Add(profile); + Context.SurfCostProfileOverride.Add(profile); return profile; } diff --git a/backend/api/Repositories/Topside/TopsideRepository.cs b/backend/api/Repositories/Topside/TopsideRepository.cs index 55f3cbfa9..88e8eab15 100644 --- a/backend/api/Repositories/Topside/TopsideRepository.cs +++ b/backend/api/Repositories/Topside/TopsideRepository.cs @@ -8,13 +8,8 @@ namespace api.Repositories; -public class TopsideRepository : BaseRepository, ITopsideRepository +public class TopsideRepository(DcdDbContext context) : BaseRepository(context), ITopsideRepository { - - public TopsideRepository(DcdDbContext context) : base(context) - { - } - public async Task GetTopside(Guid topsideId) { return await Get(topsideId); @@ -27,14 +22,14 @@ public TopsideRepository(DcdDbContext context) : base(context) public async Task GetTopsideWithCostProfile(Guid topsideId) { - return await _context.Topsides + return await Context.Topsides .Include(t => t.CostProfile) .FirstOrDefaultAsync(t => t.Id == topsideId); } public async Task TopsideHasCostProfileOverride(Guid topsideId) { - return await _context.Topsides + return await Context.Topsides .AnyAsync(t => t.Id == topsideId && t.CostProfileOverride != null); } diff --git a/backend/api/Repositories/Topside/TopsideTimeSeriesRepository.cs b/backend/api/Repositories/Topside/TopsideTimeSeriesRepository.cs index e017afc77..8d16de769 100644 --- a/backend/api/Repositories/Topside/TopsideTimeSeriesRepository.cs +++ b/backend/api/Repositories/Topside/TopsideTimeSeriesRepository.cs @@ -1,18 +1,11 @@ using api.Context; using api.Models; -using Microsoft.EntityFrameworkCore; - namespace api.Repositories; -public class TopsideTimeSeriesRepository : BaseRepository, ITopsideTimeSeriesRepository +public class TopsideTimeSeriesRepository(DcdDbContext context) : BaseRepository(context), ITopsideTimeSeriesRepository { - - public TopsideTimeSeriesRepository(DcdDbContext context) : base(context) - { - } - public async Task GetTopsideCostProfile(Guid topsideCostProfileId) { return await GetWithIncludes(topsideCostProfileId, t => t.Topside); @@ -20,7 +13,7 @@ public TopsideTimeSeriesRepository(DcdDbContext context) : base(context) public TopsideCostProfile CreateTopsideCostProfile(TopsideCostProfile topsideCostProfile) { - _context.TopsideCostProfiles.Add(topsideCostProfile); + Context.TopsideCostProfiles.Add(topsideCostProfile); return topsideCostProfile; } @@ -31,7 +24,7 @@ public TopsideCostProfile UpdateTopsideCostProfile(TopsideCostProfile topsideCos public TopsideCostProfileOverride CreateTopsideCostProfileOverride(TopsideCostProfileOverride profile) { - _context.TopsideCostProfileOverride.Add(profile); + Context.TopsideCostProfileOverride.Add(profile); return profile; } diff --git a/backend/api/Repositories/Transport/TransportRepository.cs b/backend/api/Repositories/Transport/TransportRepository.cs index c3fb98f00..249995faa 100644 --- a/backend/api/Repositories/Transport/TransportRepository.cs +++ b/backend/api/Repositories/Transport/TransportRepository.cs @@ -8,13 +8,8 @@ namespace api.Repositories; -public class TransportRepository : BaseRepository, ITransportRepository +public class TransportRepository(DcdDbContext context) : BaseRepository(context), ITransportRepository { - - public TransportRepository(DcdDbContext context) : base(context) - { - } - public async Task GetTransport(Guid transportId) { return await Get(transportId); @@ -27,14 +22,14 @@ public TransportRepository(DcdDbContext context) : base(context) public async Task GetTransportWithCostProfile(Guid transportId) { - return await _context.Transports + return await Context.Transports .Include(t => t.CostProfile) .FirstOrDefaultAsync(t => t.Id == transportId); } public async Task TransportHasCostProfileOverride(Guid transportId) { - return await _context.Transports + return await Context.Transports .AnyAsync(t => t.Id == transportId && t.CostProfileOverride != null); } diff --git a/backend/api/Repositories/Transport/TransportTimeSeriesRepository.cs b/backend/api/Repositories/Transport/TransportTimeSeriesRepository.cs index c3aea504c..28dea88a2 100644 --- a/backend/api/Repositories/Transport/TransportTimeSeriesRepository.cs +++ b/backend/api/Repositories/Transport/TransportTimeSeriesRepository.cs @@ -1,21 +1,14 @@ using api.Context; using api.Models; -using Microsoft.EntityFrameworkCore; - namespace api.Repositories; -public class TransportTimeSeriesRepository : BaseRepository, ITransportTimeSeriesRepository +public class TransportTimeSeriesRepository(DcdDbContext context) : BaseRepository(context), ITransportTimeSeriesRepository { - - public TransportTimeSeriesRepository(DcdDbContext context) : base(context) - { - } - public TransportCostProfile CreateTransportCostProfile(TransportCostProfile transportCostProfile) { - _context.TransportCostProfile.Add(transportCostProfile); + Context.TransportCostProfile.Add(transportCostProfile); return transportCostProfile; } @@ -31,7 +24,7 @@ public TransportCostProfile UpdateTransportCostProfile(TransportCostProfile tran public TransportCostProfileOverride CreateTransportCostProfileOverride(TransportCostProfileOverride profile) { - _context.TransportCostProfileOverride.Add(profile); + Context.TransportCostProfileOverride.Add(profile); return profile; } diff --git a/backend/api/Repositories/Well/WellRepository.cs b/backend/api/Repositories/Well/WellRepository.cs index ed23d8a44..d19b1041f 100644 --- a/backend/api/Repositories/Well/WellRepository.cs +++ b/backend/api/Repositories/Well/WellRepository.cs @@ -6,13 +6,8 @@ namespace api.Repositories; -public class WellRepository : BaseRepository, IWellRepository +public class WellRepository(DcdDbContext context) : BaseRepository(context), IWellRepository { - - public WellRepository(DcdDbContext context) : base(context) - { - } - public async Task GetWell(Guid wellId) { return await Get(wellId); @@ -20,7 +15,7 @@ public WellRepository(DcdDbContext context) : base(context) public async Task> GetCasesAffectedByDeleteWell(Guid wellId) { - var well = await _context.Wells + var well = await Context.Wells .Include(w => w.WellProjectWells)! .ThenInclude(wp => wp.DrillingSchedule) .Include(w => w.WellProjectWells)! @@ -43,7 +38,7 @@ public async Task> GetCasesAffectedByDeleteWell(Guid wellId) .Select(ew => ew.Exploration.Id) .Distinct() ?? []; - var cases = await _context.Cases + var cases = await Context.Cases .Where(c => wellProjectIds.Contains(c.WellProjectLink) || explorationIds.Contains(c.ExplorationLink)) .ToListAsync(); @@ -57,12 +52,12 @@ public Well UpdateWell(Well well) public Well AddWell(Well well) { - _context.Add(well); + Context.Add(well); return well; } public void DeleteWell(Well well) { - _context.Remove(well); + Context.Remove(well); } } diff --git a/backend/api/Repositories/WellProject/IWellProjectTimeSeriesRepository.cs b/backend/api/Repositories/WellProject/IWellProjectTimeSeriesRepository.cs index 090a4f9f7..dec814acf 100644 --- a/backend/api/Repositories/WellProject/IWellProjectTimeSeriesRepository.cs +++ b/backend/api/Repositories/WellProject/IWellProjectTimeSeriesRepository.cs @@ -1,4 +1,3 @@ -using api.Enums; using api.Models; namespace api.Repositories; diff --git a/backend/api/Repositories/WellProject/WellProjectRepository.cs b/backend/api/Repositories/WellProject/WellProjectRepository.cs index a5a1b6449..5b6fcdf1f 100644 --- a/backend/api/Repositories/WellProject/WellProjectRepository.cs +++ b/backend/api/Repositories/WellProject/WellProjectRepository.cs @@ -9,13 +9,8 @@ namespace api.Repositories; -public class WellProjectRepository : BaseRepository, IWellProjectRepository +public class WellProjectRepository(DcdDbContext context) : BaseRepository(context), IWellProjectRepository { - - public WellProjectRepository(DcdDbContext context) : base(context) - { - } - public async Task GetWellProject(Guid wellProjectId) { return await Get(wellProjectId); @@ -41,7 +36,7 @@ public async Task WellProjectHasProfile(Guid WellProjectId, WellProjectPro WellProjectProfileNames.GasInjectorCostProfileOverride => d => d.GasInjectorCostProfileOverride != null, }; - bool hasProfile = await _context.WellProjects + bool hasProfile = await Context.WellProjects .Where(d => d.Id == WellProjectId) .AnyAsync(profileExistsExpression); @@ -60,7 +55,7 @@ public WellProject UpdateWellProject(WellProject wellProject) public async Task GetWellProjectWithDrillingSchedule(Guid drillingScheduleId) { - var wellProject = await _context.WellProjects + var wellProject = await Context.WellProjects .Include(e => e.WellProjectWells)! .ThenInclude(w => w.DrillingSchedule) .FirstOrDefaultAsync(e => e.WellProjectWells != null && e.WellProjectWells.Any(w => w.DrillingScheduleId == drillingScheduleId)); @@ -75,7 +70,7 @@ public DrillingSchedule UpdateWellProjectWellDrillingSchedule(DrillingSchedule d public WellProjectWell CreateWellProjectWellDrillingSchedule(WellProjectWell wellProjectWellWithDrillingSchedule) { - _context.WellProjectWell.Add(wellProjectWellWithDrillingSchedule); + Context.WellProjectWell.Add(wellProjectWellWithDrillingSchedule); return wellProjectWellWithDrillingSchedule; } } diff --git a/backend/api/Repositories/WellProject/WellProjectTimeSeriesRepository.cs b/backend/api/Repositories/WellProject/WellProjectTimeSeriesRepository.cs index 991c0b456..e7a6e8518 100644 --- a/backend/api/Repositories/WellProject/WellProjectTimeSeriesRepository.cs +++ b/backend/api/Repositories/WellProject/WellProjectTimeSeriesRepository.cs @@ -1,42 +1,32 @@ -using System.Linq.Expressions; - using api.Context; -using api.Enums; using api.Models; -using Microsoft.EntityFrameworkCore; - namespace api.Repositories; -public class WellProjectTimeSeriesRepository : BaseRepository, IWellProjectTimeSeriesRepository +public class WellProjectTimeSeriesRepository(DcdDbContext context) : BaseRepository(context), IWellProjectTimeSeriesRepository { - - public WellProjectTimeSeriesRepository(DcdDbContext context) : base(context) - { - } - public OilProducerCostProfileOverride CreateOilProducerCostProfileOverride(OilProducerCostProfileOverride profile) { - _context.OilProducerCostProfileOverride.Add(profile); + Context.OilProducerCostProfileOverride.Add(profile); return profile; } public GasProducerCostProfileOverride CreateGasProducerCostProfileOverride(GasProducerCostProfileOverride profile) { - _context.GasProducerCostProfileOverride.Add(profile); + Context.GasProducerCostProfileOverride.Add(profile); return profile; } public WaterInjectorCostProfileOverride CreateWaterInjectorCostProfileOverride(WaterInjectorCostProfileOverride profile) { - _context.WaterInjectorCostProfileOverride.Add(profile); + Context.WaterInjectorCostProfileOverride.Add(profile); return profile; } public GasInjectorCostProfileOverride CreateGasInjectorCostProfileOverride(GasInjectorCostProfileOverride profile) { - _context.GasInjectorCostProfileOverride.Add(profile); + Context.GasInjectorCostProfileOverride.Add(profile); return profile; } diff --git a/backend/api/SampleData/Builders/CaseBuilder.cs b/backend/api/SampleData/Builders/CaseBuilder.cs index 3c949d34a..cb4c2e2c5 100644 --- a/backend/api/SampleData/Builders/CaseBuilder.cs +++ b/backend/api/SampleData/Builders/CaseBuilder.cs @@ -10,7 +10,7 @@ public CaseBuilder WithDrainageStrategy(string drainageStrategyName, Project pro var drainageStrategy = project.DrainageStrategies!.FirstOrDefault(d => d.Name.Equals(drainageStrategyName)); if (drainageStrategy == null) { - throw new Exception(string.Format("Drainage strategy {0} not found", drainageStrategyName)); + throw new Exception($"Drainage strategy {drainageStrategyName} not found"); } DrainageStrategyLink = drainageStrategy.Id; return this; @@ -20,7 +20,7 @@ public CaseBuilder WithWellProject(string wellProjectName, Project project) var wellProject = project.WellProjects!.FirstOrDefault(d => d.Name.Equals(wellProjectName)); if (wellProject == null) { - throw new Exception(string.Format("Drainage strategy {0} not found", wellProjectName)); + throw new Exception($"Drainage strategy {wellProjectName} not found"); } WellProjectLink = wellProject.Id; return this; @@ -30,7 +30,7 @@ public CaseBuilder WithSurf(string surfName, Project project) var surf = project.Surfs!.FirstOrDefault(d => d.Name.Equals(surfName)); if (surf == null) { - throw new Exception(string.Format("Surf {0} not found", surfName)); + throw new Exception($"Surf {surfName} not found"); } SurfLink = surf.Id; return this; @@ -40,7 +40,7 @@ public CaseBuilder WithSubstructure(string substructureName, Project project) var substructure = project.Substructures!.FirstOrDefault(d => d.Name.Equals(substructureName)); if (substructure == null) { - throw new Exception(string.Format("Substructure {0} not found", substructureName)); + throw new Exception($"Substructure {substructureName} not found"); } SubstructureLink = substructure.Id; return this; @@ -50,7 +50,7 @@ public CaseBuilder WithTopside(string topsideName, Project project) var topside = project.Topsides!.FirstOrDefault(d => d.Name.Equals(topsideName)); if (topside == null) { - throw new Exception(string.Format("Topside {0} not found", topsideName)); + throw new Exception($"Topside {topsideName} not found"); } TopsideLink = topside.Id; return this; @@ -60,7 +60,7 @@ public CaseBuilder WithTransport(string transportName, Project project) var transport = project.Transports!.FirstOrDefault(d => d.Name.Equals(transportName)); if (transport == null) { - throw new Exception(string.Format("Transport {0} not found", transportName)); + throw new Exception($"Transport {transportName} not found"); } TransportLink = transport.Id; return this; @@ -70,7 +70,7 @@ public CaseBuilder WithExploration(string explorationName, Project project) var transport = project.Explorations!.FirstOrDefault(d => d.Name.Equals(explorationName)); if (transport == null) { - throw new Exception(string.Format("Exploration {0} not found", explorationName)); + throw new Exception($"Exploration {explorationName} not found"); } ExplorationLink = transport.Id; return this; diff --git a/backend/api/SampleData/Builders/ProjectsBuilder.cs b/backend/api/SampleData/Builders/ProjectsBuilder.cs index 7ee77a5d1..5a5e4ea8d 100644 --- a/backend/api/SampleData/Builders/ProjectsBuilder.cs +++ b/backend/api/SampleData/Builders/ProjectsBuilder.cs @@ -17,7 +17,7 @@ public ProjectBuilder ForProject(string projectName) var projectBuilder = Projects.FirstOrDefault(p => p.Name.Equals(projectName)); if (projectBuilder == null) { - throw new Exception(string.Format("Cannot find project {0}", projectName)); + throw new Exception($"Cannot find project {projectName}"); } return projectBuilder; } diff --git a/backend/api/Services/Access/ProjectAccessService.cs b/backend/api/Services/Access/ProjectAccessService.cs index a558b2e72..11881d77e 100644 --- a/backend/api/Services/Access/ProjectAccessService.cs +++ b/backend/api/Services/Access/ProjectAccessService.cs @@ -7,23 +7,10 @@ namespace api.Services; -public class ProjectAccessService : IProjectAccessService +public class ProjectAccessService( + IProjectAccessRepository projectAccessRepository, + IHttpContextAccessor httpContextAccessor) : IProjectAccessService { - private readonly ILogger _logger; - private readonly IProjectAccessRepository _projectAccessRepository; - private readonly IHttpContextAccessor _httpContextAccessor; - - public ProjectAccessService( - IProjectAccessRepository projectAccessRepository, - IHttpContextAccessor httpContextAccessor, - ILoggerFactory loggerFactory - ) - { - _projectAccessRepository = projectAccessRepository; - _httpContextAccessor = httpContextAccessor; - _logger = loggerFactory.CreateLogger(); - } - /// /// Checks whether the project with the specified project ID exists on the entity with the given entity ID. /// This method is intended to be used to verify the project checked in the authorization handler is correct. @@ -33,7 +20,7 @@ ILoggerFactory loggerFactory public async Task ProjectExists(Guid projectIdFromUrl, Guid entityId) where T : class, IHasProjectId { - var entity = await _projectAccessRepository.Get(entityId); + var entity = await projectAccessRepository.Get(entityId); if (entity == null) { throw new NotFoundInDBException($"Entity of type {typeof(T)} with id {entityId} not found."); @@ -46,7 +33,7 @@ public async Task ProjectExists(Guid projectIdFromUrl, Guid entityId) public async Task GetUserProjectAccess(Guid externalId) { - var userRoles = _httpContextAccessor.HttpContext?.User.AssignedApplicationRoles(); + var userRoles = httpContextAccessor.HttpContext?.User.AssignedApplicationRoles(); if (userRoles == null) { @@ -58,7 +45,7 @@ public async Task GetUserProjectAccess(Guid externalId) }; } - var _ = await _projectAccessRepository.GetProjectByExternalId(externalId) + var _ = await projectAccessRepository.GetProjectByExternalId(externalId) ?? throw new NotFoundInDBException($"Project with external ID {externalId} not found."); bool isAdmin = userRoles.Contains(ApplicationRole.Admin); diff --git a/backend/api/Services/CompareCasesService.cs b/backend/api/Services/CompareCasesService.cs index efc76cef0..31b966e2d 100644 --- a/backend/api/Services/CompareCasesService.cs +++ b/backend/api/Services/CompareCasesService.cs @@ -1,39 +1,21 @@ using api.Dtos; using api.Models; -using api.Services.GenerateCostProfiles; namespace api.Services; -public class CompareCasesService : ICompareCasesService +public class CompareCasesService( + IProjectService projectService, + ILogger logger, + IExplorationService explorationService, + IDrainageStrategyService drainageStrategyService, + IStudyCostProfileService generateStudyCostProfile, + ICaseService caseService) + : ICompareCasesService { - private readonly IProjectService _projectService; - private readonly ILogger _logger; - private readonly IExplorationService _explorationService; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IStudyCostProfileService _generateStudyCostProfile; - private readonly ICaseService _caseService; - - - public CompareCasesService( - IProjectService projectService, - ILoggerFactory loggerFactory, - IExplorationService explorationService, - IDrainageStrategyService drainageStrategyService, - IStudyCostProfileService generateStudyCostProfile, - ICaseService caseService) - { - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - _explorationService = explorationService; - _drainageStrategyService = drainageStrategyService; - _generateStudyCostProfile = generateStudyCostProfile; - _caseService = caseService; - } - public async Task> Calculate(Guid projectId) { - var project = await _projectService.GetProjectWithoutAssetsNoTracking(projectId); + var project = await projectService.GetProjectWithoutAssetsNoTracking(projectId); var caseList = new List(); if (project.Cases != null) { @@ -42,7 +24,7 @@ public async Task> Calculate(Guid projectId) foreach (var caseItem in project.Cases) { if (caseItem.Archived) { continue; } - var caseWithProfiles = await _caseService.GetCaseWithIncludes( + var caseWithProfiles = await caseService.GetCaseWithIncludes( caseItem.Id, c => c.CessationWellsCostOverride!, c => c.CessationWellsCost!, @@ -62,7 +44,7 @@ public async Task> Calculate(Guid projectId) c => c.OnshoreRelatedOPEXCostProfile!, c => c.AdditionalOPEXCostProfile!); - drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.ProductionProfileOil!, d => d.AdditionalProductionProfileOil!, @@ -71,7 +53,7 @@ public async Task> Calculate(Guid projectId) d => d.Co2EmissionsOverride!, d => d.Co2Emissions!); - exploration = await _explorationService.GetExplorationWithIncludes( + exploration = await explorationService.GetExplorationWithIncludes( caseItem.ExplorationLink, e => e.GAndGAdminCost!, e => e.CountryOfficeCost!, @@ -140,7 +122,7 @@ private double CalculateTotalOilProduction(Case caseItem, Project project, Drain } catch (ArgumentException) { - _logger.LogInformation("DrainageStrategy {0} not found.", caseItem.DrainageStrategyLink); + logger.LogInformation("DrainageStrategy {0} not found.", caseItem.DrainageStrategyLink); } if (project.PhysicalUnit != 0 && !excludeOilFieldConversion) @@ -170,7 +152,7 @@ private double CalculateTotalGasProduction(Case caseItem, Project project, Drain } catch (ArgumentException) { - _logger.LogInformation("DrainageStrategy {0} not found.", caseItem.DrainageStrategyLink); + logger.LogInformation("DrainageStrategy {0} not found.", caseItem.DrainageStrategyLink); } if (project.PhysicalUnit != 0 && !excludeOilFieldConversion) @@ -243,12 +225,12 @@ private double CalculateTotalCessationCosts(Case caseItem) private async Task CalculateOffshorePlusOnshoreFacilityCosts(Case caseItem) { - return await _generateStudyCostProfile.SumAllCostFacility(caseItem); + return await generateStudyCostProfile.SumAllCostFacility(caseItem); } private async Task CalculateDevelopmentWellCosts(Case caseItem) { - return await _generateStudyCostProfile.SumWellCost(caseItem); + return await generateStudyCostProfile.SumWellCost(caseItem); } private double CalculateExplorationWellCosts(Case caseItem, Exploration exploration) @@ -284,7 +266,7 @@ private double CalculateExplorationWellCosts(Case caseItem, Exploration explorat } catch (ArgumentException) { - _logger.LogInformation("Exploration {0} not found.", caseItem.ExplorationLink); + logger.LogInformation("Exploration {0} not found.", caseItem.ExplorationLink); } return sumExplorationWellCost; diff --git a/backend/api/Services/CostProfileFromDrillingScheduleHelper.cs b/backend/api/Services/CostProfileFromDrillingScheduleHelper.cs index 64855da6f..13f7805fa 100644 --- a/backend/api/Services/CostProfileFromDrillingScheduleHelper.cs +++ b/backend/api/Services/CostProfileFromDrillingScheduleHelper.cs @@ -9,25 +9,11 @@ namespace api.Services; -public class CostProfileFromDrillingScheduleHelper : ICostProfileFromDrillingScheduleHelper +public class CostProfileFromDrillingScheduleHelper( + DcdDbContext context, + ICaseService caseService, + IMapper mapper) : ICostProfileFromDrillingScheduleHelper { - private readonly ILogger _logger; - private readonly ICaseService _caseService; - private readonly DcdDbContext _context; - private readonly IMapper _mapper; - - public CostProfileFromDrillingScheduleHelper( - DcdDbContext context, - ILoggerFactory loggerFactory, - ICaseService caseService, - IMapper mapper) - { - _logger = loggerFactory.CreateLogger(); - _caseService = caseService; - _context = context; - _mapper = mapper; - } - public async Task UpdateCostProfilesForWells(List wellIds) { var explorationWells = GetAllExplorationWells().Where(ew => wellIds.Contains(ew.WellId)); @@ -37,8 +23,8 @@ public async Task UpdateCostProfilesForWells(List wellIds) var uniqueExplorationIds = explorationWells.Select(ew => ew.ExplorationId).Distinct(); var uniqueWellProjectIds = wellProjectWells.Select(wpw => wpw.WellProjectId).Distinct(); - var explorationCases = (await _caseService.GetAll()).Where(c => uniqueExplorationIds.Contains(c.ExplorationLink)); - var wellProjectCases = (await _caseService.GetAll()).Where(c => uniqueWellProjectIds.Contains(c.WellProjectLink)); + var explorationCases = (await caseService.GetAll()).Where(c => uniqueExplorationIds.Contains(c.ExplorationLink)); + var wellProjectCases = (await caseService.GetAll()).Where(c => uniqueWellProjectIds.Contains(c.WellProjectLink)); var explorationCaseIds = explorationCases.Select(c => c.Id).Distinct(); var wellProjectCaseIds = wellProjectCases.Select(c => c.Id).Distinct(); @@ -61,7 +47,7 @@ public async Task UpdateCostProfilesForWells(List wellIds) UpdateWellProjects(updatedWellProjectDtoList.ToArray()); - await _context.SaveChangesAsync(); + await context.SaveChangesAsync(); } private WellProjectWithProfilesDto[] UpdateWellProjects(WellProject[] updatedWellProjects) @@ -69,8 +55,8 @@ private WellProjectWithProfilesDto[] UpdateWellProjects(WellProject[] updatedWel var updatedWellProjectDtoList = new List(); foreach (var updatedWellProject in updatedWellProjects) { - var wellProject = _context.WellProjects!.Update(updatedWellProject); - var wellProjectDto = _mapper.Map(wellProject.Entity); + var wellProject = context.WellProjects!.Update(updatedWellProject); + var wellProjectDto = mapper.Map(wellProject.Entity); if (wellProjectDto == null) { throw new ArgumentNullException(nameof(wellProjectDto)); @@ -86,8 +72,8 @@ private ExplorationWithProfilesDto[] UpdateExplorations(Exploration[] updatedExp var updatedExplorationDtoList = new List(); foreach (var updatedExploration in updatedExplorations) { - var exploration = _context.Explorations!.Update(updatedExploration); - var explorationDto = _mapper.Map(exploration.Entity); + var exploration = context.Explorations!.Update(updatedExploration); + var explorationDto = mapper.Map(exploration.Entity); if (explorationDto == null) { throw new ArgumentNullException(nameof(explorationDto)); @@ -100,21 +86,21 @@ private ExplorationWithProfilesDto[] UpdateExplorations(Exploration[] updatedExp private async Task GetExploration(Guid explorationId) { - var exploration = await _context.Explorations!.FindAsync(explorationId) - ?? throw new NotFoundInDBException(string.Format("Exploration {0} not found in database.", explorationId)); + var exploration = await context.Explorations!.FindAsync(explorationId) + ?? throw new NotFoundInDBException($"Exploration {explorationId} not found in database."); return exploration; } private async Task GetWellProject(Guid wellProjectId) { - var wellProject = await _context.WellProjects!.FindAsync(wellProjectId) - ?? throw new NotFoundInDBException(string.Format("WellProject {0} not found in database.", wellProjectId)); + var wellProject = await context.WellProjects!.FindAsync(wellProjectId) + ?? throw new NotFoundInDBException($"WellProject {wellProjectId} not found in database."); return wellProject; } private async Task UpdateExplorationCostProfilesForCase(Guid caseId) { - var caseItem = await _caseService.GetCase(caseId); + var caseItem = await caseService.GetCase(caseId); return await UpdateExplorationCostProfiles(caseItem.ExplorationLink); } @@ -194,7 +180,7 @@ private static TimeSeries GenerateExplorationCostProfileFromDrillingSche private async Task UpdateWellProjectCostProfilesForCase(Guid caseId) { - var caseItem = await _caseService.GetCase(caseId); + var caseItem = await caseService.GetCase(caseId); return await UpdateWellProjectCostProfiles(caseItem.WellProjectLink); } @@ -284,9 +270,9 @@ private static TimeSeries GenerateWellProjectCostProfileFromDrillingSche private IQueryable GetAllWells() { - if (_context.Wells != null) + if (context.Wells != null) { - return _context.Wells; + return context.Wells; } else { @@ -296,11 +282,11 @@ private IQueryable GetAllWells() private IQueryable GetAllExplorationWells() { - return _context.ExplorationWell.Include(ew => ew.DrillingSchedule); + return context.ExplorationWell.Include(ew => ew.DrillingSchedule); } private IQueryable GetAllWellProjectWells() { - return _context.WellProjectWell.Include(wpw => wpw.DrillingSchedule); + return context.WellProjectWell.Include(wpw => wpw.DrillingSchedule); } } diff --git a/backend/api/Services/DuplicateCaseService.cs b/backend/api/Services/DuplicateCaseService.cs index d4db79092..a641f98ad 100644 --- a/backend/api/Services/DuplicateCaseService.cs +++ b/backend/api/Services/DuplicateCaseService.cs @@ -7,26 +7,13 @@ namespace api.Services; -public class DuplicateCaseService : IDuplicateCaseService +public class DuplicateCaseService( + DcdDbContext context, + IProjectService projectService) : IDuplicateCaseService { - private readonly DcdDbContext _context; - private readonly IProjectService _projectService; - private readonly ILogger _logger; - - public DuplicateCaseService( - DcdDbContext context, - IProjectService projectService, - ILoggerFactory loggerFactory - ) - { - _context = context; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - } - private async Task GetCaseNoTracking(Guid caseId) { - var caseItem = await _context.Cases + var caseItem = await context.Cases .AsNoTracking() .Include(c => c.TotalFeasibilityAndConceptStudies) .Include(c => c.TotalFeasibilityAndConceptStudiesOverride) @@ -50,7 +37,7 @@ private async Task GetCaseNoTracking(Guid caseId) .FirstOrDefaultAsync(c => c.Id == caseId); if (caseItem == null) { - throw new NotFoundInDBException(string.Format("Case {0} not found.", caseId)); + throw new NotFoundInDBException($"Case {caseId} not found."); } return caseItem; } @@ -85,7 +72,7 @@ public async Task DuplicateCase(Guid caseId) SetNewGuidTimeSeries(caseItem.CalculatedTotalIncomeCostProfile); SetNewGuidTimeSeries(caseItem.CalculatedTotalCostCostProfile); - var project = await _projectService.GetProjectWithCasesAndAssets(caseItem.ProjectId); + var project = await projectService.GetProjectWithCasesAndAssets(caseItem.ProjectId); caseItem.Project = project; if (project.Cases != null) { @@ -113,10 +100,10 @@ public async Task DuplicateCase(Guid caseId) caseItem.WellProjectLink = newWellProject.Id; caseItem.ExplorationLink = newExploration.Id; - _context.Cases.Add(caseItem); + context.Cases.Add(caseItem); - await _context.SaveChangesAsync(); - return await _projectService.GetProjectDto(project.Id); + await context.SaveChangesAsync(); + return await projectService.GetProjectDto(project.Id); } private async Task> CopyExplorationWell(Guid sourceExplorationId, Guid targetExplorationId) @@ -128,14 +115,14 @@ private async Task> CopyExplorationWell(Guid sourceExplora explorationWell.ExplorationId = targetExplorationId; SetNewGuidTimeSeries(explorationWell.DrillingSchedule); - _context.ExplorationWell.Add(explorationWell); + context.ExplorationWell.Add(explorationWell); } return sourceExplorationWells; } private async Task> GetAllExplorationWellForExplorationNoTracking(Guid guid) { - return await _context.ExplorationWell + return await context.ExplorationWell .AsNoTracking() .Where(ew => ew.ExplorationId == guid) .Include(ew => ew.DrillingSchedule) @@ -151,14 +138,14 @@ private async Task> CopyWellProjectWell(Guid sourceWellPro wellProjectWell.WellProjectId = targetWellProjectId; SetNewGuidTimeSeries(wellProjectWell.DrillingSchedule); - _context.WellProjectWell.Add(wellProjectWell); + context.WellProjectWell.Add(wellProjectWell); } return sourceWellProjectWells; } private async Task> GetAllWellProjectWellForWellProjectNoTracking(Guid guid) { - return await _context.WellProjectWell + return await context.WellProjectWell .AsNoTracking() .Where(wpw => wpw.WellProjectId == guid) .Include(wpw => wpw.DrillingSchedule) @@ -176,13 +163,13 @@ private async Task CopyTopside(Guid guid) SetNewGuidTimeSeries(newTopside.CostProfileOverride); SetNewGuidTimeSeries(newTopside.CessationCostProfile); - _context.Topsides.Add(newTopside); + context.Topsides.Add(newTopside); return newTopside; } private async Task GetTopsideNoTracking(Guid topsideId) { - var topside = await _context.Topsides + var topside = await context.Topsides .AsNoTracking() .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) @@ -190,7 +177,7 @@ private async Task GetTopsideNoTracking(Guid topsideId) .FirstOrDefaultAsync(o => o.Id == topsideId); if (topside == null) { - throw new NotFoundInDBException(string.Format("Topside {0} not found.", topsideId)); + throw new NotFoundInDBException($"Topside {topsideId} not found."); } return topside; } @@ -204,13 +191,13 @@ private async Task CopyTransport(Guid guid) SetNewGuidTimeSeries(newTransport.CostProfileOverride); SetNewGuidTimeSeries(newTransport.CessationCostProfile); - _context.Transports.Add(newTransport); + context.Transports.Add(newTransport); return newTransport; } private async Task GetTransportNoTracking(Guid transportId) { - var transport = await _context.Transports + var transport = await context.Transports .AsNoTracking() .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) @@ -218,7 +205,7 @@ private async Task GetTransportNoTracking(Guid transportId) .FirstOrDefaultAsync(c => c.Id == transportId); if (transport == null) { - throw new NotFoundInDBException(string.Format("Transport {0} not found.", transportId)); + throw new NotFoundInDBException($"Transport {transportId} not found."); } return transport; } @@ -232,13 +219,13 @@ private async Task CopySubstructure(Guid guid) SetNewGuidTimeSeries(newSubstructure.CostProfileOverride); SetNewGuidTimeSeries(newSubstructure.CessationCostProfile); - _context.Substructures.Add(newSubstructure); + context.Substructures.Add(newSubstructure); return newSubstructure; } private async Task GetSubstructureNoTracking(Guid substructureId) { - var substructure = await _context.Substructures + var substructure = await context.Substructures .AsNoTracking() .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) @@ -246,7 +233,7 @@ private async Task GetSubstructureNoTracking(Guid substructureId) .FirstOrDefaultAsync(o => o.Id == substructureId); if (substructure == null) { - throw new NotFoundInDBException(string.Format("Substructure {0} not found.", substructureId)); + throw new NotFoundInDBException($"Substructure {substructureId} not found."); } return substructure; } @@ -260,13 +247,13 @@ private async Task CopySurf(Guid guid) SetNewGuidTimeSeries(newSurf.CostProfileOverride); SetNewGuidTimeSeries(newSurf.CessationCostProfile); - _context.Surfs.Add(newSurf); + context.Surfs.Add(newSurf); return newSurf; } private async Task GetSurfNoTracking(Guid surfId) { - var surf = await _context.Surfs + var surf = await context.Surfs .AsNoTracking() .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) @@ -274,7 +261,7 @@ private async Task GetSurfNoTracking(Guid surfId) .FirstOrDefaultAsync(o => o.Id == surfId); if (surf == null) { - throw new NotFoundInDBException(string.Format("Surf {0} not found.", surfId)); + throw new NotFoundInDBException($"Surf {surfId} not found."); } return surf; } @@ -302,13 +289,13 @@ private async Task CopyDrainageStrategy(Guid guid) SetNewGuidTimeSeries(newDrainageStrategy.DeferredOilProduction); SetNewGuidTimeSeries(newDrainageStrategy.DeferredGasProduction); - _context.DrainageStrategies.Add(newDrainageStrategy); + context.DrainageStrategies.Add(newDrainageStrategy); return newDrainageStrategy; } private async Task GetDrainageStrategyNoTracking(Guid drainageStrategyId) { - var drainageStrategy = await _context.DrainageStrategies + var drainageStrategy = await context.DrainageStrategies .AsNoTracking() .Include(c => c.ProductionProfileOil) .Include(c => c.AdditionalProductionProfileOil) @@ -330,7 +317,7 @@ private async Task GetDrainageStrategyNoTracking(Guid drainage .FirstOrDefaultAsync(o => o.Id == drainageStrategyId); if (drainageStrategy == null) { - throw new NotFoundInDBException(string.Format("Drainage strategy {0} not found.", drainageStrategyId)); + throw new NotFoundInDBException($"Drainage strategy {drainageStrategyId} not found."); } return drainageStrategy; } @@ -348,13 +335,13 @@ private async Task CopyExploration(Guid explorationId) SetNewGuidTimeSeries(newExploration.SeismicAcquisitionAndProcessing); SetNewGuidTimeSeries(newExploration.CountryOfficeCost); - _context.Explorations.Add(newExploration); + context.Explorations.Add(newExploration); return newExploration; } private async Task GetExplorationNoTracking(Guid explorationId) { - var exploration = await _context.Explorations + var exploration = await context.Explorations .AsNoTracking() .Include(c => c.ExplorationWellCostProfile) .Include(c => c.AppraisalWellCostProfile) @@ -366,7 +353,7 @@ private async Task GetExplorationNoTracking(Guid explorationId) .FirstOrDefaultAsync(o => o.Id == explorationId); if (exploration == null) { - throw new NotFoundInDBException(string.Format("Exploration {0} not found.", explorationId)); + throw new NotFoundInDBException($"Exploration {explorationId} not found."); } return exploration; } @@ -385,7 +372,7 @@ private async Task CopyWellProject(Guid guid) SetNewGuidTimeSeries(newWellProject.GasInjectorCostProfile); SetNewGuidTimeSeries(newWellProject.GasInjectorCostProfileOverride); - _context.WellProjects.Add(newWellProject); + context.WellProjects.Add(newWellProject); return newWellProject; } @@ -393,7 +380,7 @@ private async Task CopyWellProject(Guid guid) private async Task GetWellProjectNoTracking(Guid wellProjectId) { - var wellProject = await _context.WellProjects + var wellProject = await context.WellProjects .AsNoTracking() .Include(c => c.OilProducerCostProfile) .Include(c => c.OilProducerCostProfileOverride) @@ -406,7 +393,7 @@ private async Task GetWellProjectNoTracking(Guid wellProjectId) .FirstOrDefaultAsync(o => o.Id == wellProjectId); if (wellProject == null) { - throw new NotFoundInDBException(string.Format("Well project {0} not found.", wellProjectId)); + throw new NotFoundInDBException($"Well project {wellProjectId} not found."); } return wellProject; } diff --git a/backend/api/Services/Entities/Case/CaseService.cs b/backend/api/Services/Entities/Case/CaseService.cs index c191722fa..8d3abca51 100644 --- a/backend/api/Services/Entities/Case/CaseService.cs +++ b/backend/api/Services/Entities/Case/CaseService.cs @@ -2,63 +2,40 @@ using api.Context; using api.Dtos; -using api.Enums; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class CaseService : ICaseService +public class CaseService( + DcdDbContext context, + IProjectService projectService, + ILogger logger, + ICaseRepository repository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ICaseService { - private readonly DcdDbContext _context; - private readonly IProjectService _projectService; - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly IMapper _mapper; - private readonly IMapperService _mapperService; - private readonly ICaseRepository _repository; - - public CaseService( - DcdDbContext context, - IProjectService projectService, - ILoggerFactory loggerFactory, - ICaseRepository repository, - IMapperService mapperService, - IMapper mapper, - IProjectAccessService projectAccessService - ) - { - _context = context; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - _mapper = mapper; - _mapperService = mapperService; - _repository = repository; - _projectAccessService = projectAccessService; - } - public async Task DeleteCase(Guid projectId, Guid caseId) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, caseId); + await projectAccessService.ProjectExists(projectId, caseId); var caseItem = await GetCase(caseId); - _context.Cases!.Remove(caseItem); + context.Cases!.Remove(caseItem); - await _context.SaveChangesAsync(); + await context.SaveChangesAsync(); - return await _projectService.GetProjectDto(caseItem.ProjectId); + return await projectService.GetProjectDto(caseItem.ProjectId); } public async Task GetCase(Guid caseId) { - var caseItem = await _context.Cases! + var caseItem = await context.Cases! .Include(c => c.TotalFeasibilityAndConceptStudies) .Include(c => c.TotalFeasibilityAndConceptStudiesOverride) .Include(c => c.TotalFEEDStudies) @@ -79,21 +56,21 @@ public async Task GetCase(Guid caseId) .Include(c => c.CalculatedTotalIncomeCostProfile) .Include(c => c.CalculatedTotalCostCostProfile) .FirstOrDefaultAsync(c => c.Id == caseId) - ?? throw new NotFoundInDBException(string.Format("Case {0} not found.", caseId)); + ?? throw new NotFoundInDBException($"Case {caseId} not found."); return caseItem; } public async Task GetCaseWithIncludes(Guid caseId, params Expression>[] includes) { - return await _repository.GetCaseWithIncludes(caseId, includes) + return await repository.GetCaseWithIncludes(caseId, includes) ?? throw new NotFoundInDBException($"Case with id {caseId} not found."); } // TODO: Delete this method public async Task> GetAll() { - return await _context.Cases.ToListAsync(); + return await context.Cases.ToListAsync(); } public async Task UpdateCase( @@ -104,27 +81,27 @@ TDto updatedCaseDto where TDto : BaseUpdateCaseDto { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, caseId); + await projectAccessService.ProjectExists(projectId, caseId); - var existingCase = await _repository.GetCase(caseId) + var existingCase = await repository.GetCase(caseId) ?? throw new NotFoundInDBException($"Case with id {caseId} not found."); - _mapperService.MapToEntity(updatedCaseDto, existingCase, caseId); + mapperService.MapToEntity(updatedCaseDto, existingCase, caseId); existingCase.ModifyTime = DateTimeOffset.UtcNow; try { - await _repository.SaveChangesAndRecalculateAsync(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update case with id {caseId}.", caseId); + logger.LogError(ex, "Failed to update case with id {caseId}.", caseId); throw; } - await _repository.UpdateModifyTime(caseId); - var dto = _mapperService.MapToDto(existingCase, caseId); + await repository.UpdateModifyTime(caseId); + var dto = mapperService.MapToDto(existingCase, caseId); return dto; } } diff --git a/backend/api/Services/Entities/Case/CaseTimeSeriesService.cs b/backend/api/Services/Entities/Case/CaseTimeSeriesService.cs index 8b35f0e72..1b3172258 100644 --- a/backend/api/Services/Entities/Case/CaseTimeSeriesService.cs +++ b/backend/api/Services/Entities/Case/CaseTimeSeriesService.cs @@ -1,40 +1,21 @@ -using api.Context; using api.Dtos; using api.Enums; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class CaseTimeSeriesService : ICaseTimeSeriesService +public class CaseTimeSeriesService( + ILogger logger, + ICaseTimeSeriesRepository repository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ICaseTimeSeriesService { - private readonly ILogger _logger; - private readonly IMapperService _mapperService; - private readonly ICaseTimeSeriesRepository _repository; - private readonly ICaseRepository _caseRepository; - private readonly IProjectAccessService _projectAccessService; - - - public CaseTimeSeriesService( - ILoggerFactory loggerFactory, - ICaseTimeSeriesRepository repository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _mapperService = mapperService; - _repository = repository; - _caseRepository = caseRepository; - _projectAccessService = projectAccessService; - } - public async Task UpdateCessationWellsCostOverride( Guid projectId, Guid caseId, @@ -47,8 +28,8 @@ UpdateCessationWellsCostOverrideDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetCessationWellsCostOverride, - _repository.UpdateCessationWellsCostOverride + repository.GetCessationWellsCostOverride, + repository.UpdateCessationWellsCostOverride ); } @@ -64,8 +45,8 @@ UpdateCessationOffshoreFacilitiesCostOverrideDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetCessationOffshoreFacilitiesCostOverride, - _repository.UpdateCessationOffshoreFacilitiesCostOverride + repository.GetCessationOffshoreFacilitiesCostOverride, + repository.UpdateCessationOffshoreFacilitiesCostOverride ); } @@ -81,8 +62,8 @@ UpdateCessationOnshoreFacilitiesCostProfileDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetCessationOnshoreFacilitiesCostProfile, - _repository.UpdateCessationOnshoreFacilitiesCostProfile + repository.GetCessationOnshoreFacilitiesCostProfile, + repository.UpdateCessationOnshoreFacilitiesCostProfile ); } @@ -98,8 +79,8 @@ UpdateTotalFeasibilityAndConceptStudiesOverrideDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetTotalFeasibilityAndConceptStudiesOverride, - _repository.UpdateTotalFeasibilityAndConceptStudiesOverride + repository.GetTotalFeasibilityAndConceptStudiesOverride, + repository.UpdateTotalFeasibilityAndConceptStudiesOverride ); } @@ -115,8 +96,8 @@ UpdateTotalFEEDStudiesOverrideDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetTotalFEEDStudiesOverride, - _repository.UpdateTotalFEEDStudiesOverride + repository.GetTotalFEEDStudiesOverride, + repository.UpdateTotalFEEDStudiesOverride ); } @@ -132,8 +113,8 @@ UpdateTotalOtherStudiesCostProfileDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetTotalOtherStudiesCostProfile, - _repository.UpdateTotalOtherStudiesCostProfile + repository.GetTotalOtherStudiesCostProfile, + repository.UpdateTotalOtherStudiesCostProfile ); } @@ -149,8 +130,8 @@ UpdateHistoricCostCostProfileDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetHistoricCostCostProfile, - _repository.UpdateHistoricCostCostProfile + repository.GetHistoricCostCostProfile, + repository.UpdateHistoricCostCostProfile ); } @@ -166,8 +147,8 @@ UpdateWellInterventionCostProfileOverrideDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetWellInterventionCostProfileOverride, - _repository.UpdateWellInterventionCostProfileOverride + repository.GetWellInterventionCostProfileOverride, + repository.UpdateWellInterventionCostProfileOverride ); } @@ -183,8 +164,8 @@ UpdateOffshoreFacilitiesOperationsCostProfileOverrideDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetOffshoreFacilitiesOperationsCostProfileOverride, - _repository.UpdateOffshoreFacilitiesOperationsCostProfileOverride + repository.GetOffshoreFacilitiesOperationsCostProfileOverride, + repository.UpdateOffshoreFacilitiesOperationsCostProfileOverride ); } @@ -200,8 +181,8 @@ UpdateOnshoreRelatedOPEXCostProfileDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetOnshoreRelatedOPEXCostProfile, - _repository.UpdateOnshoreRelatedOPEXCostProfile + repository.GetOnshoreRelatedOPEXCostProfile, + repository.UpdateOnshoreRelatedOPEXCostProfile ); } @@ -215,7 +196,7 @@ CreateOffshoreFacilitiesOperationsCostProfileOverrideDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateOffshoreFacilitiesOperationsCostProfileOverride, + repository.CreateOffshoreFacilitiesOperationsCostProfileOverride, CaseProfileNames.OffshoreFacilitiesOperationsCostProfileOverride ); } @@ -229,7 +210,7 @@ CreateCessationWellsCostOverrideDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateCessationWellsCostOverride, + repository.CreateCessationWellsCostOverride, CaseProfileNames.CessationWellsCostOverride ); } @@ -244,7 +225,7 @@ CreateCessationOffshoreFacilitiesCostOverrideDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateCessationOffshoreFacilitiesCostOverride, + repository.CreateCessationOffshoreFacilitiesCostOverride, CaseProfileNames.CessationOffshoreFacilitiesCostOverride ); } @@ -259,7 +240,7 @@ CreateCessationOnshoreFacilitiesCostProfileDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateCessationOnshoreFacilitiesCostProfile, + repository.CreateCessationOnshoreFacilitiesCostProfile, CaseProfileNames.CessationOnshoreFacilitiesCostProfile ); } @@ -274,7 +255,7 @@ CreateTotalFeasibilityAndConceptStudiesOverrideDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateTotalFeasibilityAndConceptStudiesOverride, + repository.CreateTotalFeasibilityAndConceptStudiesOverride, CaseProfileNames.TotalFeasibilityAndConceptStudiesOverride ); } @@ -289,7 +270,7 @@ CreateTotalFEEDStudiesOverrideDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateTotalFEEDStudiesOverride, + repository.CreateTotalFEEDStudiesOverride, CaseProfileNames.TotalFEEDStudiesOverride ); } @@ -304,7 +285,7 @@ CreateTotalOtherStudiesCostProfileDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateTotalOtherStudiesCostProfile, + repository.CreateTotalOtherStudiesCostProfile, CaseProfileNames.TotalOtherStudiesCostProfile ); } @@ -319,7 +300,7 @@ CreateHistoricCostCostProfileDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateHistoricCostCostProfile, + repository.CreateHistoricCostCostProfile, CaseProfileNames.HistoricCostCostProfile ); } @@ -334,7 +315,7 @@ CreateWellInterventionCostProfileOverrideDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateWellInterventionCostProfileOverride, + repository.CreateWellInterventionCostProfileOverride, CaseProfileNames.WellInterventionCostProfileOverride ); } @@ -349,7 +330,7 @@ CreateOnshoreRelatedOPEXCostProfileDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateOnshoreRelatedOPEXCostProfile, + repository.CreateOnshoreRelatedOPEXCostProfile, CaseProfileNames.OnshoreRelatedOPEXCostProfile ); } @@ -364,7 +345,7 @@ CreateAdditionalOPEXCostProfileDto createProfileDto projectId, caseId, createProfileDto, - _repository.CreateAdditionalOPEXCostProfile, + repository.CreateAdditionalOPEXCostProfile, CaseProfileNames.AdditionalOPEXCostProfile ); } @@ -381,8 +362,8 @@ UpdateAdditionalOPEXCostProfileDto updatedCostProfileDto caseId, costProfileId, updatedCostProfileDto, - _repository.GetAdditionalOPEXCostProfile, - _repository.UpdateAdditionalOPEXCostProfile + repository.GetAdditionalOPEXCostProfile, + repository.UpdateAdditionalOPEXCostProfile ); } @@ -403,24 +384,24 @@ Func updateProfile ?? throw new NotFoundInDBException($"Production profile with id {costProfileId} not found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingProfile.Case.Id); + await projectAccessService.ProjectExists(projectId, existingProfile.Case.Id); - _mapperService.MapToEntity(updatedCostProfileDto, existingProfile, caseId); + mapperService.MapToEntity(updatedCostProfileDto, existingProfile, caseId); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { var profileName = typeof(TProfile).Name; - _logger.LogError(ex, "Failed to update profile {profileName} with id {costProfileId} for case id {caseId}.", profileName, costProfileId, caseId); + logger.LogError(ex, "Failed to update profile {profileName} with id {costProfileId} for case id {caseId}.", profileName, costProfileId, caseId); throw; } - var updatedDto = _mapperService.MapToDto(existingProfile, costProfileId); + var updatedDto = mapperService.MapToDto(existingProfile, costProfileId); return updatedDto; } @@ -436,12 +417,12 @@ CaseProfileNames profileName where TCreateDto : class { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, caseId); + await projectAccessService.ProjectExists(projectId, caseId); - var caseEntity = await _caseRepository.GetCase(caseId) + var caseEntity = await caseRepository.GetCase(caseId) ?? throw new NotFoundInDBException($"Case with id {caseId} not found."); - var resourceHasProfile = await _caseRepository.CaseHasProfile(caseId, profileName); + var resourceHasProfile = await caseRepository.CaseHasProfile(caseId, profileName); if (resourceHasProfile) { @@ -453,22 +434,22 @@ CaseProfileNames profileName Case = caseEntity, }; - var newProfile = _mapperService.MapToEntity(createProfileDto, profile, caseId); + var newProfile = mapperService.MapToEntity(createProfileDto, profile, caseId); TProfile createdProfile; try { createdProfile = createProfile(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create profile {profileName} for case id {caseId}.", profileName, caseId); + logger.LogError(ex, "Failed to create profile {profileName} for case id {caseId}.", profileName, caseId); throw; } - var updatedDto = _mapperService.MapToDto(createdProfile, createdProfile.Id); + var updatedDto = mapperService.MapToDto(createdProfile, createdProfile.Id); return updatedDto; } } diff --git a/backend/api/Services/Entities/Case/CaseWithAssetsService.cs b/backend/api/Services/Entities/Case/CaseWithAssetsService.cs index 5698ccff2..b75813bff 100644 --- a/backend/api/Services/Entities/Case/CaseWithAssetsService.cs +++ b/backend/api/Services/Entities/Case/CaseWithAssetsService.cs @@ -5,41 +5,26 @@ namespace api.Services; -public class CaseWithAssetsService : ICaseWithAssetsService +public class CaseWithAssetsService( + ICaseWithAssetsRepository repository, + IProjectRepository projectRepository, + IMapperService mapperService, + IConversionMapperService conversionMapperService, + IProjectAccessService projectAccessService) + : ICaseWithAssetsService { - - private readonly ICaseWithAssetsRepository _repository; - private readonly IProjectRepository _projectRepository; - private readonly IMapperService _mapperService; - private readonly IConversionMapperService _conversionMapperService; - private readonly IProjectAccessService _projectAccessService; - public CaseWithAssetsService( - ICaseWithAssetsRepository repository, - IProjectRepository projectRepository, - IMapperService mapperService, - IConversionMapperService conversionMapperService, - IProjectAccessService projectAccessService - ) - { - _repository = repository; - _projectRepository = projectRepository; - _mapperService = mapperService; - _conversionMapperService = conversionMapperService; - _projectAccessService = projectAccessService; - } - public async Task GetCaseWithAssetsNoTracking(Guid projectId, Guid caseId) { - await _projectAccessService.ProjectExists(projectId, caseId); + await projectAccessService.ProjectExists(projectId, caseId); - var project = await _projectRepository.GetProjectByIdOrExternalId(projectId) + var project = await projectRepository.GetProjectByIdOrExternalId(projectId) ?? throw new NotFoundInDBException($"Project with id {projectId} not found"); - var (caseItem, drainageStrategy, topside, exploration, substructure, surf, transport, wellProject) = await _repository.GetCaseWithAssetsNoTracking(caseId); + var (caseItem, drainageStrategy, topside, exploration, substructure, surf, transport, wellProject) = await repository.GetCaseWithAssetsNoTracking(caseId); var caseWithAssetsDto = new CaseWithAssetsDto { - Case = _mapperService.MapToDto(caseItem, caseItem.Id), + Case = mapperService.MapToDto(caseItem, caseItem.Id), CessationWellsCost = MapToDto(caseItem.CessationWellsCost, caseItem.CessationWellsCost?.Id), CessationWellsCostOverride = MapToDto(caseItem.CessationWellsCostOverride, caseItem.CessationWellsCostOverride?.Id), CessationOffshoreFacilitiesCost = MapToDto(caseItem.CessationOffshoreFacilitiesCost, caseItem.CessationOffshoreFacilitiesCost?.Id), @@ -60,7 +45,7 @@ public async Task GetCaseWithAssetsNoTracking(Guid projectId, CalculatedTotalIncomeCostProfile = MapToDto(caseItem.CalculatedTotalIncomeCostProfile, caseItem.CalculatedTotalIncomeCostProfile?.Id), CalculatedTotalCostCostProfile = MapToDto(caseItem.CalculatedTotalCostCostProfile, caseItem.CalculatedTotalCostCostProfile?.Id), - DrainageStrategy = _conversionMapperService.MapToDto(drainageStrategy, drainageStrategy.Id, project.PhysicalUnit), + DrainageStrategy = conversionMapperService.MapToDto(drainageStrategy, drainageStrategy.Id, project.PhysicalUnit), ProductionProfileOil = ConversionMapToDto(drainageStrategy?.ProductionProfileOil, drainageStrategy?.ProductionProfileOil?.Id, project.PhysicalUnit), AdditionalProductionProfileOil = ConversionMapToDto(drainageStrategy?.AdditionalProductionProfileOil, drainageStrategy?.AdditionalProductionProfileOil?.Id, project.PhysicalUnit), ProductionProfileGas = ConversionMapToDto(drainageStrategy?.ProductionProfileGas, drainageStrategy?.ProductionProfileGas?.Id, project.PhysicalUnit), @@ -80,28 +65,28 @@ public async Task GetCaseWithAssetsNoTracking(Guid projectId, DeferredOilProduction = ConversionMapToDto(drainageStrategy?.DeferredOilProduction, drainageStrategy?.DeferredOilProduction?.Id, project.PhysicalUnit), DeferredGasProduction = ConversionMapToDto(drainageStrategy?.DeferredGasProduction, drainageStrategy?.DeferredGasProduction?.Id, project.PhysicalUnit), - Topside = _mapperService.MapToDto(topside, topside.Id), + Topside = mapperService.MapToDto(topside, topside.Id), TopsideCostProfile = MapToDto(topside.CostProfile, topside.CostProfile?.Id), TopsideCostProfileOverride = MapToDto(topside.CostProfileOverride, topside.CostProfileOverride?.Id), TopsideCessationCostProfile = MapToDto(topside.CessationCostProfile, topside.CessationCostProfile?.Id), - Substructure = _mapperService.MapToDto(substructure, substructure.Id), + Substructure = mapperService.MapToDto(substructure, substructure.Id), SubstructureCostProfile = MapToDto(substructure.CostProfile, substructure.CostProfile?.Id), SubstructureCostProfileOverride = MapToDto(substructure.CostProfileOverride, substructure.CostProfileOverride?.Id), SubstructureCessationCostProfile = MapToDto(substructure.CessationCostProfile, substructure.CessationCostProfile?.Id), - Surf = _mapperService.MapToDto(surf, surf.Id), + Surf = mapperService.MapToDto(surf, surf.Id), SurfCostProfile = MapToDto(surf.CostProfile, surf.CostProfile?.Id), SurfCostProfileOverride = MapToDto(surf.CostProfileOverride, surf.CostProfileOverride?.Id), SurfCessationCostProfile = MapToDto(surf.CessationCostProfile, surf.CessationCostProfile?.Id), - Transport = _mapperService.MapToDto(transport, transport.Id), + Transport = mapperService.MapToDto(transport, transport.Id), TransportCostProfile = MapToDto(transport.CostProfile, transport.CostProfile?.Id), TransportCostProfileOverride = MapToDto(transport.CostProfileOverride, transport.CostProfileOverride?.Id), TransportCessationCostProfile = MapToDto(transport.CessationCostProfile, transport.CessationCostProfile?.Id), - Exploration = _mapperService.MapToDto(exploration, exploration.Id), - ExplorationWells = exploration.ExplorationWells?.Select(w => _mapperService.MapToDto(w, w.ExplorationId)).ToList() ?? new List(), + Exploration = mapperService.MapToDto(exploration, exploration.Id), + ExplorationWells = exploration.ExplorationWells?.Select(w => mapperService.MapToDto(w, w.ExplorationId)).ToList() ?? new List(), ExplorationWellCostProfile = MapToDto(exploration.ExplorationWellCostProfile, exploration.ExplorationWellCostProfile?.Id), AppraisalWellCostProfile = MapToDto(exploration.AppraisalWellCostProfile, exploration.AppraisalWellCostProfile?.Id), SidetrackCostProfile = MapToDto(exploration.SidetrackCostProfile, exploration.SidetrackCostProfile?.Id), @@ -110,8 +95,8 @@ public async Task GetCaseWithAssetsNoTracking(Guid projectId, SeismicAcquisitionAndProcessing = MapToDto(exploration.SeismicAcquisitionAndProcessing, exploration.SeismicAcquisitionAndProcessing?.Id), CountryOfficeCost = MapToDto(exploration.CountryOfficeCost, exploration.CountryOfficeCost?.Id), - WellProject = _mapperService.MapToDto(wellProject, wellProject.Id), - WellProjectWells = wellProject.WellProjectWells?.Select(w => _mapperService.MapToDto(w, w.WellProjectId)).ToList() ?? new List(), + WellProject = mapperService.MapToDto(wellProject, wellProject.Id), + WellProjectWells = wellProject.WellProjectWells?.Select(w => mapperService.MapToDto(w, w.WellProjectId)).ToList() ?? new List(), OilProducerCostProfile = MapToDto(wellProject.OilProducerCostProfile, wellProject.OilProducerCostProfile?.Id), OilProducerCostProfileOverride = MapToDto(wellProject.OilProducerCostProfileOverride, wellProject.OilProducerCostProfileOverride?.Id), GasProducerCostProfile = MapToDto(wellProject.GasProducerCostProfile, wellProject.GasProducerCostProfile?.Id), @@ -131,7 +116,7 @@ public async Task GetCaseWithAssetsNoTracking(Guid projectId, { return null; } - return _mapperService.MapToDto(source, (Guid)id); + return mapperService.MapToDto(source, (Guid)id); } private TDto? ConversionMapToDto(T? source, Guid? id, PhysUnit physUnit) where T : class where TDto : class @@ -140,6 +125,6 @@ public async Task GetCaseWithAssetsNoTracking(Guid projectId, { return null; } - return _conversionMapperService.MapToDto(source, (Guid)id, physUnit); + return conversionMapperService.MapToDto(source, (Guid)id, physUnit); } } diff --git a/backend/api/Services/Entities/Case/CreateCaseService.cs b/backend/api/Services/Entities/Case/CreateCaseService.cs index 70c27e595..c4b2e3a85 100644 --- a/backend/api/Services/Entities/Case/CreateCaseService.cs +++ b/backend/api/Services/Entities/Case/CreateCaseService.cs @@ -1,34 +1,21 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; namespace api.Services; -public class CreateCaseService : ICreateCaseService +public class CreateCaseService( + ICaseRepository caseRepository, + IProjectService projectService, + IMapperService mapperService) + : ICreateCaseService { - private readonly ICaseRepository _caseRepository; - private readonly IProjectService _projectService; - private readonly IMapperService _mapperService; - - public CreateCaseService( - DcdDbContext context, - ICaseRepository caseRepository, - IProjectService projectService, - IMapperService mapperService - ) - { - _caseRepository = caseRepository; - _projectService = projectService; - _mapperService = mapperService; - } - public async Task CreateCase(Guid projectId, CreateCaseDto createCaseDto) { var caseItem = new Case(); - _mapperService.MapToEntity(createCaseDto, caseItem, Guid.Empty); + mapperService.MapToEntity(createCaseDto, caseItem, Guid.Empty); - var project = await _projectService.GetProject(projectId); + var project = await projectService.GetProject(projectId); caseItem.Project = project; caseItem.CapexFactorFeasibilityStudies = 0.015; caseItem.CapexFactorFEEDStudies = 0.015; @@ -48,9 +35,9 @@ public async Task CreateCase(Guid projectId, CreateCaseDto caseItem.Exploration = CreateExploration(project); caseItem.WellProject = CreateWellProject(project); - await _caseRepository.AddCase(caseItem); + await caseRepository.AddCase(caseItem); - return await _projectService.GetProjectDto(project.Id); + return await projectService.GetProjectDto(project.Id); } private static DrainageStrategy CreateDrainageStrategy(Project project) diff --git a/backend/api/Services/Entities/Case/ICaseTimeSeriesService.cs b/backend/api/Services/Entities/Case/ICaseTimeSeriesService.cs index 077228320..f4abab491 100644 --- a/backend/api/Services/Entities/Case/ICaseTimeSeriesService.cs +++ b/backend/api/Services/Entities/Case/ICaseTimeSeriesService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/Case/ICaseWithAssetsService.cs b/backend/api/Services/Entities/Case/ICaseWithAssetsService.cs index 4b64829f0..71bc27727 100644 --- a/backend/api/Services/Entities/Case/ICaseWithAssetsService.cs +++ b/backend/api/Services/Entities/Case/ICaseWithAssetsService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/Case/ICreateCaseService.cs b/backend/api/Services/Entities/Case/ICreateCaseService.cs index 0bf192031..c9ed89be8 100644 --- a/backend/api/Services/Entities/Case/ICreateCaseService.cs +++ b/backend/api/Services/Entities/Case/ICreateCaseService.cs @@ -1,7 +1,4 @@ -using System.Linq.Expressions; - using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/DevelopmentOperationalWellCostsService.cs b/backend/api/Services/Entities/DevelopmentOperationalWellCostsService.cs index 3ce0bdb0c..5e6587af7 100644 --- a/backend/api/Services/Entities/DevelopmentOperationalWellCostsService.cs +++ b/backend/api/Services/Entities/DevelopmentOperationalWellCostsService.cs @@ -1,27 +1,15 @@ -using api.Adapters; using api.Context; -using api.Dtos; using api.Models; using Microsoft.EntityFrameworkCore; namespace api.Services; -public class DevelopmentOperationalWellCostsService : IDevelopmentOperationalWellCostsService +public class DevelopmentOperationalWellCostsService(DcdDbContext context) : IDevelopmentOperationalWellCostsService { - private readonly DcdDbContext _context; - private readonly IProjectService _projectService; - private readonly ILogger _logger; - public DevelopmentOperationalWellCostsService(DcdDbContext context, IProjectService projectService, ILoggerFactory loggerFactory) - { - _context = context; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - } - public async Task GetOperationalWellCosts(Guid id) { - var operationalWellCosts = await _context.DevelopmentOperationalWellCosts! + var operationalWellCosts = await context.DevelopmentOperationalWellCosts! .Include(dowc => dowc.Project) .FirstOrDefaultAsync(o => o.Id == id); return operationalWellCosts; diff --git a/backend/api/Services/Entities/DrainageStrategy/DrainageStrategyService.cs b/backend/api/Services/Entities/DrainageStrategy/DrainageStrategyService.cs index 23abdc37f..2ec5ea183 100644 --- a/backend/api/Services/Entities/DrainageStrategy/DrainageStrategyService.cs +++ b/backend/api/Services/Entities/DrainageStrategy/DrainageStrategyService.cs @@ -1,50 +1,30 @@ using System.Linq.Expressions; -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class DrainageStrategyService : IDrainageStrategyService +public class DrainageStrategyService( + ILogger logger, + ICaseRepository caseRepository, + IDrainageStrategyRepository repository, + IConversionMapperService conversionMapperService, + IProjectRepository projectRepository, + IProjectAccessService projectAccessService) + : IDrainageStrategyService { - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly ICaseRepository _caseRepository; - private readonly IDrainageStrategyRepository _repository; - private readonly IConversionMapperService _conversionMapperService; - private readonly IProjectRepository _projectRepository; - - public DrainageStrategyService( - ILoggerFactory loggerFactory, - ICaseRepository caseRepository, - IDrainageStrategyRepository repository, - IConversionMapperService conversionMapperService, - IProjectRepository projectRepository, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _caseRepository = caseRepository; - _repository = repository; - _conversionMapperService = conversionMapperService; - _projectRepository = projectRepository; - _projectAccessService = projectAccessService; - } - public async Task GetDrainageStrategyWithIncludes( Guid drainageStrategyId, params Expression>[] includes ) { - return await _repository.GetDrainageStrategyWithIncludes(drainageStrategyId, includes) + return await repository.GetDrainageStrategyWithIncludes(drainageStrategyId, includes) ?? throw new NotFoundInDBException($"Drainage strategy with id {drainageStrategyId} not found."); } @@ -56,28 +36,28 @@ UpdateDrainageStrategyDto updatedDrainageStrategyDto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, drainageStrategyId); + await projectAccessService.ProjectExists(projectId, drainageStrategyId); - var existingDrainageStrategy = await _repository.GetDrainageStrategy(drainageStrategyId) + var existingDrainageStrategy = await repository.GetDrainageStrategy(drainageStrategyId) ?? throw new NotFoundInDBException($"Drainage strategy with id {drainageStrategyId} not found."); - var project = await _projectRepository.GetProject(projectId) + var project = await projectRepository.GetProject(projectId) ?? throw new NotFoundInDBException($"Project with id {projectId} not found."); - _conversionMapperService.MapToEntity(updatedDrainageStrategyDto, existingDrainageStrategy, drainageStrategyId, project.PhysicalUnit); + conversionMapperService.MapToEntity(updatedDrainageStrategyDto, existingDrainageStrategy, drainageStrategyId, project.PhysicalUnit); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update drainage strategy with id {drainageStrategyId} for case id {caseId}.", drainageStrategyId, caseId); + logger.LogError(ex, "Failed to update drainage strategy with id {drainageStrategyId} for case id {caseId}.", drainageStrategyId, caseId); throw; } - var dto = _conversionMapperService.MapToDto(existingDrainageStrategy, drainageStrategyId, project.PhysicalUnit); + var dto = conversionMapperService.MapToDto(existingDrainageStrategy, drainageStrategyId, project.PhysicalUnit); return dto; } } diff --git a/backend/api/Services/Entities/DrainageStrategy/DrainageStrategyTimeSeriesService.cs b/backend/api/Services/Entities/DrainageStrategy/DrainageStrategyTimeSeriesService.cs index 09c246e7a..419e6aa46 100644 --- a/backend/api/Services/Entities/DrainageStrategy/DrainageStrategyTimeSeriesService.cs +++ b/backend/api/Services/Entities/DrainageStrategy/DrainageStrategyTimeSeriesService.cs @@ -10,35 +10,16 @@ namespace api.Services; -public class DrainageStrategyTimeSeriesService : IDrainageStrategyTimeSeriesService +public class DrainageStrategyTimeSeriesService( + ILogger logger, + ICaseRepository caseRepository, + IDrainageStrategyTimeSeriesRepository repository, + IDrainageStrategyRepository drainageStrategyTimeSeriesRepository, + IConversionMapperService conversionMapperService, + IProjectRepository projectRepository, + IProjectAccessService projectAccessService) + : IDrainageStrategyTimeSeriesService { - private readonly ILogger _logger; - private readonly ICaseRepository _caseRepository; - private readonly IDrainageStrategyTimeSeriesRepository _repository; - private readonly IDrainageStrategyRepository _drainageStrategyRepository; - private readonly IConversionMapperService _conversionMapperService; - private readonly IProjectRepository _projectRepository; - private readonly IProjectAccessService _projectAccessService; - - public DrainageStrategyTimeSeriesService( - ILoggerFactory loggerFactory, - ICaseRepository caseRepository, - IDrainageStrategyTimeSeriesRepository repository, - IDrainageStrategyRepository drainageStrategyTimeSeriesRepository, - IConversionMapperService conversionMapperService, - IProjectRepository projectRepository, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _caseRepository = caseRepository; - _repository = repository; - _drainageStrategyRepository = drainageStrategyTimeSeriesRepository; - _conversionMapperService = conversionMapperService; - _projectRepository = projectRepository; - _projectAccessService = projectAccessService; - } - public async Task CreateProductionProfileOil( Guid projectId, Guid caseId, @@ -51,7 +32,7 @@ CreateProductionProfileOilDto createProductionProfileOilDto caseId, drainageStrategyId, createProductionProfileOilDto, - _repository.CreateProductionProfileOil, + repository.CreateProductionProfileOil, DrainageStrategyProfileNames.ProductionProfileOil ); } @@ -70,8 +51,8 @@ UpdateProductionProfileOilDto updatedProductionProfileOilDto drainageStrategyId, productionProfileOilId, updatedProductionProfileOilDto, - _repository.GetProductionProfileOil, - _repository.UpdateProductionProfileOil + repository.GetProductionProfileOil, + repository.UpdateProductionProfileOil ); } @@ -87,7 +68,7 @@ CreateAdditionalProductionProfileOilDto createAdditionalProductionProfileOilDto caseId, drainageStrategyId, createAdditionalProductionProfileOilDto, - _repository.CreateAdditionalProductionProfileOil, + repository.CreateAdditionalProductionProfileOil, DrainageStrategyProfileNames.AdditionalProductionProfileOil ); } @@ -106,8 +87,8 @@ UpdateAdditionalProductionProfileOilDto updatedAdditionalProductionProfileOilDto drainageStrategyId, additionalproductionProfileOilId, updatedAdditionalProductionProfileOilDto, - _repository.GetAdditionalProductionProfileOil, - _repository.UpdateAdditionalProductionProfileOil + repository.GetAdditionalProductionProfileOil, + repository.UpdateAdditionalProductionProfileOil ); } @@ -123,7 +104,7 @@ CreateProductionProfileGasDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateProductionProfileGas, + repository.CreateProductionProfileGas, DrainageStrategyProfileNames.ProductionProfileGas ); } @@ -142,8 +123,8 @@ UpdateProductionProfileGasDto updatedProductionProfileGasDto drainageStrategyId, productionProfileId, updatedProductionProfileGasDto, - _repository.GetProductionProfileGas, - _repository.UpdateProductionProfileGas + repository.GetProductionProfileGas, + repository.UpdateProductionProfileGas ); } @@ -159,7 +140,7 @@ CreateAdditionalProductionProfileGasDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateAdditionalProductionProfileGas, + repository.CreateAdditionalProductionProfileGas, DrainageStrategyProfileNames.AdditionalProductionProfileGas ); } @@ -178,8 +159,8 @@ UpdateAdditionalProductionProfileGasDto updatedAdditionalProductionProfileGasDto drainageStrategyId, productionProfileId, updatedAdditionalProductionProfileGasDto, - _repository.GetAdditionalProductionProfileGas, - _repository.UpdateAdditionalProductionProfileGas + repository.GetAdditionalProductionProfileGas, + repository.UpdateAdditionalProductionProfileGas ); } @@ -195,7 +176,7 @@ CreateProductionProfileWaterDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateProductionProfileWater, + repository.CreateProductionProfileWater, DrainageStrategyProfileNames.ProductionProfileWater ); } @@ -214,8 +195,8 @@ UpdateProductionProfileWaterDto updatedProductionProfileWaterDto drainageStrategyId, productionProfileId, updatedProductionProfileWaterDto, - _repository.GetProductionProfileWater, - _repository.UpdateProductionProfileWater + repository.GetProductionProfileWater, + repository.UpdateProductionProfileWater ); } @@ -231,7 +212,7 @@ CreateProductionProfileWaterInjectionDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateProductionProfileWaterInjection, + repository.CreateProductionProfileWaterInjection, DrainageStrategyProfileNames.ProductionProfileWaterInjection ); } @@ -250,8 +231,8 @@ UpdateProductionProfileWaterInjectionDto updatedProductionProfileWaterInjectionD drainageStrategyId, productionProfileId, updatedProductionProfileWaterInjectionDto, - _repository.GetProductionProfileWaterInjection, - _repository.UpdateProductionProfileWaterInjection + repository.GetProductionProfileWaterInjection, + repository.UpdateProductionProfileWaterInjection ); } @@ -267,7 +248,7 @@ CreateFuelFlaringAndLossesOverrideDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateFuelFlaringAndLossesOverride, + repository.CreateFuelFlaringAndLossesOverride, DrainageStrategyProfileNames.FuelFlaringAndLossesOverride ); } @@ -286,8 +267,8 @@ UpdateFuelFlaringAndLossesOverrideDto updateDto drainageStrategyId, profileId, updateDto, - _repository.GetFuelFlaringAndLossesOverride, - _repository.UpdateFuelFlaringAndLossesOverride + repository.GetFuelFlaringAndLossesOverride, + repository.UpdateFuelFlaringAndLossesOverride ); } @@ -303,7 +284,7 @@ CreateNetSalesGasOverrideDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateNetSalesGasOverride, + repository.CreateNetSalesGasOverride, DrainageStrategyProfileNames.NetSalesGasOverride ); } @@ -322,8 +303,8 @@ UpdateNetSalesGasOverrideDto updateDto drainageStrategyId, profileId, updateDto, - _repository.GetNetSalesGasOverride, - _repository.UpdateNetSalesGasOverride + repository.GetNetSalesGasOverride, + repository.UpdateNetSalesGasOverride ); } @@ -339,7 +320,7 @@ CreateCo2EmissionsOverrideDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateCo2EmissionsOverride, + repository.CreateCo2EmissionsOverride, DrainageStrategyProfileNames.Co2EmissionsOverride ); } @@ -358,8 +339,8 @@ UpdateCo2EmissionsOverrideDto updateDto drainageStrategyId, profileId, updateDto, - _repository.GetCo2EmissionsOverride, - _repository.UpdateCo2EmissionsOverride + repository.GetCo2EmissionsOverride, + repository.UpdateCo2EmissionsOverride ); } @@ -375,7 +356,7 @@ CreateImportedElectricityOverrideDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateImportedElectricityOverride, + repository.CreateImportedElectricityOverride, DrainageStrategyProfileNames.ImportedElectricityOverride ); } @@ -394,8 +375,8 @@ UpdateImportedElectricityOverrideDto updateDto drainageStrategyId, profileId, updateDto, - _repository.GetImportedElectricityOverride, - _repository.UpdateImportedElectricityOverride + repository.GetImportedElectricityOverride, + repository.UpdateImportedElectricityOverride ); } @@ -411,7 +392,7 @@ CreateDeferredOilProductionDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateDeferredOilProduction, + repository.CreateDeferredOilProduction, DrainageStrategyProfileNames.DeferredOilProduction ); } @@ -430,8 +411,8 @@ UpdateDeferredOilProductionDto updatedDeferredOilProductionDto drainageStrategyId, productionProfileId, updatedDeferredOilProductionDto, - _repository.GetDeferredOilProduction, - _repository.UpdateDeferredOilProduction + repository.GetDeferredOilProduction, + repository.UpdateDeferredOilProduction ); } @@ -447,7 +428,7 @@ CreateDeferredGasProductionDto createProfileDto caseId, drainageStrategyId, createProfileDto, - _repository.CreateDeferredGasProduction, + repository.CreateDeferredGasProduction, DrainageStrategyProfileNames.DeferredGasProduction ); } @@ -466,8 +447,8 @@ UpdateDeferredGasProductionDto updatedDeferredGasProductionDto drainageStrategyId, productionProfileId, updatedDeferredGasProductionDto, - _repository.GetDeferredGasProduction, - _repository.UpdateDeferredGasProduction + repository.GetDeferredGasProduction, + repository.UpdateDeferredGasProduction ); } @@ -488,28 +469,28 @@ Func updateProfile ?? throw new NotFoundInDBException($"Production profile with id {productionProfileId} not found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingProfile.DrainageStrategy.Id); + await projectAccessService.ProjectExists(projectId, existingProfile.DrainageStrategy.Id); - var project = await _projectRepository.GetProject(projectId) + var project = await projectRepository.GetProject(projectId) ?? throw new NotFoundInDBException($"Project with id {projectId} not found."); - _conversionMapperService.MapToEntity(updatedProductionProfileDto, existingProfile, drainageStrategyId, project.PhysicalUnit); + conversionMapperService.MapToEntity(updatedProductionProfileDto, existingProfile, drainageStrategyId, project.PhysicalUnit); // TProfile updatedProfile; try { // updatedProfile = updateProfile(existingProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { var profileName = typeof(TProfile).Name; - _logger.LogError(ex, "Failed to update profile {profileName} with id {productionProfileId} for case id {caseId}.", profileName, productionProfileId, caseId); + logger.LogError(ex, "Failed to update profile {profileName} with id {productionProfileId} for case id {caseId}.", profileName, productionProfileId, caseId); throw; } - var updatedDto = _conversionMapperService.MapToDto(existingProfile, productionProfileId, project.PhysicalUnit); + var updatedDto = conversionMapperService.MapToDto(existingProfile, productionProfileId, project.PhysicalUnit); return updatedDto; } @@ -526,19 +507,19 @@ DrainageStrategyProfileNames profileName where TCreateDto : class { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, drainageStrategyId); + await projectAccessService.ProjectExists(projectId, drainageStrategyId); - var drainageStrategy = await _drainageStrategyRepository.GetDrainageStrategy(drainageStrategyId) + var drainageStrategy = await drainageStrategyTimeSeriesRepository.GetDrainageStrategy(drainageStrategyId) ?? throw new NotFoundInDBException($"Drainage strategy with id {drainageStrategyId} not found."); - var resourceHasProfile = await _drainageStrategyRepository.DrainageStrategyHasProfile(drainageStrategyId, profileName); + var resourceHasProfile = await drainageStrategyTimeSeriesRepository.DrainageStrategyHasProfile(drainageStrategyId, profileName); if (resourceHasProfile) { throw new ResourceAlreadyExistsException($"Drainage strategy with id {drainageStrategyId} already has a profile of type {typeof(TProfile).Name}."); } - var project = await _projectRepository.GetProject(projectId) + var project = await projectRepository.GetProject(projectId) ?? throw new NotFoundInDBException($"Project with id {projectId} not found."); TProfile profile = new() @@ -546,22 +527,22 @@ DrainageStrategyProfileNames profileName DrainageStrategy = drainageStrategy, }; - var newProfile = _conversionMapperService.MapToEntity(createProductionProfileDto, profile, drainageStrategyId, project.PhysicalUnit); + var newProfile = conversionMapperService.MapToEntity(createProductionProfileDto, profile, drainageStrategyId, project.PhysicalUnit); TProfile createdProfile; try { createdProfile = createProfile(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create profile {profileName} for case id {caseId}.", profileName, caseId); + logger.LogError(ex, "Failed to create profile {profileName} for case id {caseId}.", profileName, caseId); throw; } - var updatedDto = _conversionMapperService.MapToDto(createdProfile, createdProfile.Id, project.PhysicalUnit); + var updatedDto = conversionMapperService.MapToDto(createdProfile, createdProfile.Id, project.PhysicalUnit); return updatedDto; } } diff --git a/backend/api/Services/Entities/DrainageStrategy/IDrainageStrategyTimeSeriesService.cs b/backend/api/Services/Entities/DrainageStrategy/IDrainageStrategyTimeSeriesService.cs index 7f339e8ba..62fb12dee 100644 --- a/backend/api/Services/Entities/DrainageStrategy/IDrainageStrategyTimeSeriesService.cs +++ b/backend/api/Services/Entities/DrainageStrategy/IDrainageStrategyTimeSeriesService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/Exploration/ExplorationService.cs b/backend/api/Services/Entities/Exploration/ExplorationService.cs index c598bc4f7..40de483c2 100644 --- a/backend/api/Services/Entities/Exploration/ExplorationService.cs +++ b/backend/api/Services/Entities/Exploration/ExplorationService.cs @@ -10,32 +10,17 @@ namespace api.Services; -public class ExplorationService : IExplorationService +public class ExplorationService( + ILogger logger, + ICaseRepository caseRepository, + IExplorationRepository repository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : IExplorationService { - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly ICaseRepository _caseRepository; - private readonly IExplorationRepository _repository; - private readonly IMapperService _mapperService; - - public ExplorationService( - ILoggerFactory loggerFactory, - ICaseRepository caseRepository, - IExplorationRepository repository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _caseRepository = caseRepository; - _repository = repository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task GetExplorationWithIncludes(Guid explorationId, params Expression>[] includes) { - return await _repository.GetExplorationWithIncludes(explorationId, includes) + return await repository.GetExplorationWithIncludes(explorationId, includes) ?? throw new NotFoundInDBException($"Exploration with id {explorationId} not found."); } @@ -47,25 +32,25 @@ UpdateExplorationDto updatedExplorationDto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, explorationId); + await projectAccessService.ProjectExists(projectId, explorationId); - var existingExploration = await _repository.GetExploration(explorationId) + var existingExploration = await repository.GetExploration(explorationId) ?? throw new NotFoundInDBException($"Exploration with id {explorationId} not found."); - _mapperService.MapToEntity(updatedExplorationDto, existingExploration, explorationId); + mapperService.MapToEntity(updatedExplorationDto, existingExploration, explorationId); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update exploration with id {explorationId} for case id {caseId}.", explorationId, caseId); + logger.LogError(ex, "Failed to update exploration with id {explorationId} for case id {caseId}.", explorationId, caseId); throw; } - var dto = _mapperService.MapToDto(existingExploration, explorationId); + var dto = mapperService.MapToDto(existingExploration, explorationId); return dto; } @@ -78,29 +63,29 @@ public async Task UpdateExplorationWellDrillingSchedule( UpdateDrillingScheduleDto updatedExplorationWellDto ) { - var existingExploration = await _repository.GetExplorationWithDrillingSchedule(drillingScheduleId) + var existingExploration = await repository.GetExplorationWithDrillingSchedule(drillingScheduleId) ?? throw new NotFoundInDBException($"No exploration connected to {drillingScheduleId} found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingExploration.Id); + await projectAccessService.ProjectExists(projectId, existingExploration.Id); var existingDrillingSchedule = existingExploration.ExplorationWells?.FirstOrDefault(w => w.WellId == wellId)?.DrillingSchedule ?? throw new NotFoundInDBException($"Drilling schedule with id {drillingScheduleId} not found."); - _mapperService.MapToEntity(updatedExplorationWellDto, existingDrillingSchedule, drillingScheduleId); + mapperService.MapToEntity(updatedExplorationWellDto, existingDrillingSchedule, drillingScheduleId); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update drilling schedule with id {drillingScheduleId}", drillingScheduleId); + logger.LogError(ex, "Failed to update drilling schedule with id {drillingScheduleId}", drillingScheduleId); throw; } - var dto = _mapperService.MapToDto(existingDrillingSchedule, drillingScheduleId); + var dto = mapperService.MapToDto(existingDrillingSchedule, drillingScheduleId); return dto; } @@ -113,16 +98,16 @@ CreateDrillingScheduleDto updatedExplorationWellDto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, explorationId); + await projectAccessService.ProjectExists(projectId, explorationId); - var existingExploration = await _repository.GetExploration(explorationId) + var existingExploration = await repository.GetExploration(explorationId) ?? throw new NotFoundInDBException($"Well project with {explorationId} not found."); - var existingWell = await _repository.GetWell(wellId) + var existingWell = await repository.GetWell(wellId) ?? throw new NotFoundInDBException($"Well with {wellId} not found."); DrillingSchedule drillingSchedule = new(); - var newDrillingSchedule = _mapperService.MapToEntity(updatedExplorationWellDto, drillingSchedule, explorationId); + var newDrillingSchedule = mapperService.MapToEntity(updatedExplorationWellDto, drillingSchedule, explorationId); ExplorationWell newExplorationWell = new() { @@ -134,13 +119,13 @@ CreateDrillingScheduleDto updatedExplorationWellDto ExplorationWell createdExplorationWell; try { - createdExplorationWell = _repository.CreateExplorationWellDrillingSchedule(newExplorationWell); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + createdExplorationWell = repository.CreateExplorationWellDrillingSchedule(newExplorationWell); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update drilling schedule with id {drillingScheduleId}", explorationId); + logger.LogError(ex, "Failed to update drilling schedule with id {drillingScheduleId}", explorationId); throw; } @@ -150,7 +135,7 @@ CreateDrillingScheduleDto updatedExplorationWellDto throw new Exception(nameof(createdExplorationWell.DrillingSchedule)); } - var dto = _mapperService.MapToDto(createdExplorationWell.DrillingSchedule, explorationId); + var dto = mapperService.MapToDto(createdExplorationWell.DrillingSchedule, explorationId); return dto; } } diff --git a/backend/api/Services/Entities/Exploration/ExplorationTimeSeriesService.cs b/backend/api/Services/Entities/Exploration/ExplorationTimeSeriesService.cs index 5da378abe..f8192519e 100644 --- a/backend/api/Services/Entities/Exploration/ExplorationTimeSeriesService.cs +++ b/backend/api/Services/Entities/Exploration/ExplorationTimeSeriesService.cs @@ -1,50 +1,22 @@ -using api.Context; using api.Dtos; using api.Enums; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class ExplorationTimeSeriesService : IExplorationTimeSeriesService +public class ExplorationTimeSeriesService( + ILogger logger, + ICaseRepository caseRepository, + IExplorationTimeSeriesRepository repository, + IExplorationRepository explorationRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : IExplorationTimeSeriesService { - private readonly DcdDbContext _context; - private readonly IProjectService _projectService; - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly IMapper _mapper; - private readonly ICaseRepository _caseRepository; - private readonly IExplorationTimeSeriesRepository _repository; - private readonly IExplorationRepository _explorationRepository; - private readonly IMapperService _mapperService; - - public ExplorationTimeSeriesService( - DcdDbContext context, - IProjectService projectService, - ILoggerFactory loggerFactory, - IMapper mapper, - ICaseRepository caseRepository, - IExplorationTimeSeriesRepository repository, - IExplorationRepository explorationRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _context = context; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - _mapper = mapper; - _caseRepository = caseRepository; - _repository = repository; - _explorationRepository = explorationRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } public async Task CreateGAndGAdminCostOverride( Guid projectId, Guid caseId, @@ -57,7 +29,7 @@ CreateGAndGAdminCostOverrideDto createProfileDto caseId, explorationId, createProfileDto, - _repository.CreateGAndGAdminCostOverride, + repository.CreateGAndGAdminCostOverride, ExplorationProfileNames.GAndGAdminCostOverride ); } @@ -75,8 +47,8 @@ UpdateGAndGAdminCostOverrideDto updateDto wellProjectId, profileId, updateDto, - _repository.GetGAndGAdminCostOverride, - _repository.UpdateGAndGAdminCostOverride + repository.GetGAndGAdminCostOverride, + repository.UpdateGAndGAdminCostOverride ); } public async Task UpdateSeismicAcquisitionAndProcessing( @@ -93,8 +65,8 @@ UpdateSeismicAcquisitionAndProcessingDto updateDto wellProjectId, profileId, updateDto, - _repository.GetSeismicAcquisitionAndProcessing, - _repository.UpdateSeismicAcquisitionAndProcessing + repository.GetSeismicAcquisitionAndProcessing, + repository.UpdateSeismicAcquisitionAndProcessing ); } @@ -112,8 +84,8 @@ UpdateCountryOfficeCostDto updateDto wellProjectId, profileId, updateDto, - _repository.GetCountryOfficeCost, - _repository.UpdateCountryOfficeCost + repository.GetCountryOfficeCost, + repository.UpdateCountryOfficeCost ); } @@ -129,7 +101,7 @@ CreateSeismicAcquisitionAndProcessingDto createProfileDto caseId, explorationId, createProfileDto, - _repository.CreateSeismicAcquisitionAndProcessing, + repository.CreateSeismicAcquisitionAndProcessing, ExplorationProfileNames.SeismicAcquisitionAndProcessing ); } @@ -146,7 +118,7 @@ CreateCountryOfficeCostDto createProfileDto caseId, explorationId, createProfileDto, - _repository.CreateCountryOfficeCost, + repository.CreateCountryOfficeCost, ExplorationProfileNames.CountryOfficeCost ); } @@ -168,25 +140,25 @@ Func updateProfile ?? throw new NotFoundInDBException($"Cost profile with id {profileId} not found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingProfile.Exploration.Id); + await projectAccessService.ProjectExists(projectId, existingProfile.Exploration.Id); - _mapperService.MapToEntity(updatedProfileDto, existingProfile, explorationId); + mapperService.MapToEntity(updatedProfileDto, existingProfile, explorationId); TProfile updatedProfile; try { updatedProfile = updateProfile(existingProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { var profileName = typeof(TProfile).Name; - _logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); + logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); throw; } - var updatedDto = _mapperService.MapToDto(updatedProfile, profileId); + var updatedDto = mapperService.MapToDto(updatedProfile, profileId); return updatedDto; } @@ -203,12 +175,12 @@ ExplorationProfileNames profileName where TCreateDto : class { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, explorationId); + await projectAccessService.ProjectExists(projectId, explorationId); - var exploration = await _explorationRepository.GetExploration(explorationId) + var exploration = await explorationRepository.GetExploration(explorationId) ?? throw new NotFoundInDBException($"Exploration with id {explorationId} not found."); - var resourceHasProfile = await _explorationRepository.ExplorationHasProfile(explorationId, profileName); + var resourceHasProfile = await explorationRepository.ExplorationHasProfile(explorationId, profileName); if (resourceHasProfile) { @@ -220,22 +192,22 @@ ExplorationProfileNames profileName Exploration = exploration, }; - var newProfile = _mapperService.MapToEntity(createExplorationProfileDto, profile, explorationId); + var newProfile = mapperService.MapToEntity(createExplorationProfileDto, profile, explorationId); TProfile createdProfile; try { createdProfile = createProfile(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create profile {profileName} for case id {caseId}.", profileName, caseId); + logger.LogError(ex, "Failed to create profile {profileName} for case id {caseId}.", profileName, caseId); throw; } - var updatedDto = _mapperService.MapToDto(createdProfile, createdProfile.Id); + var updatedDto = mapperService.MapToDto(createdProfile, createdProfile.Id); return updatedDto; } } diff --git a/backend/api/Services/Entities/Exploration/IExplorationTimeSeriesService.cs b/backend/api/Services/Entities/Exploration/IExplorationTimeSeriesService.cs index 00cf26380..f2aef6c0e 100644 --- a/backend/api/Services/Entities/Exploration/IExplorationTimeSeriesService.cs +++ b/backend/api/Services/Entities/Exploration/IExplorationTimeSeriesService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/ExplorationOperationalWellCostsService.cs b/backend/api/Services/Entities/ExplorationOperationalWellCostsService.cs index 8013b2af7..bd0764cce 100644 --- a/backend/api/Services/Entities/ExplorationOperationalWellCostsService.cs +++ b/backend/api/Services/Entities/ExplorationOperationalWellCostsService.cs @@ -1,27 +1,15 @@ -using api.Adapters; using api.Context; -using api.Dtos; using api.Models; using Microsoft.EntityFrameworkCore; namespace api.Services; -public class ExplorationOperationalWellCostsService : IExplorationOperationalWellCostsService +public class ExplorationOperationalWellCostsService(DcdDbContext context) : IExplorationOperationalWellCostsService { - private readonly DcdDbContext _context; - private readonly IProjectService _projectService; - private readonly ILogger _logger; - public ExplorationOperationalWellCostsService(DcdDbContext context, IProjectService projectService, ILoggerFactory loggerFactory) - { - _context = context; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - } - public async Task GetOperationalWellCosts(Guid id) { - var operationalWellCosts = await _context.ExplorationOperationalWellCosts! + var operationalWellCosts = await context.ExplorationOperationalWellCosts! .Include(eowc => eowc.Project) .FirstOrDefaultAsync(o => o.Id == id); return operationalWellCosts; diff --git a/backend/api/Services/Entities/ExplorationWellService.cs b/backend/api/Services/Entities/ExplorationWellService.cs index 3f2783bec..f0b82610c 100644 --- a/backend/api/Services/Entities/ExplorationWellService.cs +++ b/backend/api/Services/Entities/ExplorationWellService.cs @@ -1,26 +1,15 @@ using api.Context; -using api.Dtos; -using api.Exceptions; using api.Models; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class ExplorationWellService : IExplorationWellService +public class ExplorationWellService(DcdDbContext context) : IExplorationWellService { - private readonly DcdDbContext _context; - - public ExplorationWellService(DcdDbContext context) - { - _context = context; - } - public async Task> GetExplorationWellsForExploration(Guid explorationId) { - var explorationWells = await _context.ExplorationWell! + var explorationWells = await context.ExplorationWell! .Include(wpw => wpw.DrillingSchedule) .Where(w => w.ExplorationId == explorationId).ToListAsync(); diff --git a/backend/api/Services/Entities/IDevelopmentOperationalWellCostsService.cs b/backend/api/Services/Entities/IDevelopmentOperationalWellCostsService.cs index bcaa800eb..680ce4399 100644 --- a/backend/api/Services/Entities/IDevelopmentOperationalWellCostsService.cs +++ b/backend/api/Services/Entities/IDevelopmentOperationalWellCostsService.cs @@ -1,4 +1,3 @@ -using api.Dtos; using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/IExplorationOperationalWellCostsService.cs b/backend/api/Services/Entities/IExplorationOperationalWellCostsService.cs index ba68a247e..74c82ab4a 100644 --- a/backend/api/Services/Entities/IExplorationOperationalWellCostsService.cs +++ b/backend/api/Services/Entities/IExplorationOperationalWellCostsService.cs @@ -1,4 +1,3 @@ -using api.Dtos; using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/IExplorationWellService.cs b/backend/api/Services/Entities/IExplorationWellService.cs index 799449fe5..fdda2b413 100644 --- a/backend/api/Services/Entities/IExplorationWellService.cs +++ b/backend/api/Services/Entities/IExplorationWellService.cs @@ -1,4 +1,3 @@ -using api.Dtos; using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/IRevisionService.cs b/backend/api/Services/Entities/IRevisionService.cs index 103332bd4..aa03e9201 100644 --- a/backend/api/Services/Entities/IRevisionService.cs +++ b/backend/api/Services/Entities/IRevisionService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/IWellProjectWellService.cs b/backend/api/Services/Entities/IWellProjectWellService.cs index 22acc40a1..ec8251467 100644 --- a/backend/api/Services/Entities/IWellProjectWellService.cs +++ b/backend/api/Services/Entities/IWellProjectWellService.cs @@ -1,4 +1,3 @@ -using api.Dtos; using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/ProjectMember/ProjectMemberService.cs b/backend/api/Services/Entities/ProjectMember/ProjectMemberService.cs index a8b26e123..6dc74770d 100644 --- a/backend/api/Services/Entities/ProjectMember/ProjectMemberService.cs +++ b/backend/api/Services/Entities/ProjectMember/ProjectMemberService.cs @@ -7,18 +7,8 @@ namespace api.Services; -public class ProjectMemberService : IProjectMemberService +public class ProjectMemberService(IProjectMemberRepository projectMemberRepository) : IProjectMemberService { - - private readonly IProjectMemberRepository _projectMemberRepository; - - public ProjectMemberService( - IProjectMemberRepository projectMemberRepository - ) - { - _projectMemberRepository = projectMemberRepository; - } - public async Task CreateProjectMember(Guid projectId, CreateProjectMemberDto dto) { var projectMember = new ProjectMember @@ -28,15 +18,15 @@ public async Task CreateProjectMember(Guid projectId, CreatePr Role = dto.Role }; - var existingProjectMember = await _projectMemberRepository.GetProjectMember(projectId, dto.UserId); + var existingProjectMember = await projectMemberRepository.GetProjectMember(projectId, dto.UserId); if (existingProjectMember != null) { throw new ResourceAlreadyExistsException("Project member already exists"); } - await _projectMemberRepository.CreateProjectMember(projectMember); - await _projectMemberRepository.SaveChangesAsync(); + await projectMemberRepository.CreateProjectMember(projectMember); + await projectMemberRepository.SaveChangesAsync(); return new ProjectMemberDto { @@ -48,14 +38,14 @@ public async Task CreateProjectMember(Guid projectId, CreatePr public async Task DeleteProjectMember(Guid projectId, Guid userId) { - var projectMember = await _projectMemberRepository.GetProjectMember(projectId, userId); + var projectMember = await projectMemberRepository.GetProjectMember(projectId, userId); if (projectMember == null) { throw new NotFoundInDBException("Project member not found"); } - _projectMemberRepository.DeleteProjectMember(projectMember); - await _projectMemberRepository.SaveChangesAsync(); + projectMemberRepository.DeleteProjectMember(projectMember); + await projectMemberRepository.SaveChangesAsync(); } } diff --git a/backend/api/Services/Entities/ProjectService.cs b/backend/api/Services/Entities/ProjectService.cs index db051c921..816a6bdd6 100644 --- a/backend/api/Services/Entities/ProjectService.cs +++ b/backend/api/Services/Entities/ProjectService.cs @@ -11,58 +11,40 @@ using AutoMapper; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Caching.Memory; using Newtonsoft.Json; namespace api.Services; -public class ProjectService : IProjectService +public class ProjectService( + DcdDbContext context, + ILogger logger, + IMapper mapper, + IProjectRepository projectRepository, + IMapperService mapperService, + IFusionService fusionService) + : IProjectService { - private readonly DcdDbContext _context; - private readonly IFusionService _fusionService; - private readonly ILogger _logger; - private readonly IMapper _mapper; - private readonly IMapperService _mapperService; - private readonly IProjectRepository _projectRepository; - - public ProjectService( - DcdDbContext context, - ILoggerFactory loggerFactory, - IMapper mapper, - IProjectRepository projectRepository, - IMapperService mapperService, - IFusionService fusionService - ) - { - _context = context; - _logger = loggerFactory.CreateLogger(); - _fusionService = fusionService; - _mapper = mapper; - _projectRepository = projectRepository; - _mapperService = mapperService; - } - public async Task UpdateProject(Guid projectId, UpdateProjectDto projectDto) { - var existingProject = await _projectRepository.GetProjectWithCases(projectId) + var existingProject = await projectRepository.GetProjectWithCases(projectId) ?? throw new NotFoundInDBException($"Project {projectId} not found"); existingProject.ModifyTime = DateTimeOffset.UtcNow; - _mapperService.MapToEntity(projectDto, existingProject, projectId); + mapperService.MapToEntity(projectDto, existingProject, projectId); try { - await _projectRepository.SaveChangesAsync(); + await projectRepository.SaveChangesAsync(); } catch (DbUpdateException e) { - _logger.LogError(e, "Failed to update project {projectId}", projectId); + logger.LogError(e, "Failed to update project {projectId}", projectId); throw; } - var dto = _mapperService.MapToDto(existingProject, projectId); + var dto = mapperService.MapToDto(existingProject, projectId); return dto; } @@ -72,23 +54,23 @@ public async Task UpdateExplorationOperation UpdateExplorationOperationalWellCostsDto dto ) { - var existingExplorationOperationalWellCosts = await _projectRepository.GetExplorationOperationalWellCosts(explorationOperationalWellCostsId) + var existingExplorationOperationalWellCosts = await projectRepository.GetExplorationOperationalWellCosts(explorationOperationalWellCostsId) ?? throw new NotFoundInDBException($"ExplorationOperationalWellCosts {explorationOperationalWellCostsId} not found"); - _mapperService.MapToEntity(dto, existingExplorationOperationalWellCosts, explorationOperationalWellCostsId); + mapperService.MapToEntity(dto, existingExplorationOperationalWellCosts, explorationOperationalWellCostsId); try { - await _projectRepository.UpdateModifyTime(projectId); - await _projectRepository.SaveChangesAsync(); + await projectRepository.UpdateModifyTime(projectId); + await projectRepository.SaveChangesAsync(); } catch (DbUpdateException e) { - _logger.LogError(e, "Failed to update exploration operational well costs {explorationOperationalWellCostsId}", explorationOperationalWellCostsId); + logger.LogError(e, "Failed to update exploration operational well costs {explorationOperationalWellCostsId}", explorationOperationalWellCostsId); throw; } - var returnDto = _mapperService.MapToDto(existingExplorationOperationalWellCosts, explorationOperationalWellCostsId); + var returnDto = mapperService.MapToDto(existingExplorationOperationalWellCosts, explorationOperationalWellCostsId); return returnDto; } @@ -98,23 +80,23 @@ public async Task UpdateDevelopmentOperation UpdateDevelopmentOperationalWellCostsDto dto ) { - var existingDevelopmentOperationalWellCosts = await _projectRepository.GetDevelopmentOperationalWellCosts(developmentOperationalWellCostsId) + var existingDevelopmentOperationalWellCosts = await projectRepository.GetDevelopmentOperationalWellCosts(developmentOperationalWellCostsId) ?? throw new NotFoundInDBException($"DevelopmentOperationalWellCosts {developmentOperationalWellCostsId} not found"); - _mapperService.MapToEntity(dto, existingDevelopmentOperationalWellCosts, developmentOperationalWellCostsId); + mapperService.MapToEntity(dto, existingDevelopmentOperationalWellCosts, developmentOperationalWellCostsId); try { - await _projectRepository.UpdateModifyTime(projectId); - await _projectRepository.SaveChangesAsync(); + await projectRepository.UpdateModifyTime(projectId); + await projectRepository.SaveChangesAsync(); } catch (DbUpdateException e) { - _logger.LogError(e, "Failed to update development operational well costs {developmentOperationalWellCostsId}", developmentOperationalWellCostsId); + logger.LogError(e, "Failed to update development operational well costs {developmentOperationalWellCostsId}", developmentOperationalWellCostsId); throw; } - var returnDto = _mapperService.MapToDto(existingDevelopmentOperationalWellCosts, developmentOperationalWellCostsId); + var returnDto = mapperService.MapToDto(existingDevelopmentOperationalWellCosts, developmentOperationalWellCostsId); return returnDto; } @@ -122,16 +104,16 @@ public async Task UpdateProjectFromProjectMaster(ProjectWi { var existingProject = await GetProjectWithCasesAndAssets(projectDto.Id); - _mapper.Map(projectDto, existingProject); + mapper.Map(projectDto, existingProject); - _context.Projects!.Update(existingProject); - await _context.SaveChangesAsync(); + context.Projects!.Update(existingProject); + await context.SaveChangesAsync(); return await GetProjectDto(existingProject.Id); } public async Task CreateProject(Guid contextId) { - var projectMaster = await _fusionService.GetProjectMasterFromFusionContextId(contextId); + var projectMaster = await fusionService.GetProjectMasterFromFusionContextId(contextId); if (projectMaster == null) { @@ -139,7 +121,7 @@ public async Task CreateProject(Guid contextId) } // Check if a project with the same external ID already exists - var existingProject = await _projectRepository.GetProjectByExternalId(projectMaster.Identity); + var existingProject = await projectRepository.GetProjectByExternalId(projectMaster.Identity); if (existingProject != null) { @@ -148,7 +130,7 @@ public async Task CreateProject(Guid contextId) var project = new Project(); - _mapperService.MapToEntity(projectMaster, project, Guid.Empty); + mapperService.MapToEntity(projectMaster, project, Guid.Empty); project.CreateDate = DateTimeOffset.UtcNow; project.Cases = new List(); @@ -170,23 +152,23 @@ public async Task CreateProject(Guid contextId) project.DailyEmissionFromDrillingRig = 100; project.AverageDevelopmentDrillingDays = 50; - _context.Projects.Add(project); + context.Projects.Add(project); - await _context.SaveChangesAsync(); + await context.SaveChangesAsync(); return await GetProjectDto(project.Id); } public async Task> GetAll() { - Activity.Current?.AddBaggage(nameof(_context.Projects), JsonConvert.SerializeObject(_context.Projects, + Activity.Current?.AddBaggage(nameof(context.Projects), JsonConvert.SerializeObject(context.Projects, Formatting.None, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, })); - if (_context.Projects != null) + if (context.Projects != null) { - var projects = _context.Projects + var projects = context.Projects .Include(c => c.Cases); foreach (var project in projects) @@ -208,7 +190,7 @@ public async Task> GetAllDtos() var projectDtos = new List(); foreach (var project in projects) { - var projectDto = _mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); + var projectDto = mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); if (projectDto != null) { projectDtos.Add(projectDto); @@ -229,14 +211,14 @@ public async Task> GetAllDtos() public async Task GetProjectWithoutAssets(Guid projectId) { - if (_context.Projects != null) + if (context.Projects != null) { if (projectId == Guid.Empty) { throw new NotFoundInDBException($"Project {projectId} not found"); } - var project = await _context.Projects! + var project = await context.Projects! .Include(p => p.Cases) .Include(p => p.Wells) .Include(p => p.ExplorationOperationalWellCosts) @@ -251,20 +233,20 @@ public async Task GetProjectWithoutAssets(Guid projectId) return project; } - _logger.LogError(new NotFoundInDBException("The database contains no projects"), "no projects"); + logger.LogError(new NotFoundInDBException("The database contains no projects"), "no projects"); throw new NotFoundInDBException("The database contains no projects"); } public async Task GetProjectWithoutAssetsNoTracking(Guid projectId) { - if (_context.Projects != null) + if (context.Projects != null) { if (projectId == Guid.Empty) { throw new NotFoundInDBException($"Project {projectId} not found"); } - var project = await _context.Projects + var project = await context.Projects .AsNoTracking() .Include(p => p.Cases) .Include(p => p.Wells) @@ -280,13 +262,13 @@ public async Task GetProjectWithoutAssetsNoTracking(Guid projectId) return project; } - _logger.LogError(new NotFoundInDBException("The database contains no projects"), "no projects"); + logger.LogError(new NotFoundInDBException("The database contains no projects"), "no projects"); throw new NotFoundInDBException("The database contains no projects"); } public async Task GetProject(Guid projectId) { - return await _projectRepository.GetProject(projectId) + return await projectRepository.GetProject(projectId) ?? throw new NotFoundInDBException($"Project {projectId} not found"); } @@ -298,7 +280,7 @@ public async Task GetProjectWithCasesAndAssets(Guid projectId) throw new NotFoundInDBException($"Project {projectId} not found"); } - var project = await _context.Projects + var project = await context.Projects .Include(p => p.Cases)!.ThenInclude(c => c.TotalFeasibilityAndConceptStudies) .Include(p => p.Cases)!.ThenInclude(c => c.TotalFeasibilityAndConceptStudiesOverride) .Include(p => p.Cases)!.ThenInclude(c => c.TotalFEEDStudies) @@ -330,7 +312,7 @@ public async Task GetProjectWithCasesAndAssets(Guid projectId) if (project == null) { - throw new NotFoundInDBException(string.Format("Project {0} not found", projectId)); + throw new NotFoundInDBException($"Project {projectId} not found"); } Activity.Current?.AddBaggage(nameof(projectId), JsonConvert.SerializeObject(projectId, Formatting.None, @@ -355,17 +337,17 @@ public async Task GetProjectDto(Guid projectId) { projectLastUpdated = project.ModifyTime; } - var revisionDetails = _context.RevisionDetails.Where(r => r.OriginalProjectId == project.Id).ToList(); + var revisionDetails = context.RevisionDetails.Where(r => r.OriginalProjectId == project.Id).ToList(); - var destination = _mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); + var destination = mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); - destination.RevisionsDetailsList = _mapper.Map>(revisionDetails); + destination.RevisionsDetailsList = mapper.Map>(revisionDetails); var projectDto = destination; if (projectDto == null) { - throw new NotFoundInDBException(string.Format("Project {0} not found", projectId)); + throw new NotFoundInDBException($"Project {projectId} not found"); } projectDto.ModifyTime = projectLastUpdated; @@ -388,32 +370,32 @@ public async Task UpdateProjectFromProjectMaster() var projectMaster = await GetProjectDtoFromProjectMaster(project.Id); if (projectMaster == null) { - _logger.LogWarning("ProjectMaster not found for project {projectName} ({projectId})", project.Name, + logger.LogWarning("ProjectMaster not found for project {projectName} ({projectId})", project.Name, project.Id); continue; } if (!project.Equals(projectMaster)) { - _logger.LogWarning("Project {projectName} ({projectId}) differs from ProjectMaster", project.Name, + logger.LogWarning("Project {projectName} ({projectId}) differs from ProjectMaster", project.Name, project.Id); numberOfDeviations++; await UpdateProjectFromProjectMaster(projectMaster); } else { - _logger.LogInformation("Project {projectName} ({projectId}) is identical to ProjectMaster", + logger.LogInformation("Project {projectName} ({projectId}) is identical to ProjectMaster", project.Name, project.Id); } } - _logger.LogInformation("Number of projects which differs from ProjectMaster: {count} / {total}", + logger.LogInformation("Number of projects which differs from ProjectMaster: {count} / {total}", numberOfDeviations, totalNumberOfProjects); } private async Task GetProjectDtoFromProjectMaster(Guid projectGuid) { - var projectMaster = await _fusionService.GetProjectMasterFromFusionContextId(projectGuid); + var projectMaster = await fusionService.GetProjectMasterFromFusionContextId(projectGuid); if (projectMaster == null) { @@ -430,7 +412,7 @@ public async Task UpdateProjectFromProjectMaster() } catch (ArgumentException ex) { - _logger.LogError(ex, "Invalid category or phase for project with ID {ProjectId}", projectGuid); + logger.LogError(ex, "Invalid category or phase for project with ID {ProjectId}", projectGuid); return null; } @@ -465,14 +447,14 @@ private async Task AddAssetsToProject(Project project) public async Task> GetWells(Guid projectId) { - return await _context.Wells + return await context.Wells .Where(d => d.ProjectId.Equals(projectId)).ToListAsync(); } public async Task> GetExplorations(Guid projectId) { - return await _context.Explorations + return await context.Explorations .Include(c => c.ExplorationWellCostProfile) .Include(c => c.AppraisalWellCostProfile) .Include(c => c.SidetrackCostProfile) @@ -486,7 +468,7 @@ public async Task> GetExplorations(Guid projectId) public async Task> GetTransports(Guid projectId) { - return await _context.Transports + return await context.Transports .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -495,7 +477,7 @@ public async Task> GetTransports(Guid projectId) public async Task> GetTopsides(Guid projectId) { - return await _context.Topsides + return await context.Topsides .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -504,7 +486,7 @@ public async Task> GetTopsides(Guid projectId) public async Task> GetSurfs(Guid projectId) { - return await _context.Surfs + return await context.Surfs .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -513,7 +495,7 @@ public async Task> GetSurfs(Guid projectId) public async Task> GetDrainageStrategies(Guid projectId) { - return await _context.DrainageStrategies + return await context.DrainageStrategies .Include(c => c.ProductionProfileOil) .Include(c => c.AdditionalProductionProfileOil) .Include(c => c.ProductionProfileGas) @@ -536,7 +518,7 @@ public async Task> GetDrainageStrategies(Guid proj public async Task> GetWellProjects(Guid projectId) { - return await _context.WellProjects + return await context.WellProjects .Include(c => c.OilProducerCostProfile) .Include(c => c.OilProducerCostProfileOverride) .Include(c => c.GasProducerCostProfile) @@ -551,7 +533,7 @@ public async Task> GetWellProjects(Guid projectId) public async Task> GetSubstructures(Guid projectId) { - return await _context.Substructures + return await context.Substructures .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) diff --git a/backend/api/Services/Entities/RevisionService.cs b/backend/api/Services/Entities/RevisionService.cs index 1be2ea696..2bfc64bc1 100644 --- a/backend/api/Services/Entities/RevisionService.cs +++ b/backend/api/Services/Entities/RevisionService.cs @@ -16,40 +16,17 @@ namespace api.Services; -public class RevisionService : IRevisionService +public class RevisionService( + DcdDbContext context, + IRevisionRepository revisionRepository, + IMapper mapper, + IProjectRepository projectRepository) + : IRevisionService { - private readonly ILogger _logger; - private readonly IRevisionRepository _revisionRepository; - private readonly IProjectAccessService _projectAccessService; - private readonly IProjectService _projectService; - private readonly DcdDbContext _context; - private readonly IMapper _mapper; - private readonly IProjectRepository _projectRepository; - - - public RevisionService( - DcdDbContext context, - ILoggerFactory loggerFactory, - IRevisionRepository revisionRepository, - IProjectAccessService projectAccessService, - IProjectService projectService, - IMapper mapper, - IProjectRepository projectRepository - ) - { - _context = context; - _logger = loggerFactory.CreateLogger(); - _revisionRepository = revisionRepository; - _projectAccessService = projectAccessService; - _projectService = projectService; - _mapper = mapper; - _projectRepository = projectRepository; - } - // TODO: Rewrite when CaseWithAssetsDto is no longer needed public async Task GetProjectWithCasesAndAssets(Guid projectId) { - Project project = await _context.Projects + Project project = await context.Projects .Include(p => p.Cases)!.ThenInclude(c => c.TotalFeasibilityAndConceptStudies) .Include(p => p.Cases)!.ThenInclude(c => c.TotalFeasibilityAndConceptStudiesOverride) .Include(p => p.Cases)!.ThenInclude(c => c.TotalFEEDStudies) @@ -98,14 +75,14 @@ private async Task AddAssetsToProject(Project project) public async Task> GetWells(Guid projectId) { - return await _context.Wells + return await context.Wells .Where(d => d.ProjectId.Equals(projectId)).ToListAsync(); } public async Task> GetExplorations(Guid projectId) { - return await _context.Explorations + return await context.Explorations .Include(c => c.ExplorationWellCostProfile) .Include(c => c.AppraisalWellCostProfile) .Include(c => c.SidetrackCostProfile) @@ -119,7 +96,7 @@ public async Task> GetExplorations(Guid projectId) public async Task> GetTransports(Guid projectId) { - return await _context.Transports + return await context.Transports .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -128,7 +105,7 @@ public async Task> GetTransports(Guid projectId) public async Task> GetTopsides(Guid projectId) { - return await _context.Topsides + return await context.Topsides .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -137,7 +114,7 @@ public async Task> GetTopsides(Guid projectId) public async Task> GetSurfs(Guid projectId) { - return await _context.Surfs + return await context.Surfs .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -146,7 +123,7 @@ public async Task> GetSurfs(Guid projectId) public async Task> GetDrainageStrategies(Guid projectId) { - return await _context.DrainageStrategies + return await context.DrainageStrategies .Include(c => c.ProductionProfileOil) .Include(c => c.AdditionalProductionProfileOil) .Include(c => c.ProductionProfileGas) @@ -169,7 +146,7 @@ public async Task> GetDrainageStrategies(Guid proj public async Task> GetWellProjects(Guid projectId) { - return await _context.WellProjects + return await context.WellProjects .Include(c => c.OilProducerCostProfile) .Include(c => c.OilProducerCostProfileOverride) .Include(c => c.GasProducerCostProfile) @@ -184,7 +161,7 @@ public async Task> GetWellProjects(Guid projectId) public async Task> GetSubstructures(Guid projectId) { - return await _context.Substructures + return await context.Substructures .Include(c => c.CostProfile) .Include(c => c.CostProfileOverride) .Include(c => c.CessationCostProfile) @@ -204,13 +181,13 @@ public async Task GetRevision(Guid projectId) projectLastUpdated = project.ModifyTime; } - var destination = _mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); + var destination = mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); var projectDto = destination; if (projectDto == null) { - throw new NotFoundInDBException(string.Format("Project {0} not found", projectId)); + throw new NotFoundInDBException($"Project {projectId} not found"); } projectDto.ModifyTime = projectLastUpdated; @@ -225,7 +202,7 @@ public async Task GetRevision(Guid projectId) public async Task CreateRevision(Guid projectId, CreateRevisionDto createRevisionDto) { - var project = await _revisionRepository.GetProjectAndAssetsNoTracking(projectId) + var project = await revisionRepository.GetProjectAndAssetsNoTracking(projectId) ?? throw new NotFoundInDBException($"Project with id {projectId} not found."); SetProjectAndRelatedEntitiesToEmptyGuids(project, projectId, createRevisionDto); @@ -243,16 +220,16 @@ public async Task CreateRevision(Guid projectId, CreateRev project.RevisionDetails = revisionDetails; - var revision = await _revisionRepository.AddRevision(project); + var revision = await revisionRepository.AddRevision(project); - var revisionDto = _mapper.Map(revision, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); + var revisionDto = mapper.Map(revision, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); return revisionDto; } private async Task UpdateProjectWithRevisionChanges(Guid projectId, CreateRevisionDto createRevisionDto) { - var existingProject = await _projectRepository.GetProject(projectId) + var existingProject = await projectRepository.GetProject(projectId) ?? throw new NotFoundInDBException($"Project {projectId} not found"); existingProject.InternalProjectPhase = createRevisionDto.InternalProjectPhase; diff --git a/backend/api/Services/Entities/Substructure/ISubstructureTimeSeriesService.cs b/backend/api/Services/Entities/Substructure/ISubstructureTimeSeriesService.cs index e787517f8..cda02c349 100644 --- a/backend/api/Services/Entities/Substructure/ISubstructureTimeSeriesService.cs +++ b/backend/api/Services/Entities/Substructure/ISubstructureTimeSeriesService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/Substructure/SubstructureService.cs b/backend/api/Services/Entities/Substructure/SubstructureService.cs index a167ea071..8c0ee5cdd 100644 --- a/backend/api/Services/Entities/Substructure/SubstructureService.cs +++ b/backend/api/Services/Entities/Substructure/SubstructureService.cs @@ -1,53 +1,26 @@ using System.Linq.Expressions; -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class SubstructureService : ISubstructureService +public class SubstructureService( + ILogger logger, + ISubstructureRepository substructureRepository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ISubstructureService { - private readonly DcdDbContext _context; - private readonly IProjectService _projectService; - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly IMapper _mapper; - private readonly ISubstructureRepository _repository; - private readonly ICaseRepository _caseRepository; - private readonly IMapperService _mapperService; - - public SubstructureService( - DcdDbContext context, - IProjectService projectService, - ILoggerFactory loggerFactory, - IMapper mapper, - ISubstructureRepository substructureRepository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _context = context; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - _mapper = mapper; - _repository = substructureRepository; - _caseRepository = caseRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task GetSubstructureWithIncludes(Guid substructureId, params Expression>[] includes) { - return await _repository.GetSubstructureWithIncludes(substructureId, includes) + return await substructureRepository.GetSubstructureWithIncludes(substructureId, includes) ?? throw new NotFoundInDBException($"Substructure with id {substructureId} not found."); } @@ -60,28 +33,28 @@ TDto updatedSubstructureDto where TDto : BaseUpdateSubstructureDto { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, substructureId); + await projectAccessService.ProjectExists(projectId, substructureId); - var existingSubstructure = await _repository.GetSubstructure(substructureId) + var existingSubstructure = await substructureRepository.GetSubstructure(substructureId) ?? throw new NotFoundInDBException($"Substructure with id {substructureId} not found."); - _mapperService.MapToEntity(updatedSubstructureDto, existingSubstructure, substructureId); + mapperService.MapToEntity(updatedSubstructureDto, existingSubstructure, substructureId); existingSubstructure.LastChangedDate = DateTimeOffset.UtcNow; // Substructure updatedSubstructure; try { // updatedSubstructure = _repository.UpdateSubstructure(existingSubstructure); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await substructureRepository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update substructure with id {SubstructureId} for case id {CaseId}.", substructureId, caseId); + logger.LogError(ex, "Failed to update substructure with id {SubstructureId} for case id {CaseId}.", substructureId, caseId); throw; } - var dto = _mapperService.MapToDto(existingSubstructure, substructureId); + var dto = mapperService.MapToDto(existingSubstructure, substructureId); return dto; } diff --git a/backend/api/Services/Entities/Substructure/SubstructureTimeSeriesService.cs b/backend/api/Services/Entities/Substructure/SubstructureTimeSeriesService.cs index dfe696363..b39549296 100644 --- a/backend/api/Services/Entities/Substructure/SubstructureTimeSeriesService.cs +++ b/backend/api/Services/Entities/Substructure/SubstructureTimeSeriesService.cs @@ -1,43 +1,21 @@ - -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class SubstructureTimeSeriesService : ISubstructureTimeSeriesService +public class SubstructureTimeSeriesService( + ILogger logger, + ISubstructureRepository substructureRepository, + ISubstructureTimeSeriesRepository repository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ISubstructureTimeSeriesService { - private readonly ILogger _logger; - private readonly ISubstructureRepository _substructureRepository; - private readonly ISubstructureTimeSeriesRepository _repository; - private readonly ICaseRepository _caseRepository; - private readonly IMapperService _mapperService; - private readonly IProjectAccessService _projectAccessService; - - - public SubstructureTimeSeriesService( - ILoggerFactory loggerFactory, - ISubstructureRepository substructureRepository, - ISubstructureTimeSeriesRepository repository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _repository = repository; - _substructureRepository = substructureRepository; - _caseRepository = caseRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task AddOrUpdateSubstructureCostProfile( Guid projectId, Guid caseId, @@ -46,9 +24,9 @@ UpdateSubstructureCostProfileDto dto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, substructureId); + await projectAccessService.ProjectExists(projectId, substructureId); - var substructure = await _substructureRepository.GetSubstructureWithCostProfile(substructureId) + var substructure = await substructureRepository.GetSubstructureWithCostProfile(substructureId) ?? throw new NotFoundInDBException($"Substructure with id {substructureId} not found."); if (substructure.CostProfile != null) @@ -73,8 +51,8 @@ UpdateSubstructureCostProfileDto dto substructureId, profileId, dto, - _repository.GetSubstructureCostProfile, - _repository.UpdateSubstructureCostProfile + repository.GetSubstructureCostProfile, + repository.UpdateSubstructureCostProfile ); } @@ -90,24 +68,24 @@ Substructure substructure Substructure = substructure }; - var newProfile = _mapperService.MapToEntity(dto, substructureCostProfile, substructureId); + var newProfile = mapperService.MapToEntity(dto, substructureCostProfile, substructureId); if (newProfile.Substructure.CostProfileOverride != null) { newProfile.Substructure.CostProfileOverride.Override = false; } try { - _repository.CreateSubstructureCostProfile(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + repository.CreateSubstructureCostProfile(newProfile); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (Exception ex) { - _logger.LogError(ex, "Failed to create cost profile for substructure with id {substructureId} for case id {caseId}.", substructureId, caseId); + logger.LogError(ex, "Failed to create cost profile for substructure with id {substructureId} for case id {caseId}.", substructureId, caseId); throw; } - var newDto = _mapperService.MapToDto(newProfile, newProfile.Id); + var newDto = mapperService.MapToDto(newProfile, newProfile.Id); return newDto; } @@ -119,12 +97,12 @@ CreateSubstructureCostProfileOverrideDto dto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, substructureId); + await projectAccessService.ProjectExists(projectId, substructureId); - var substructure = await _substructureRepository.GetSubstructure(substructureId) + var substructure = await substructureRepository.GetSubstructure(substructureId) ?? throw new NotFoundInDBException($"Substructure with id {substructureId} not found."); - var resourceHasProfile = await _substructureRepository.SubstructureHasCostProfileOverride(substructureId); + var resourceHasProfile = await substructureRepository.SubstructureHasCostProfileOverride(substructureId); if (resourceHasProfile) { @@ -136,22 +114,22 @@ CreateSubstructureCostProfileOverrideDto dto Substructure = substructure, }; - var newProfile = _mapperService.MapToEntity(dto, profile, substructureId); + var newProfile = mapperService.MapToEntity(dto, profile, substructureId); SubstructureCostProfileOverride createdProfile; try { - createdProfile = _repository.CreateSubstructureCostProfileOverride(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + createdProfile = repository.CreateSubstructureCostProfileOverride(newProfile); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create profile SubstructureCostProfileOverride for case id {caseId}.", caseId); + logger.LogError(ex, "Failed to create profile SubstructureCostProfileOverride for case id {caseId}.", caseId); throw; } - var updatedDto = _mapperService.MapToDto(createdProfile, createdProfile.Id); + var updatedDto = mapperService.MapToDto(createdProfile, createdProfile.Id); return updatedDto; } @@ -169,8 +147,8 @@ UpdateSubstructureCostProfileOverrideDto dto substructureId, costProfileId, dto, - _repository.GetSubstructureCostProfileOverride, - _repository.UpdateSubstructureCostProfileOverride + repository.GetSubstructureCostProfileOverride, + repository.UpdateSubstructureCostProfileOverride ); } @@ -191,7 +169,7 @@ Func updateProfile ?? throw new NotFoundInDBException($"Cost profile with id {profileId} not found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingProfile.Substructure.Id); + await projectAccessService.ProjectExists(projectId, existingProfile.Substructure.Id); if (existingProfile.Substructure.ProspVersion == null) { @@ -200,21 +178,21 @@ Func updateProfile existingProfile.Substructure.CostProfileOverride.Override = true; } } - _mapperService.MapToEntity(updatedProfileDto, existingProfile, substructureId); + mapperService.MapToEntity(updatedProfileDto, existingProfile, substructureId); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { var profileName = typeof(TProfile).Name; - _logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); + logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); throw; } - var updatedDto = _mapperService.MapToDto(existingProfile, profileId); + var updatedDto = mapperService.MapToDto(existingProfile, profileId); return updatedDto; } } diff --git a/backend/api/Services/Entities/Surf/ISurfTimeSeriesService.cs b/backend/api/Services/Entities/Surf/ISurfTimeSeriesService.cs index a96b7299c..658437df7 100644 --- a/backend/api/Services/Entities/Surf/ISurfTimeSeriesService.cs +++ b/backend/api/Services/Entities/Surf/ISurfTimeSeriesService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/Surf/SurfService.cs b/backend/api/Services/Entities/Surf/SurfService.cs index 8be911d81..b848f7417 100644 --- a/backend/api/Services/Entities/Surf/SurfService.cs +++ b/backend/api/Services/Entities/Surf/SurfService.cs @@ -1,42 +1,25 @@ using System.Linq.Expressions; -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class SurfService : ISurfService +public class SurfService( + ILogger logger, + ISurfRepository repository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ISurfService { - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly ISurfRepository _repository; - private readonly ICaseRepository _caseRepository; - private readonly IMapperService _mapperService; - public SurfService( - ILoggerFactory loggerFactory, - ISurfRepository repository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _repository = repository; - _caseRepository = caseRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task GetSurfWithIncludes(Guid surfId, params Expression>[] includes) { - return await _repository.GetSurfWithIncludes(surfId, includes) + return await repository.GetSurfWithIncludes(surfId, includes) ?? throw new NotFoundInDBException($"Topside with id {surfId} not found."); } @@ -49,27 +32,27 @@ TDto updatedSurfDto where TDto : BaseUpdateSurfDto { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, surfId); + await projectAccessService.ProjectExists(projectId, surfId); - var existingSurf = await _repository.GetSurf(surfId) - ?? throw new ArgumentException(string.Format($"Surf with id {surfId} not found.")); + var existingSurf = await repository.GetSurf(surfId) + ?? throw new ArgumentException($"Surf with id {surfId} not found."); - _mapperService.MapToEntity(updatedSurfDto, existingSurf, surfId); + mapperService.MapToEntity(updatedSurfDto, existingSurf, surfId); existingSurf.LastChangedDate = DateTimeOffset.UtcNow; try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update surf with id {surfId} for case id {caseId}.", surfId, caseId); + logger.LogError(ex, "Failed to update surf with id {surfId} for case id {caseId}.", surfId, caseId); throw; } - var dto = _mapperService.MapToDto(existingSurf, surfId); + var dto = mapperService.MapToDto(existingSurf, surfId); return dto; } } diff --git a/backend/api/Services/Entities/Surf/SurfTimeSeriesService.cs b/backend/api/Services/Entities/Surf/SurfTimeSeriesService.cs index 8898e1f95..7dffaf5d6 100644 --- a/backend/api/Services/Entities/Surf/SurfTimeSeriesService.cs +++ b/backend/api/Services/Entities/Surf/SurfTimeSeriesService.cs @@ -1,40 +1,21 @@ -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class SurfTimeSeriesService : ISurfTimeSeriesService +public class SurfTimeSeriesService( + ILogger logger, + ISurfTimeSeriesRepository repository, + ISurfRepository surfRepository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ISurfTimeSeriesService { - private readonly ILogger _logger; - private readonly IProjectAccessService _projectAccessService; - private readonly ISurfRepository _surfRepository; - private readonly ISurfTimeSeriesRepository _repository; - private readonly ICaseRepository _caseRepository; - private readonly IMapperService _mapperService; - public SurfTimeSeriesService( - ILoggerFactory loggerFactory, - ISurfTimeSeriesRepository repository, - ISurfRepository surfRepository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _repository = repository; - _surfRepository = surfRepository; - _caseRepository = caseRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task CreateSurfCostProfileOverride( Guid projectId, Guid caseId, @@ -43,12 +24,12 @@ CreateSurfCostProfileOverrideDto dto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, surfId); + await projectAccessService.ProjectExists(projectId, surfId); - var surf = await _surfRepository.GetSurf(surfId) + var surf = await surfRepository.GetSurf(surfId) ?? throw new NotFoundInDBException($"Surf with id {surfId} not found."); - var resourceHasProfile = await _surfRepository.SurfHasCostProfileOverride(surfId); + var resourceHasProfile = await surfRepository.SurfHasCostProfileOverride(surfId); if (resourceHasProfile) { @@ -60,22 +41,22 @@ CreateSurfCostProfileOverrideDto dto Surf = surf, }; - var newProfile = _mapperService.MapToEntity(dto, profile, surfId); + var newProfile = mapperService.MapToEntity(dto, profile, surfId); SurfCostProfileOverride createdProfile; try { - createdProfile = _repository.CreateSurfCostProfileOverride(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + createdProfile = repository.CreateSurfCostProfileOverride(newProfile); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create profile SurfCostProfileOverride for case id {caseId}.", caseId); + logger.LogError(ex, "Failed to create profile SurfCostProfileOverride for case id {caseId}.", caseId); throw; } - var updatedDto = _mapperService.MapToDto(createdProfile, createdProfile.Id); + var updatedDto = mapperService.MapToDto(createdProfile, createdProfile.Id); return updatedDto; } @@ -87,9 +68,9 @@ UpdateSurfCostProfileDto dto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, surfId); + await projectAccessService.ProjectExists(projectId, surfId); - var surf = await _surfRepository.GetSurfWithCostProfile(surfId) + var surf = await surfRepository.GetSurfWithCostProfile(surfId) ?? throw new NotFoundInDBException($"Surf with id {surfId} not found."); if (surf.CostProfile != null) @@ -114,8 +95,8 @@ UpdateSurfCostProfileDto dto surfId, profileId, dto, - _repository.GetSurfCostProfile, - _repository.UpdateSurfCostProfile + repository.GetSurfCostProfile, + repository.UpdateSurfCostProfile ); } @@ -131,7 +112,7 @@ Surf surf Surf = surf }; - var newProfile = _mapperService.MapToEntity(dto, surfCostProfile, surfId); + var newProfile = mapperService.MapToEntity(dto, surfCostProfile, surfId); if (newProfile.Surf.CostProfileOverride != null) { @@ -140,17 +121,17 @@ Surf surf try { - _repository.CreateSurfCostProfile(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + repository.CreateSurfCostProfile(newProfile); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (Exception ex) { - _logger.LogError(ex, "Failed to create cost profile for surf with id {surfId} for case id {caseId}.", surfId, caseId); + logger.LogError(ex, "Failed to create cost profile for surf with id {surfId} for case id {caseId}.", surfId, caseId); throw; } - var newDto = _mapperService.MapToDto(newProfile, newProfile.Id); + var newDto = mapperService.MapToDto(newProfile, newProfile.Id); return newDto; } @@ -168,8 +149,8 @@ UpdateSurfCostProfileOverrideDto updatedSurfCostProfileOverrideDto surfId, costProfileId, updatedSurfCostProfileOverrideDto, - _repository.GetSurfCostProfileOverride, - _repository.UpdateSurfCostProfileOverride + repository.GetSurfCostProfileOverride, + repository.UpdateSurfCostProfileOverride ); } @@ -190,7 +171,7 @@ Func updateProfile ?? throw new NotFoundInDBException($"Cost profile with id {profileId} not found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingProfile.Surf.Id); + await projectAccessService.ProjectExists(projectId, existingProfile.Surf.Id); if (existingProfile.Surf.ProspVersion == null) { @@ -200,23 +181,23 @@ Func updateProfile } } - _mapperService.MapToEntity(updatedProfileDto, existingProfile, surfId); + mapperService.MapToEntity(updatedProfileDto, existingProfile, surfId); // TProfile updatedProfile; try { // updatedProfile = updateProfile(existingProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { var profileName = typeof(TProfile).Name; - _logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); + logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); throw; } - var updatedDto = _mapperService.MapToDto(existingProfile, profileId); + var updatedDto = mapperService.MapToDto(existingProfile, profileId); return updatedDto; } } diff --git a/backend/api/Services/Entities/Topside/ITopsideTimeSeriesService.cs b/backend/api/Services/Entities/Topside/ITopsideTimeSeriesService.cs index 4fdcf8c38..9b14a717a 100644 --- a/backend/api/Services/Entities/Topside/ITopsideTimeSeriesService.cs +++ b/backend/api/Services/Entities/Topside/ITopsideTimeSeriesService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/Topside/TopsideService.cs b/backend/api/Services/Entities/Topside/TopsideService.cs index 800492e7a..493f54652 100644 --- a/backend/api/Services/Entities/Topside/TopsideService.cs +++ b/backend/api/Services/Entities/Topside/TopsideService.cs @@ -1,43 +1,25 @@ using System.Linq.Expressions; -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class TopsideService : ITopsideService +public class TopsideService( + ILogger logger, + ITopsideRepository repository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ITopsideService { - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly ITopsideRepository _repository; - private readonly ICaseRepository _caseRepository; - private readonly IMapperService _mapperService; - - public TopsideService( - ILoggerFactory loggerFactory, - ITopsideRepository repository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _repository = repository; - _caseRepository = caseRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task GetTopsideWithIncludes(Guid topsideId, params Expression>[] includes) { - return await _repository.GetTopsideWithIncludes(topsideId, includes) + return await repository.GetTopsideWithIncludes(topsideId, includes) ?? throw new NotFoundInDBException($"Topside with id {topsideId} not found."); } @@ -50,26 +32,26 @@ TDto updatedTopsideDto where TDto : BaseUpdateTopsideDto { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, topsideId); + await projectAccessService.ProjectExists(projectId, topsideId); - var existingTopside = await _repository.GetTopside(topsideId) + var existingTopside = await repository.GetTopside(topsideId) ?? throw new NotFoundInDBException($"Topside with id {topsideId} not found."); - _mapperService.MapToEntity(updatedTopsideDto, existingTopside, topsideId); + mapperService.MapToEntity(updatedTopsideDto, existingTopside, topsideId); existingTopside.LastChangedDate = DateTimeOffset.UtcNow; try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update topside with id {topsideId} for case id {caseId}.", topsideId, caseId); + logger.LogError(ex, "Failed to update topside with id {topsideId} for case id {caseId}.", topsideId, caseId); throw; } - var dto = _mapperService.MapToDto(existingTopside, topsideId); + var dto = mapperService.MapToDto(existingTopside, topsideId); return dto; } } diff --git a/backend/api/Services/Entities/Topside/TopsideTimeSeriesService.cs b/backend/api/Services/Entities/Topside/TopsideTimeSeriesService.cs index dda326d8c..ab82ec080 100644 --- a/backend/api/Services/Entities/Topside/TopsideTimeSeriesService.cs +++ b/backend/api/Services/Entities/Topside/TopsideTimeSeriesService.cs @@ -1,41 +1,21 @@ -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class TopsideTimeSeriesService : ITopsideTimeSeriesService +public class TopsideTimeSeriesService( + ILogger logger, + ITopsideTimeSeriesRepository repository, + ITopsideRepository topsideRepository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ITopsideTimeSeriesService { - private readonly ILogger _logger; - private readonly IProjectAccessService _projectAccessService; - private readonly ITopsideTimeSeriesRepository _repository; - private readonly ITopsideRepository _topsideRepository; - private readonly ICaseRepository _caseRepository; - private readonly IMapperService _mapperService; - - public TopsideTimeSeriesService( - ILoggerFactory loggerFactory, - ITopsideTimeSeriesRepository repository, - ITopsideRepository topsideRepository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _repository = repository; - _topsideRepository = topsideRepository; - _caseRepository = caseRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task CreateTopsideCostProfileOverride( Guid projectId, Guid caseId, @@ -44,12 +24,12 @@ CreateTopsideCostProfileOverrideDto dto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, topsideId); + await projectAccessService.ProjectExists(projectId, topsideId); - var topside = await _topsideRepository.GetTopside(topsideId) + var topside = await topsideRepository.GetTopside(topsideId) ?? throw new NotFoundInDBException($"Topside with id {topsideId} not found."); - var resourceHasProfile = await _topsideRepository.TopsideHasCostProfileOverride(topsideId); + var resourceHasProfile = await topsideRepository.TopsideHasCostProfileOverride(topsideId); if (resourceHasProfile) { @@ -61,22 +41,22 @@ CreateTopsideCostProfileOverrideDto dto Topside = topside, }; - var newProfile = _mapperService.MapToEntity(dto, profile, topsideId); + var newProfile = mapperService.MapToEntity(dto, profile, topsideId); TopsideCostProfileOverride createdProfile; try { - createdProfile = _repository.CreateTopsideCostProfileOverride(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + createdProfile = repository.CreateTopsideCostProfileOverride(newProfile); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create profile TopsideCostProfileOverride for case id {caseId}.", caseId); + logger.LogError(ex, "Failed to create profile TopsideCostProfileOverride for case id {caseId}.", caseId); throw; } - var updatedDto = _mapperService.MapToDto(createdProfile, createdProfile.Id); + var updatedDto = mapperService.MapToDto(createdProfile, createdProfile.Id); return updatedDto; } @@ -94,8 +74,8 @@ UpdateTopsideCostProfileOverrideDto dto topsideId, costProfileId, dto, - _repository.GetTopsideCostProfileOverride, - _repository.UpdateTopsideCostProfileOverride + repository.GetTopsideCostProfileOverride, + repository.UpdateTopsideCostProfileOverride ); } @@ -107,9 +87,9 @@ UpdateTopsideCostProfileDto dto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, topsideId); + await projectAccessService.ProjectExists(projectId, topsideId); - var topside = await _topsideRepository.GetTopsideWithCostProfile(topsideId) + var topside = await topsideRepository.GetTopsideWithCostProfile(topsideId) ?? throw new NotFoundInDBException($"Topside with id {topsideId} not found."); if (topside.CostProfile != null) @@ -134,8 +114,8 @@ UpdateTopsideCostProfileDto dto topsideId, profileId, dto, - _repository.GetTopsideCostProfile, - _repository.UpdateTopsideCostProfile + repository.GetTopsideCostProfile, + repository.UpdateTopsideCostProfile ); } @@ -151,24 +131,24 @@ Topside topside Topside = topside }; - var newProfile = _mapperService.MapToEntity(dto, topsideCostProfile, topsideId); + var newProfile = mapperService.MapToEntity(dto, topsideCostProfile, topsideId); if (newProfile.Topside.CostProfileOverride != null) { newProfile.Topside.CostProfileOverride.Override = false; } try { - _repository.CreateTopsideCostProfile(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + repository.CreateTopsideCostProfile(newProfile); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (Exception ex) { - _logger.LogError(ex, "Failed to create cost profile for topside with id {topsideId} for case id {caseId}.", topsideId, caseId); + logger.LogError(ex, "Failed to create cost profile for topside with id {topsideId} for case id {caseId}.", topsideId, caseId); throw; } - var newDto = _mapperService.MapToDto(newProfile, newProfile.Id); + var newDto = mapperService.MapToDto(newProfile, newProfile.Id); return newDto; } @@ -189,7 +169,7 @@ Func updateProfile ?? throw new NotFoundInDBException($"Cost profile with id {profileId} not found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingProfile.Topside.Id); + await projectAccessService.ProjectExists(projectId, existingProfile.Topside.Id); if (existingProfile.Topside.ProspVersion == null) { @@ -199,21 +179,21 @@ Func updateProfile } } - _mapperService.MapToEntity(updatedProfileDto, existingProfile, topsideId); + mapperService.MapToEntity(updatedProfileDto, existingProfile, topsideId); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { var profileName = typeof(TProfile).Name; - _logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); + logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); throw; } - var updatedDto = _mapperService.MapToDto(existingProfile, profileId); + var updatedDto = mapperService.MapToDto(existingProfile, profileId); return updatedDto; } } diff --git a/backend/api/Services/Entities/Transport/ITransportTimeSeriesService.cs b/backend/api/Services/Entities/Transport/ITransportTimeSeriesService.cs index 8777698dc..bb2308faa 100644 --- a/backend/api/Services/Entities/Transport/ITransportTimeSeriesService.cs +++ b/backend/api/Services/Entities/Transport/ITransportTimeSeriesService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/Transport/TransportService.cs b/backend/api/Services/Entities/Transport/TransportService.cs index 1ec24a05c..e446a7d17 100644 --- a/backend/api/Services/Entities/Transport/TransportService.cs +++ b/backend/api/Services/Entities/Transport/TransportService.cs @@ -1,43 +1,25 @@ using System.Linq.Expressions; -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class TransportService : ITransportService +public class TransportService( + ILogger logger, + ICaseRepository caseRepository, + ITransportRepository transportRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ITransportService { - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly ICaseRepository _caseRepository; - private readonly ITransportRepository _repository; - private readonly IMapperService _mapperService; - - public TransportService( - ILoggerFactory loggerFactory, - ICaseRepository caseRepository, - ITransportRepository transportRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _caseRepository = caseRepository; - _repository = transportRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task GetTransportWithIncludes(Guid transportId, params Expression>[] includes) { - return await _repository.GetTransportWithIncludes(transportId, includes) + return await transportRepository.GetTransportWithIncludes(transportId, includes) ?? throw new NotFoundInDBException($"Transport with id {transportId} not found."); } @@ -45,29 +27,29 @@ public async Task UpdateTransport(Guid projectId, Guid caseI where TDto : BaseUpdateTransportDto { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, transportId); + await projectAccessService.ProjectExists(projectId, transportId); - var existing = await _repository.GetTransport(transportId) + var existing = await transportRepository.GetTransport(transportId) ?? throw new NotFoundInDBException($"Transport with id {transportId} not found."); - _mapperService.MapToEntity(updatedTransportDto, existing, transportId); + mapperService.MapToEntity(updatedTransportDto, existing, transportId); existing.LastChangedDate = DateTimeOffset.UtcNow; // Transport updatedTransport; try { // updatedTransport = _repository.UpdateTransport(existing); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await transportRepository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateConcurrencyException ex) { - _logger.LogError(ex, "Failed to update transport with id {transportId} for case id {caseId}.", transportId, caseId); + logger.LogError(ex, "Failed to update transport with id {transportId} for case id {caseId}.", transportId, caseId); throw; } - var dto = _mapperService.MapToDto(existing, transportId); + var dto = mapperService.MapToDto(existing, transportId); return dto; } } diff --git a/backend/api/Services/Entities/Transport/TransportTimeSeriesService.cs b/backend/api/Services/Entities/Transport/TransportTimeSeriesService.cs index 28086c082..ebfa4504f 100644 --- a/backend/api/Services/Entities/Transport/TransportTimeSeriesService.cs +++ b/backend/api/Services/Entities/Transport/TransportTimeSeriesService.cs @@ -1,41 +1,21 @@ -using api.Context; using api.Dtos; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class TransportTimeSeriesService : ITransportTimeSeriesService +public class TransportTimeSeriesService( + ILogger logger, + ICaseRepository caseRepository, + ITransportRepository transportRepository, + ITransportTimeSeriesRepository repository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : ITransportTimeSeriesService { - private readonly ILogger _logger; - private readonly IProjectAccessService _projectAccessService; - private readonly ICaseRepository _caseRepository; - private readonly ITransportRepository _transportRepository; - private readonly ITransportTimeSeriesRepository _repository; - private readonly IMapperService _mapperService; - - public TransportTimeSeriesService( - ILoggerFactory loggerFactory, - ICaseRepository caseRepository, - ITransportRepository transportRepository, - ITransportTimeSeriesRepository repository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _caseRepository = caseRepository; - _repository = repository; - _transportRepository = transportRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task CreateTransportCostProfileOverride( Guid projectId, Guid caseId, @@ -44,12 +24,12 @@ CreateTransportCostProfileOverrideDto dto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, transportId); + await projectAccessService.ProjectExists(projectId, transportId); - var transport = await _transportRepository.GetTransport(transportId) + var transport = await transportRepository.GetTransport(transportId) ?? throw new NotFoundInDBException($"Transport with id {transportId} not found."); - var resourceHasProfile = await _transportRepository.TransportHasCostProfileOverride(transportId); + var resourceHasProfile = await transportRepository.TransportHasCostProfileOverride(transportId); if (resourceHasProfile) { @@ -61,22 +41,22 @@ CreateTransportCostProfileOverrideDto dto Transport = transport, }; - var newProfile = _mapperService.MapToEntity(dto, profile, transportId); + var newProfile = mapperService.MapToEntity(dto, profile, transportId); TransportCostProfileOverride createdProfile; try { - createdProfile = _repository.CreateTransportCostProfileOverride(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + createdProfile = repository.CreateTransportCostProfileOverride(newProfile); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create profile TransportCostProfileOverride for case id {caseId}.", caseId); + logger.LogError(ex, "Failed to create profile TransportCostProfileOverride for case id {caseId}.", caseId); throw; } - var updatedDto = _mapperService.MapToDto(createdProfile, createdProfile.Id); + var updatedDto = mapperService.MapToDto(createdProfile, createdProfile.Id); return updatedDto; } @@ -93,8 +73,8 @@ public async Task UpdateTransportCostProfileOve transportId, costProfileId, dto, - _repository.GetTransportCostProfileOverride, - _repository.UpdateTransportCostProfileOverride + repository.GetTransportCostProfileOverride, + repository.UpdateTransportCostProfileOverride ); } @@ -105,7 +85,7 @@ public async Task AddOrUpdateTransportCostProfile( UpdateTransportCostProfileDto dto ) { - var transport = await _transportRepository.GetTransportWithCostProfile(transportId) + var transport = await transportRepository.GetTransportWithCostProfile(transportId) ?? throw new NotFoundInDBException($"Transport with id {transportId} not found."); if (transport.CostProfile != null) @@ -130,8 +110,8 @@ UpdateTransportCostProfileDto dto transportId, profileId, dto, - _repository.GetTransportCostProfile, - _repository.UpdateTransportCostProfile + repository.GetTransportCostProfile, + repository.UpdateTransportCostProfile ); } @@ -147,7 +127,7 @@ Transport transport Transport = transport }; - var newProfile = _mapperService.MapToEntity(dto, transportCostProfile, transportId); + var newProfile = mapperService.MapToEntity(dto, transportCostProfile, transportId); if (newProfile.Transport.CostProfileOverride != null) { @@ -156,17 +136,17 @@ Transport transport try { - _repository.CreateTransportCostProfile(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + repository.CreateTransportCostProfile(newProfile); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (Exception ex) { - _logger.LogError(ex, "Failed to create cost profile for transport with id {transportId} for case id {caseId}.", transportId, caseId); + logger.LogError(ex, "Failed to create cost profile for transport with id {transportId} for case id {caseId}.", transportId, caseId); throw; } - var newDto = _mapperService.MapToDto(newProfile, newProfile.Id); + var newDto = mapperService.MapToDto(newProfile, newProfile.Id); return newDto; } @@ -187,7 +167,7 @@ Func updateProfile ?? throw new NotFoundInDBException($"Cost profile with id {profileId} not found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingProfile.Transport.Id); + await projectAccessService.ProjectExists(projectId, existingProfile.Transport.Id); if (existingProfile.Transport.ProspVersion == null) { @@ -197,21 +177,21 @@ Func updateProfile } } - _mapperService.MapToEntity(updatedProfileDto, existingProfile, transportId); + mapperService.MapToEntity(updatedProfileDto, existingProfile, transportId); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { var profileName = typeof(TProfile).Name; - _logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); + logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); throw; } - var updatedDto = _mapperService.MapToDto(existingProfile, profileId); + var updatedDto = mapperService.MapToDto(existingProfile, profileId); return updatedDto; } } diff --git a/backend/api/Services/Entities/WellProject/IWellProjectTimeSeriesService.cs b/backend/api/Services/Entities/WellProject/IWellProjectTimeSeriesService.cs index 8b396849b..1af575584 100644 --- a/backend/api/Services/Entities/WellProject/IWellProjectTimeSeriesService.cs +++ b/backend/api/Services/Entities/WellProject/IWellProjectTimeSeriesService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Entities/WellProject/WellProjectService.cs b/backend/api/Services/Entities/WellProject/WellProjectService.cs index dc1a9520b..2eefbb628 100644 --- a/backend/api/Services/Entities/WellProject/WellProjectService.cs +++ b/backend/api/Services/Entities/WellProject/WellProjectService.cs @@ -9,32 +9,17 @@ namespace api.Services; -public class WellProjectService : IWellProjectService +public class WellProjectService( + ILogger logger, + IWellProjectRepository repository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : IWellProjectService { - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly IWellProjectRepository _repository; - private readonly ICaseRepository _caseRepository; - private readonly IMapperService _mapperService; - - public WellProjectService( - ILoggerFactory loggerFactory, - IWellProjectRepository repository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _logger = loggerFactory.CreateLogger(); - _repository = repository; - _caseRepository = caseRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task GetWellProjectWithIncludes(Guid wellProjectId, params Expression>[] includes) { - return await _repository.GetWellProjectWithIncludes(wellProjectId, includes) + return await repository.GetWellProjectWithIncludes(wellProjectId, includes) ?? throw new NotFoundInDBException($"WellProject with id {wellProjectId} not found."); } @@ -46,25 +31,25 @@ UpdateWellProjectDto updatedWellProjectDto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, wellProjectId); + await projectAccessService.ProjectExists(projectId, wellProjectId); - var existingWellProject = await _repository.GetWellProject(wellProjectId) + var existingWellProject = await repository.GetWellProject(wellProjectId) ?? throw new NotFoundInDBException($"Well project with id {wellProjectId} not found."); - _mapperService.MapToEntity(updatedWellProjectDto, existingWellProject, wellProjectId); + mapperService.MapToEntity(updatedWellProjectDto, existingWellProject, wellProjectId); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update well project with id {wellProjectId} for case id {caseId}.", wellProjectId, caseId); + logger.LogError(ex, "Failed to update well project with id {wellProjectId} for case id {caseId}.", wellProjectId, caseId); throw; } - var dto = _mapperService.MapToDto(existingWellProject, wellProjectId); + var dto = mapperService.MapToDto(existingWellProject, wellProjectId); return dto; } @@ -77,31 +62,31 @@ public async Task UpdateWellProjectWellDrillingSchedule( UpdateDrillingScheduleDto updatedWellProjectWellDto ) { - var existingWellProject = await _repository.GetWellProjectWithDrillingSchedule(drillingScheduleId) + var existingWellProject = await repository.GetWellProjectWithDrillingSchedule(drillingScheduleId) ?? throw new NotFoundInDBException($"No wellproject connected to {drillingScheduleId} found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingWellProject.Id); + await projectAccessService.ProjectExists(projectId, existingWellProject.Id); var existingDrillingSchedule = existingWellProject.WellProjectWells?.FirstOrDefault(w => w.WellId == wellId)?.DrillingSchedule ?? throw new NotFoundInDBException($"Drilling schedule with {drillingScheduleId} not found."); - _mapperService.MapToEntity(updatedWellProjectWellDto, existingDrillingSchedule, drillingScheduleId); + mapperService.MapToEntity(updatedWellProjectWellDto, existingDrillingSchedule, drillingScheduleId); // DrillingSchedule updatedDrillingSchedule; try { // updatedDrillingSchedule = _repository.UpdateWellProjectWellDrillingSchedule(existingDrillingSchedule); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update drilling schedule with id {drillingScheduleId}", drillingScheduleId); + logger.LogError(ex, "Failed to update drilling schedule with id {drillingScheduleId}", drillingScheduleId); throw; } - var dto = _mapperService.MapToDto(existingDrillingSchedule, drillingScheduleId); + var dto = mapperService.MapToDto(existingDrillingSchedule, drillingScheduleId); return dto; } @@ -114,16 +99,16 @@ CreateDrillingScheduleDto updatedWellProjectWellDto ) { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, wellProjectId); + await projectAccessService.ProjectExists(projectId, wellProjectId); - var existingWellProject = await _repository.GetWellProject(wellProjectId) + var existingWellProject = await repository.GetWellProject(wellProjectId) ?? throw new NotFoundInDBException($"Well project with {wellProjectId} not found."); - var existingWell = await _repository.GetWell(wellId) + var existingWell = await repository.GetWell(wellId) ?? throw new NotFoundInDBException($"Well with {wellId} not found."); DrillingSchedule drillingSchedule = new(); - var newDrillingSchedule = _mapperService.MapToEntity(updatedWellProjectWellDto, drillingSchedule, wellProjectId); + var newDrillingSchedule = mapperService.MapToEntity(updatedWellProjectWellDto, drillingSchedule, wellProjectId); WellProjectWell newWellProjectWell = new() { @@ -135,13 +120,13 @@ CreateDrillingScheduleDto updatedWellProjectWellDto WellProjectWell createdWellProjectWell; try { - createdWellProjectWell = _repository.CreateWellProjectWellDrillingSchedule(newWellProjectWell); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + createdWellProjectWell = repository.CreateWellProjectWellDrillingSchedule(newWellProjectWell); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update drilling schedule with id {drillingScheduleId}", wellProjectId); + logger.LogError(ex, "Failed to update drilling schedule with id {drillingScheduleId}", wellProjectId); throw; } @@ -151,7 +136,7 @@ CreateDrillingScheduleDto updatedWellProjectWellDto throw new Exception(nameof(createdWellProjectWell.DrillingSchedule)); } - var dto = _mapperService.MapToDto(createdWellProjectWell.DrillingSchedule, wellProjectId); + var dto = mapperService.MapToDto(createdWellProjectWell.DrillingSchedule, wellProjectId); return dto; } } diff --git a/backend/api/Services/Entities/WellProject/WellProjectTimeSeriesService.cs b/backend/api/Services/Entities/WellProject/WellProjectTimeSeriesService.cs index ba87a4a35..2231db86a 100644 --- a/backend/api/Services/Entities/WellProject/WellProjectTimeSeriesService.cs +++ b/backend/api/Services/Entities/WellProject/WellProjectTimeSeriesService.cs @@ -1,51 +1,22 @@ -using api.Context; using api.Dtos; using api.Enums; using api.Exceptions; using api.Models; using api.Repositories; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class WellProjectTimeSeriesService : IWellProjectTimeSeriesService +public class WellProjectTimeSeriesService( + ILogger logger, + IWellProjectTimeSeriesRepository repository, + IWellProjectRepository wellProjectRepository, + ICaseRepository caseRepository, + IMapperService mapperService, + IProjectAccessService projectAccessService) + : IWellProjectTimeSeriesService { - private readonly DcdDbContext _context; - private readonly IProjectService _projectService; - private readonly IProjectAccessService _projectAccessService; - private readonly ILogger _logger; - private readonly IMapper _mapper; - private readonly IWellProjectTimeSeriesRepository _repository; - private readonly IWellProjectRepository _wellProjectRepository; - private readonly ICaseRepository _caseRepository; - private readonly IMapperService _mapperService; - - public WellProjectTimeSeriesService( - DcdDbContext context, - IProjectService projectService, - ILoggerFactory loggerFactory, - IMapper mapper, - IWellProjectTimeSeriesRepository repository, - IWellProjectRepository wellProjectRepository, - ICaseRepository caseRepository, - IMapperService mapperService, - IProjectAccessService projectAccessService - ) - { - _context = context; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - _mapper = mapper; - _repository = repository; - _wellProjectRepository = wellProjectRepository; - _caseRepository = caseRepository; - _mapperService = mapperService; - _projectAccessService = projectAccessService; - } - public async Task UpdateOilProducerCostProfileOverride( Guid projectId, Guid caseId, @@ -60,8 +31,8 @@ UpdateOilProducerCostProfileOverrideDto updateDto wellProjectId, profileId, updateDto, - _repository.GetOilProducerCostProfileOverride, - _repository.UpdateOilProducerCostProfileOverride + repository.GetOilProducerCostProfileOverride, + repository.UpdateOilProducerCostProfileOverride ); } @@ -79,8 +50,8 @@ UpdateGasProducerCostProfileOverrideDto updateDto wellProjectId, profileId, updateDto, - _repository.GetGasProducerCostProfileOverride, - _repository.UpdateGasProducerCostProfileOverride + repository.GetGasProducerCostProfileOverride, + repository.UpdateGasProducerCostProfileOverride ); } @@ -98,8 +69,8 @@ UpdateWaterInjectorCostProfileOverrideDto updateDto wellProjectId, profileId, updateDto, - _repository.GetWaterInjectorCostProfileOverride, - _repository.UpdateWaterInjectorCostProfileOverride + repository.GetWaterInjectorCostProfileOverride, + repository.UpdateWaterInjectorCostProfileOverride ); } @@ -117,8 +88,8 @@ UpdateGasInjectorCostProfileOverrideDto updateDto wellProjectId, profileId, updateDto, - _repository.GetGasInjectorCostProfileOverride, - _repository.UpdateGasInjectorCostProfileOverride + repository.GetGasInjectorCostProfileOverride, + repository.UpdateGasInjectorCostProfileOverride ); } @@ -134,7 +105,7 @@ CreateOilProducerCostProfileOverrideDto createProfileDto caseId, wellProjectId, createProfileDto, - _repository.CreateOilProducerCostProfileOverride, + repository.CreateOilProducerCostProfileOverride, WellProjectProfileNames.OilProducerCostProfileOverride ); } @@ -151,7 +122,7 @@ CreateGasProducerCostProfileOverrideDto createProfileDto caseId, wellProjectId, createProfileDto, - _repository.CreateGasProducerCostProfileOverride, + repository.CreateGasProducerCostProfileOverride, WellProjectProfileNames.GasProducerCostProfileOverride ); } @@ -168,7 +139,7 @@ CreateWaterInjectorCostProfileOverrideDto createProfileDto caseId, wellProjectId, createProfileDto, - _repository.CreateWaterInjectorCostProfileOverride, + repository.CreateWaterInjectorCostProfileOverride, WellProjectProfileNames.WaterInjectorCostProfileOverride ); } @@ -185,7 +156,7 @@ CreateGasInjectorCostProfileOverrideDto createProfileDto caseId, wellProjectId, createProfileDto, - _repository.CreateGasInjectorCostProfileOverride, + repository.CreateGasInjectorCostProfileOverride, WellProjectProfileNames.GasInjectorCostProfileOverride ); } @@ -207,23 +178,23 @@ Func updateProfile ?? throw new NotFoundInDBException($"Cost profile with id {profileId} not found."); // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, existingProfile.WellProject.Id); + await projectAccessService.ProjectExists(projectId, existingProfile.WellProject.Id); - _mapperService.MapToEntity(updatedProfileDto, existingProfile, wellProjectId); + mapperService.MapToEntity(updatedProfileDto, existingProfile, wellProjectId); try { - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { var profileName = typeof(TProfile).Name; - _logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); + logger.LogError(ex, "Failed to update profile {profileName} with id {profileId} for case id {caseId}.", profileName, profileId, caseId); throw; } - var updatedDto = _mapperService.MapToDto(existingProfile, profileId); + var updatedDto = mapperService.MapToDto(existingProfile, profileId); return updatedDto; } @@ -240,12 +211,12 @@ WellProjectProfileNames profileName where TCreateDto : class { // Need to verify that the project from the URL is the same as the project of the resource - await _projectAccessService.ProjectExists(projectId, wellProjectId); + await projectAccessService.ProjectExists(projectId, wellProjectId); - var wellProject = await _wellProjectRepository.GetWellProject(wellProjectId) + var wellProject = await wellProjectRepository.GetWellProject(wellProjectId) ?? throw new NotFoundInDBException($"Well project with id {wellProjectId} not found."); - var resourceHasProfile = await _wellProjectRepository.WellProjectHasProfile(wellProjectId, profileName); + var resourceHasProfile = await wellProjectRepository.WellProjectHasProfile(wellProjectId, profileName); if (resourceHasProfile) { @@ -257,22 +228,22 @@ WellProjectProfileNames profileName WellProject = wellProject, }; - var newProfile = _mapperService.MapToEntity(createWellProjectProfileDto, profile, wellProjectId); + var newProfile = mapperService.MapToEntity(createWellProjectProfileDto, profile, wellProjectId); TProfile createdProfile; try { createdProfile = createProfile(newProfile); - await _caseRepository.UpdateModifyTime(caseId); - await _repository.SaveChangesAndRecalculateAsync(caseId); + await caseRepository.UpdateModifyTime(caseId); + await repository.SaveChangesAndRecalculateAsync(caseId); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create profile {profileName} for case id {caseId}.", profileName, caseId); + logger.LogError(ex, "Failed to create profile {profileName} for case id {caseId}.", profileName, caseId); throw; } - var updatedDto = _mapperService.MapToDto(createdProfile, createdProfile.Id); + var updatedDto = mapperService.MapToDto(createdProfile, createdProfile.Id); return updatedDto; } } diff --git a/backend/api/Services/Entities/WellProjectWellService.cs b/backend/api/Services/Entities/WellProjectWellService.cs index 6e079c46d..0e50dc07f 100644 --- a/backend/api/Services/Entities/WellProjectWellService.cs +++ b/backend/api/Services/Entities/WellProjectWellService.cs @@ -1,26 +1,15 @@ using api.Context; -using api.Dtos; -using api.Exceptions; using api.Models; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class WellProjectWellService : IWellProjectWellService +public class WellProjectWellService(DcdDbContext context) : IWellProjectWellService { - private readonly DcdDbContext _context; - - public WellProjectWellService(DcdDbContext context) - { - _context = context; - } - public async Task> GetWellProjectWellsForWellProject(Guid wellProjectId) { - return await _context.WellProjectWell! + return await context.WellProjectWell! .Include(wpw => wpw.DrillingSchedule) .Where(w => w.WellProjectId == wellProjectId).ToListAsync(); } diff --git a/backend/api/Services/Entities/WellService.cs b/backend/api/Services/Entities/WellService.cs index b80603630..8bcee453d 100644 --- a/backend/api/Services/Entities/WellService.cs +++ b/backend/api/Services/Entities/WellService.cs @@ -7,26 +7,13 @@ namespace api.Services; -public class WellService : IWellService +public class WellService( + ILogger logger, + IWellRepository repository, + IMapperService mapperService, + IProjectRepository projectRepository) + : IWellService { - private readonly IWellRepository _repository; - private readonly IProjectRepository _projectRepository; - private readonly ILogger _logger; - private readonly IMapperService _mapperService; - - public WellService( - ILoggerFactory loggerFactory, - IWellRepository repository, - IMapperService mapperService, - IProjectRepository projectRepository - ) - { - _logger = loggerFactory.CreateLogger(); - _repository = repository; - _mapperService = mapperService; - _projectRepository = projectRepository; - } - private static bool UpdateChangesWellType(Well well, UpdateWellDto updatedWellDto) { var isWellProjectWell = Well.IsWellProjectWell(well.WellCategory); @@ -50,7 +37,7 @@ public async Task UpdateWell(Guid projectId, Guid wellId, UpdateWellDto { - var existingWell = await _repository.GetWell(wellId) + var existingWell = await repository.GetWell(wellId) ?? throw new NotFoundInDBException($"Well with id {wellId} not found"); if (InvalidWellCategory(updatedWellDto)) @@ -63,26 +50,26 @@ public async Task UpdateWell(Guid projectId, Guid wellId, UpdateWellDto throw new WellChangeTypeException("Cannot change well type", wellId); } - _mapperService.MapToEntity(updatedWellDto, existingWell, wellId); + mapperService.MapToEntity(updatedWellDto, existingWell, wellId); try { - await _projectRepository.UpdateModifyTime(projectId); - await _repository.SaveChangesAsync(); // TODO: run calculations + await projectRepository.UpdateModifyTime(projectId); + await repository.SaveChangesAsync(); // TODO: run calculations } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to update well with id {wellId}", wellId); + logger.LogError(ex, "Failed to update well with id {wellId}", wellId); throw; } - var dto = _mapperService.MapToDto(existingWell, wellId); + var dto = mapperService.MapToDto(existingWell, wellId); return dto; } public async Task CreateWell(Guid projectId, CreateWellDto createWellDto) { - var project = await _projectRepository.GetProject(projectId) + var project = await projectRepository.GetProject(projectId) ?? throw new NotFoundInDBException($"Project with id {projectId} not found"); Well well = new() @@ -90,46 +77,46 @@ public async Task CreateWell(Guid projectId, CreateWellDto createWellDt Project = project }; - var newWell = _mapperService.MapToEntity(createWellDto, well, projectId); + var newWell = mapperService.MapToEntity(createWellDto, well, projectId); Well createdWell; try { - createdWell = _repository.AddWell(newWell); - await _projectRepository.UpdateModifyTime(projectId); - await _repository.SaveChangesAsync(); + createdWell = repository.AddWell(newWell); + await projectRepository.UpdateModifyTime(projectId); + await repository.SaveChangesAsync(); } catch (DbUpdateException ex) { - _logger.LogError(ex, "Failed to create well"); + logger.LogError(ex, "Failed to create well"); throw; } - var dto = _mapperService.MapToDto(createdWell, createdWell.Id); + var dto = mapperService.MapToDto(createdWell, createdWell.Id); return dto; } public async Task DeleteWell(Guid projectId, Guid wellId) { - var well = await _repository.GetWell(wellId) + var well = await repository.GetWell(wellId) ?? throw new NotFoundInDBException($"Well with id {wellId} not found"); - _repository.DeleteWell(well); - await _projectRepository.UpdateModifyTime(projectId); - await _repository.SaveChangesAsync(); // TODO: Run calculations + repository.DeleteWell(well); + await projectRepository.UpdateModifyTime(projectId); + await repository.SaveChangesAsync(); // TODO: Run calculations } public async Task> GetAffectedCases(Guid wellId) { - _ = await _repository.GetWell(wellId) + _ = await repository.GetWell(wellId) ?? throw new NotFoundInDBException($"Well with id {wellId} not found"); - var cases = await _repository.GetCasesAffectedByDeleteWell(wellId); + var cases = await repository.GetCasesAffectedByDeleteWell(wellId); var dtos = new List(); foreach (var c in cases) { - var dto = _mapperService.MapToDto(c, c.Id); + var dto = mapperService.MapToDto(c, c.Id); dtos.Add(dto); } return dtos; diff --git a/backend/api/Services/Fusion/FusionPeopleService.cs b/backend/api/Services/Fusion/FusionPeopleService.cs index d66be3b00..298189dc5 100644 --- a/backend/api/Services/Fusion/FusionPeopleService.cs +++ b/backend/api/Services/Fusion/FusionPeopleService.cs @@ -2,7 +2,6 @@ using Fusion.Integration; -using Microsoft.Extensions.Caching.Memory; using Microsoft.Identity.Abstractions; namespace api.Services; @@ -12,23 +11,13 @@ public interface IFusionPeopleService Task> GetAllPersonsOnProject(Guid projectMasterId, string search, int top, int skip); } -public class FusionPeopleService : IFusionPeopleService +public class FusionPeopleService( + IDownstreamApi downstreamApi, + IFusionContextResolver fusionContextResolver) : IFusionPeopleService { - private readonly IDownstreamApi _downstreamApi; - private readonly IFusionContextResolver _fusionContextResolver; - - - public FusionPeopleService( - IDownstreamApi downstreamApi, - IFusionContextResolver fusionContextResolver) - { - _downstreamApi = downstreamApi; - _fusionContextResolver = fusionContextResolver; - } - public async Task> GetAllPersonsOnProject(Guid fusionContextId, string search, int top, int skip) { - var contextRelations = await _fusionContextResolver.GetContextRelationsAsync(fusionContextId); + var contextRelations = await fusionContextResolver.GetContextRelationsAsync(fusionContextId); string? orgChartId = contextRelations.FirstOrDefault(x => x.Type == FusionContextType.OrgChart)?.ExternalId?.ToString(); @@ -64,7 +53,7 @@ private static FusionSearchObject BuildFusionSearchObject(string orgChartId, str public async Task> QueryFusionPeopleService(FusionSearchObject fusionSearchObject) { - var response = await _downstreamApi.PostForUserAsync( + var response = await downstreamApi.PostForUserAsync( "FusionPeople", fusionSearchObject, opt => opt.RelativePath = "search/persons/query?api-version=1.0"); diff --git a/backend/api/Services/GenerateCostProfiles/CessationCostProfileService.cs b/backend/api/Services/GenerateCostProfiles/CessationCostProfileService.cs index 118e7d401..5200a141d 100644 --- a/backend/api/Services/GenerateCostProfiles/CessationCostProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/CessationCostProfileService.cs @@ -1,41 +1,18 @@ using api.Models; -using AutoMapper; - namespace api.Services; -public class CessationCostProfileService : ICessationCostProfileService +public class CessationCostProfileService( + ICaseService caseService, + IDrainageStrategyService drainageStrategyService, + IWellProjectWellService wellProjectWellService, + ISurfService surfService, + IProjectService projectService) + : ICessationCostProfileService { - private readonly ICaseService _caseService; - private readonly ILogger _logger; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IWellProjectService _wellProjectService; - private readonly IWellProjectWellService _wellProjectWellService; - private readonly ISurfService _surfService; - private readonly IProjectService _projectService; - - public CessationCostProfileService( - ILoggerFactory loggerFactory, - ICaseService caseService, - IDrainageStrategyService drainageStrategyService, - IWellProjectService wellProjectService, - IWellProjectWellService wellProjectWellService, - ISurfService surfService, - IProjectService projectService - ) - { - _logger = loggerFactory.CreateLogger(); - _caseService = caseService; - _drainageStrategyService = drainageStrategyService; - _wellProjectService = wellProjectService; - _wellProjectWellService = wellProjectWellService; - _surfService = surfService; - _projectService = projectService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes( caseId, c => c.CessationWellsCostOverride!, c => c.CessationWellsCost!, @@ -43,7 +20,7 @@ public async Task Generate(Guid caseId) c => c.CessationOffshoreFacilitiesCost! ); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.ProductionProfileOil!, d => d.AdditionalProductionProfileOil!, @@ -53,7 +30,7 @@ public async Task Generate(Guid caseId) var lastYearOfProduction = CalculationHelper.GetRelativeLastYearOfProduction(drainageStrategy); - var project = await _projectService.GetProjectWithoutAssets(caseItem.ProjectId); + var project = await projectService.GetProjectWithoutAssets(caseItem.ProjectId); await CalculateCessationWellsCost(caseItem, project, lastYearOfProduction); await GetCessationOffshoreFacilitiesCost(caseItem, lastYearOfProduction); @@ -93,7 +70,7 @@ private async Task GetCessationOffshoreFacilitiesCost(Case caseItem, int? lastYe return; } - var surf = await _surfService.GetSurfWithIncludes(caseItem.SurfLink); + var surf = await surfService.GetSurfWithIncludes(caseItem.SurfLink); caseItem.CessationOffshoreFacilitiesCost = GenerateCessationOffshoreFacilitiesCost( surf, lastYear.Value, @@ -103,7 +80,7 @@ private async Task GetCessationOffshoreFacilitiesCost(Case caseItem, int? lastYe private async Task GenerateCessationWellsCost(Guid wellProjectId, Project project, int lastYear, CessationWellsCost cessationWells) { - var linkedWells = await _wellProjectWellService.GetWellProjectWellsForWellProject(wellProjectId); + var linkedWells = await wellProjectWellService.GetWellProjectWellsForWellProject(wellProjectId); if (linkedWells == null) { return cessationWells; diff --git a/backend/api/Services/GenerateCostProfiles/Co2DrillingFlaringFuelTotalsService.cs b/backend/api/Services/GenerateCostProfiles/Co2DrillingFlaringFuelTotalsService.cs index c1fd8c7c5..18f0ea443 100644 --- a/backend/api/Services/GenerateCostProfiles/Co2DrillingFlaringFuelTotalsService.cs +++ b/backend/api/Services/GenerateCostProfiles/Co2DrillingFlaringFuelTotalsService.cs @@ -1,42 +1,23 @@ -using api.Adapters; using api.Dtos; using api.Helpers; using api.Models; namespace api.Services.GenerateCostProfiles; -public class Co2DrillingFlaringFuelTotalsService : ICo2DrillingFlaringFuelTotalsService +public class Co2DrillingFlaringFuelTotalsService( + ICaseService caseService, + IProjectService projectService, + ITopsideService topsideService, + IDrainageStrategyService drainageStrategyService, + IWellProjectWellService wellProjectWellService) + : ICo2DrillingFlaringFuelTotalsService { - private readonly ICaseService _caseService; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IProjectService _projectService; - private readonly ITopsideService _topsideService; - private readonly IWellProjectService _wellProjectService; - private readonly IWellProjectWellService _wellProjectWellService; - - public Co2DrillingFlaringFuelTotalsService( - ICaseService caseService, - IProjectService projectService, - ITopsideService topsideService, - IDrainageStrategyService drainageStrategyService, - IWellProjectService wellProjectService, - IWellProjectWellService wellProjectWellService - ) - { - _caseService = caseService; - _projectService = projectService; - _topsideService = topsideService; - _drainageStrategyService = drainageStrategyService; - _wellProjectService = wellProjectService; - _wellProjectWellService = wellProjectWellService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes(caseId); - var topside = await _topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); - var project = await _projectService.GetProjectWithoutAssets(caseItem.ProjectId); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes(caseId); + var topside = await topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); + var project = await projectService.GetProjectWithoutAssets(caseItem.ProjectId); + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.ProductionProfileOil!, d => d.AdditionalProductionProfileOil!, @@ -91,7 +72,7 @@ DrainageStrategy drainageStrategy private async Task CalculateDrillingEmissionsTotal(Project project, Guid wellProjectId) { - var linkedWells = await _wellProjectWellService.GetWellProjectWellsForWellProject(wellProjectId); + var linkedWells = await wellProjectWellService.GetWellProjectWellsForWellProject(wellProjectId); if (linkedWells == null) { return 0.0; diff --git a/backend/api/Services/GenerateCostProfiles/Co2EmissionsProfileService.cs b/backend/api/Services/GenerateCostProfiles/Co2EmissionsProfileService.cs index 34e73505b..be5c557c2 100644 --- a/backend/api/Services/GenerateCostProfiles/Co2EmissionsProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/Co2EmissionsProfileService.cs @@ -1,40 +1,20 @@ -using api.Adapters; -using api.Context; -using api.Dtos; using api.Helpers; using api.Models; -using AutoMapper; - namespace api.Services.GenerateCostProfiles; -public class Co2EmissionsProfileService : ICo2EmissionsProfileService +public class Co2EmissionsProfileService( + ICaseService caseService, + IDrainageStrategyService drainageStrategyService, + IProjectService projectService, + ITopsideService topsideService, + IWellProjectWellService wellProjectWellService) + : ICo2EmissionsProfileService { - private readonly ICaseService _caseService; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IProjectService _projectService; - private readonly ITopsideService _topsideService; - private readonly IWellProjectWellService _wellProjectWellService; - - public Co2EmissionsProfileService( - ICaseService caseService, - IDrainageStrategyService drainageStrategyService, - IProjectService projectService, - ITopsideService topsideService, - IWellProjectWellService wellProjectWellService - ) - { - _caseService = caseService; - _projectService = projectService; - _topsideService = topsideService; - _drainageStrategyService = drainageStrategyService; - _wellProjectWellService = wellProjectWellService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes(caseId); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes(caseId); + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.ProductionProfileOil!, d => d.AdditionalProductionProfileOil!, @@ -49,8 +29,8 @@ public async Task Generate(Guid caseId) return; } - var topside = await _topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); - var project = await _projectService.GetProjectWithoutAssets(caseItem.ProjectId); + var topside = await topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); + var project = await projectService.GetProjectWithoutAssets(caseItem.ProjectId); var fuelConsumptionsProfile = GetFuelConsumptionsProfile(project, caseItem, topside, drainageStrategy); var flaringsProfile = GetFlaringsProfile(project, drainageStrategy); @@ -131,7 +111,7 @@ DrainageStrategy drainageStrategy private async Task CalculateDrillingEmissions(Project project, Guid wellProjectId) { - var linkedWells = await _wellProjectWellService.GetWellProjectWellsForWellProject(wellProjectId); + var linkedWells = await wellProjectWellService.GetWellProjectWellsForWellProject(wellProjectId); if (linkedWells == null) { return new TimeSeriesVolume(); diff --git a/backend/api/Services/GenerateCostProfiles/Co2IntensityProfileService.cs b/backend/api/Services/GenerateCostProfiles/Co2IntensityProfileService.cs index 0db01b0aa..e6b199ede 100644 --- a/backend/api/Services/GenerateCostProfiles/Co2IntensityProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/Co2IntensityProfileService.cs @@ -1,40 +1,22 @@ -using api.Adapters; using api.Dtos; -using api.Helpers; using api.Models; using AutoMapper; namespace api.Services.GenerateCostProfiles; -public class Co2IntensityProfileService : ICo2IntensityProfileService +public class Co2IntensityProfileService( + ICaseService caseService, + IDrainageStrategyService drainageStrategyService, + IProjectService projectService, + IMapper mapper) + : ICo2IntensityProfileService { - private readonly ICaseService _caseService; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IProjectService _projectService; - private readonly ICo2EmissionsProfileService _generateCo2EmissionsProfile; - private readonly IMapper _mapper; - - public Co2IntensityProfileService( - ICaseService caseService, - IDrainageStrategyService drainageStrategyService, - IProjectService projectService, - ICo2EmissionsProfileService generateCo2EmissionsProfile, - IMapper mapper - ) - { - _caseService = caseService; - _projectService = projectService; - _drainageStrategyService = drainageStrategyService; - _generateCo2EmissionsProfile = generateCo2EmissionsProfile; - _mapper = mapper; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCase(caseId); - var project = await _projectService.GetProjectWithoutAssets(caseItem.ProjectId); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var caseItem = await caseService.GetCase(caseId); + var project = await projectService.GetProjectWithoutAssets(caseItem.ProjectId); + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.Co2Emissions!, d => d.Co2EmissionsOverride!, @@ -87,7 +69,7 @@ public async Task Generate(Guid caseId) Values = co2IntensityValues.ToArray(), }; - var dto = _mapper.Map(co2Intensity); + var dto = mapper.Map(co2Intensity); return dto ?? new Co2IntensityDto(); } diff --git a/backend/api/Services/GenerateCostProfiles/Co2IntensityTotalService.cs b/backend/api/Services/GenerateCostProfiles/Co2IntensityTotalService.cs index 60e0db21b..a13e1c166 100644 --- a/backend/api/Services/GenerateCostProfiles/Co2IntensityTotalService.cs +++ b/backend/api/Services/GenerateCostProfiles/Co2IntensityTotalService.cs @@ -4,31 +4,18 @@ namespace api.Services.GenerateCostProfiles; -public class Co2IntensityTotalService : ICo2IntensityTotalService +public class Co2IntensityTotalService( + IProjectService projectService, + ILogger logger, + ICaseService caseService, + IDrainageStrategyService drainageStrategyService) + : ICo2IntensityTotalService { - private readonly ICaseService _caseService; - private readonly IProjectService _projectService; - private readonly ILogger _logger; - private readonly IDrainageStrategyService _drainageStrategyService; - - public Co2IntensityTotalService( - IProjectService projectService, - ILoggerFactory loggerFactory, - ICaseService caseService, - IDrainageStrategyService drainageStrategyService - ) - { - _caseService = caseService; - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - _drainageStrategyService = drainageStrategyService; - } - public async Task Calculate(Guid caseId) { - var caseItem = await _caseService.GetCase(caseId); - var project = await _projectService.GetProjectWithCasesAndAssets(caseItem.ProjectId); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var caseItem = await caseService.GetCase(caseId); + var project = await projectService.GetProjectWithCasesAndAssets(caseItem.ProjectId); + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.Co2Emissions!, d => d.Co2EmissionsOverride!, @@ -71,7 +58,7 @@ private double CalculateTotalOilProduction(Case caseItem, Project project, Drain } catch (ArgumentException) { - _logger.LogInformation("DrainageStrategy {0} not found.", caseItem.DrainageStrategyLink); + logger.LogInformation("DrainageStrategy {0} not found.", caseItem.DrainageStrategyLink); } if (project.PhysicalUnit != 0 && !excludeOilFieldConversion) @@ -100,7 +87,7 @@ private double CalculateTotalGasProduction(Case caseItem, Project project, Drain } catch (ArgumentException) { - _logger.LogInformation("DrainageStrategy {0} not found.", caseItem.DrainageStrategyLink); + logger.LogInformation("DrainageStrategy {0} not found.", caseItem.DrainageStrategyLink); } if (project.PhysicalUnit != 0 && !excludeOilFieldConversion) diff --git a/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateBreakEvenOilPriceService.cs b/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateBreakEvenOilPriceService.cs index 9d0a019fb..9587b9b00 100644 --- a/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateBreakEvenOilPriceService.cs +++ b/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateBreakEvenOilPriceService.cs @@ -1,29 +1,17 @@ -using api.Models; - namespace api.Services.EconomicsServices; -public class CalculateBreakEvenOilPriceService : ICalculateBreakEvenOilPriceService +public class CalculateBreakEvenOilPriceService( + ICaseService caseService, + IDrainageStrategyService drainageStrategyService) : ICalculateBreakEvenOilPriceService { - private readonly ICaseService _caseService; - private readonly IDrainageStrategyService _drainageStrategyService; - - public CalculateBreakEvenOilPriceService( - ICaseService caseService, - IDrainageStrategyService drainageStrategyService - ) - { - _caseService = caseService; - _drainageStrategyService = drainageStrategyService; - } - public async Task CalculateBreakEvenOilPrice(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes( caseId, c => c.Project ); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.ProductionProfileOil!, d => d.AdditionalProductionProfileOil!, diff --git a/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateNPVService.cs b/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateNPVService.cs index 3f50f1ad4..9b8f18fd5 100644 --- a/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateNPVService.cs +++ b/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateNPVService.cs @@ -2,15 +2,8 @@ namespace api.Services.EconomicsServices; -public class CalculateNPVService : ICalculateNPVService +public class CalculateNPVService(ICaseService caseService) : ICalculateNPVService { - private readonly ICaseService _caseService; - - public CalculateNPVService(ICaseService caseService) - { - _caseService = caseService; - } - private static TimeSeries? GetCashflowProfile(Case caseItem) { if (caseItem.CalculatedTotalIncomeCostProfile == null || caseItem.CalculatedTotalCostCostProfile == null) @@ -23,7 +16,7 @@ public CalculateNPVService(ICaseService caseService) public async Task CalculateNPV(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes( caseId, c => c.Project, c => c.CalculatedTotalIncomeCostProfile!, diff --git a/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateTotalCostService.cs b/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateTotalCostService.cs index 0ee0d58de..06994c166 100644 --- a/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateTotalCostService.cs +++ b/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateTotalCostService.cs @@ -1,40 +1,20 @@ using api.Models; -using api.Services; namespace api.Services.EconomicsServices; -public class CalculateTotalCostService : ICalculateTotalCostService +public class CalculateTotalCostService( + ICaseService caseService, + ISubstructureService substructureService, + ISurfService surfService, + ITopsideService topsideService, + ITransportService transportService, + IWellProjectService wellProjectService, + IExplorationService explorationService) + : ICalculateTotalCostService { - private readonly ICaseService _caseService; - private readonly ISubstructureService _substructureService; - private readonly ISurfService _surfService; - private readonly ITopsideService _topsideService; - private readonly ITransportService _transportService; - private readonly IWellProjectService _wellProjectService; - private readonly IExplorationService _explorationService; - - public CalculateTotalCostService( - ICaseService caseService, - ISubstructureService substructureService, - ISurfService surfService, - ITopsideService topsideService, - ITransportService transportService, - IWellProjectService wellProjectService, - IExplorationService explorationService) - { - _caseService = caseService; - _substructureService = substructureService; - _surfService = surfService; - _topsideService = topsideService; - _transportService = transportService; - _explorationService = explorationService; - _wellProjectService = wellProjectService; - } - - public async Task CalculateTotalCost(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes( caseId, c => c.TotalFeasibilityAndConceptStudies!, c => c.TotalFeasibilityAndConceptStudiesOverride!, @@ -77,25 +57,25 @@ public async Task CalculateTotalCost(Guid caseId) Values = totalCessationCost.Values ?? [] }; - var substructure = await _substructureService.GetSubstructureWithIncludes( + var substructure = await substructureService.GetSubstructureWithIncludes( caseItem.SubstructureLink, s => s.CostProfileOverride!, s => s.CostProfile! ); - var surf = await _surfService.GetSurfWithIncludes( + var surf = await surfService.GetSurfWithIncludes( caseItem.SurfLink, s => s.CostProfileOverride!, s => s.CostProfile! ); - var topside = await _topsideService.GetTopsideWithIncludes( + var topside = await topsideService.GetTopsideWithIncludes( caseItem.TopsideLink, t => t.CostProfileOverride!, t => t.CostProfile! ); - var transport = await _transportService.GetTransportWithIncludes( + var transport = await transportService.GetTransportWithIncludes( caseItem.TransportLink, t => t.CostProfileOverride!, t => t.CostProfile! @@ -108,7 +88,7 @@ public async Task CalculateTotalCost(Guid caseId) Values = totalOffshoreFacilityCost.Values }; - var wellProject = await _wellProjectService.GetWellProjectWithIncludes( + var wellProject = await wellProjectService.GetWellProjectWithIncludes( caseItem.WellProjectLink, w => w.OilProducerCostProfileOverride!, w => w.OilProducerCostProfile!, @@ -127,7 +107,7 @@ public async Task CalculateTotalCost(Guid caseId) Values = totalDevelopmentCost.Values }; - var exploration = await _explorationService.GetExplorationWithIncludes( + var exploration = await explorationService.GetExplorationWithIncludes( caseItem.ExplorationLink, e => e.GAndGAdminCost!, e => e.CountryOfficeCost!, diff --git a/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateTotalIncomeService.cs b/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateTotalIncomeService.cs index a88bcaf6b..2f09180f8 100644 --- a/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateTotalIncomeService.cs +++ b/backend/api/Services/GenerateCostProfiles/EconomicsServices/CalculateTotalIncomeService.cs @@ -2,25 +2,16 @@ namespace api.Services.EconomicsServices; -public class CalculateTotalIncomeService : ICalculateTotalIncomeService +public class CalculateTotalIncomeService(ICaseService caseService, IDrainageStrategyService drainageStrategyService) : ICalculateTotalIncomeService { - private readonly ICaseService _caseService; - private readonly IDrainageStrategyService _drainageStrategyService; - - public CalculateTotalIncomeService(ICaseService caseService, IDrainageStrategyService drainageStrategyService) - { - _caseService = caseService; - _drainageStrategyService = drainageStrategyService; - } - public async Task CalculateTotalIncome(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes( caseId, c => c.Project ); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.ProductionProfileGas!, d => d.AdditionalProductionProfileGas!, diff --git a/backend/api/Services/GenerateCostProfiles/EconomicsServices/EconomicsHelper.cs b/backend/api/Services/GenerateCostProfiles/EconomicsServices/EconomicsHelper.cs index 93f33cf21..1e263c694 100644 --- a/backend/api/Services/GenerateCostProfiles/EconomicsServices/EconomicsHelper.cs +++ b/backend/api/Services/GenerateCostProfiles/EconomicsServices/EconomicsHelper.cs @@ -4,7 +4,6 @@ namespace api.Services.EconomicsServices; public static class EconomicsHelper { - public static double CalculateDiscountedVolume(double[] values, double discountRate, int startIndex) { double accumulatedVolume = 0; diff --git a/backend/api/Services/GenerateCostProfiles/EconomicsServices/ICalculateTotalCostService.cs b/backend/api/Services/GenerateCostProfiles/EconomicsServices/ICalculateTotalCostService.cs index 81b6104e7..508cc25f4 100644 --- a/backend/api/Services/GenerateCostProfiles/EconomicsServices/ICalculateTotalCostService.cs +++ b/backend/api/Services/GenerateCostProfiles/EconomicsServices/ICalculateTotalCostService.cs @@ -1,5 +1,3 @@ -using api.Dtos; - namespace api.Services.EconomicsServices; public interface ICalculateTotalCostService diff --git a/backend/api/Services/GenerateCostProfiles/EconomicsServices/ICalculateTotalIncomeService.cs b/backend/api/Services/GenerateCostProfiles/EconomicsServices/ICalculateTotalIncomeService.cs index 4ec59eb53..331a97532 100644 --- a/backend/api/Services/GenerateCostProfiles/EconomicsServices/ICalculateTotalIncomeService.cs +++ b/backend/api/Services/GenerateCostProfiles/EconomicsServices/ICalculateTotalIncomeService.cs @@ -1,5 +1,3 @@ -using api.Dtos; - namespace api.Services.EconomicsServices; public interface ICalculateTotalIncomeService diff --git a/backend/api/Services/GenerateCostProfiles/FuelFlaringLossesProfileService.cs b/backend/api/Services/GenerateCostProfiles/FuelFlaringLossesProfileService.cs index 5f2c41d4f..cb0e0cec3 100644 --- a/backend/api/Services/GenerateCostProfiles/FuelFlaringLossesProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/FuelFlaringLossesProfileService.cs @@ -1,35 +1,19 @@ -using api.Context; using api.Helpers; using api.Models; -using AutoMapper; - namespace api.Services.GenerateCostProfiles; -public class FuelFlaringLossesProfileService : IFuelFlaringLossesProfileService +public class FuelFlaringLossesProfileService( + ICaseService caseService, + IProjectService projectService, + ITopsideService topsideService, + IDrainageStrategyService drainageStrategyService) + : IFuelFlaringLossesProfileService { - private readonly ICaseService _caseService; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IProjectService _projectService; - private readonly ITopsideService _topsideService; - - public FuelFlaringLossesProfileService( - ICaseService caseService, - IProjectService projectService, - ITopsideService topsideService, - IDrainageStrategyService drainageStrategyService - ) - { - _caseService = caseService; - _projectService = projectService; - _topsideService = topsideService; - _drainageStrategyService = drainageStrategyService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes(caseId); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes(caseId); + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.FuelFlaringAndLosses!, d => d.FuelFlaringAndLossesOverride!, @@ -45,8 +29,8 @@ public async Task Generate(Guid caseId) return; } - var topside = await _topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); - var project = await _projectService.GetProjectWithoutAssets(caseItem.ProjectId); + var topside = await topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); + var project = await projectService.GetProjectWithoutAssets(caseItem.ProjectId); var fuelConsumptions = EmissionCalculationHelper.CalculateTotalFuelConsumptions(caseItem, topside, drainageStrategy); var flaring = EmissionCalculationHelper.CalculateFlaring(project, drainageStrategy); diff --git a/backend/api/Services/GenerateCostProfiles/GenerateGAndGAdminCostProfile.cs b/backend/api/Services/GenerateCostProfiles/GenerateGAndGAdminCostProfile.cs index d667f8a62..a375e2918 100644 --- a/backend/api/Services/GenerateCostProfiles/GenerateGAndGAdminCostProfile.cs +++ b/backend/api/Services/GenerateCostProfiles/GenerateGAndGAdminCostProfile.cs @@ -5,34 +5,18 @@ namespace api.Services; -public class GenerateGAndGAdminCostProfile : IGenerateGAndGAdminCostProfile +public class GenerateGAndGAdminCostProfile( + IProjectService projectService, + ICaseService caseService, + IExplorationService explorationService, + IExplorationWellService explorationWellService) + : IGenerateGAndGAdminCostProfile { - private readonly IProjectService _projectService; - private readonly ICaseService _caseService; - private readonly ILogger _logger; - private readonly IExplorationService _explorationService; - private readonly IExplorationWellService _explorationWellService; - - public GenerateGAndGAdminCostProfile( - ILoggerFactory loggerFactory, - IProjectService projectService, - ICaseService caseService, - IExplorationService explorationService, - IExplorationWellService explorationWellService - ) - { - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - _caseService = caseService; - _explorationService = explorationService; - _explorationWellService = explorationWellService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes(caseId); + var caseItem = await caseService.GetCaseWithIncludes(caseId); - var exploration = await _explorationService.GetExplorationWithIncludes( + var exploration = await explorationService.GetExplorationWithIncludes( caseItem.ExplorationLink, e => e.GAndGAdminCost!, e => e.GAndGAdminCostOverride! @@ -43,7 +27,7 @@ public async Task Generate(Guid caseId) return; } - var linkedWells = await _explorationWellService.GetExplorationWellsForExploration(exploration.Id); + var linkedWells = await explorationWellService.GetExplorationWellsForExploration(exploration.Id); if (linkedWells?.Count > 0) { var drillingSchedules = linkedWells.Select(lw => lw.DrillingSchedule); @@ -51,7 +35,7 @@ public async Task Generate(Guid caseId) var dG1Date = caseItem.DG1Date; if (earliestYear != null && dG1Date.Year >= earliestYear) { - var project = await _projectService.GetProject(caseItem.ProjectId); + var project = await projectService.GetProject(caseItem.ProjectId); var countryCost = MapCountry(project.Country); var lastYear = new DateTimeOffset(dG1Date.Year, 1, 1, 0, 0, 0, 0, new GregorianCalendar(), TimeSpan.Zero); var lastYearMinutes = (dG1Date - lastYear).TotalMinutes; diff --git a/backend/api/Services/GenerateCostProfiles/ICessationCostProfileService.cs b/backend/api/Services/GenerateCostProfiles/ICessationCostProfileService.cs index 903bfd122..70e5c3089 100644 --- a/backend/api/Services/GenerateCostProfiles/ICessationCostProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/ICessationCostProfileService.cs @@ -1,5 +1,3 @@ -using api.Dtos; - namespace api.Services { public interface ICessationCostProfileService diff --git a/backend/api/Services/GenerateCostProfiles/ICo2EmissionsProfileService.cs b/backend/api/Services/GenerateCostProfiles/ICo2EmissionsProfileService.cs index 2cb500268..a1fc5b1a7 100644 --- a/backend/api/Services/GenerateCostProfiles/ICo2EmissionsProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/ICo2EmissionsProfileService.cs @@ -1,5 +1,3 @@ -using api.Dtos; - namespace api.Services.GenerateCostProfiles { public interface ICo2EmissionsProfileService diff --git a/backend/api/Services/GenerateCostProfiles/IGenerateGAndGAdminCostProfile.cs b/backend/api/Services/GenerateCostProfiles/IGenerateGAndGAdminCostProfile.cs index 10f1d477d..0e6ed17ef 100644 --- a/backend/api/Services/GenerateCostProfiles/IGenerateGAndGAdminCostProfile.cs +++ b/backend/api/Services/GenerateCostProfiles/IGenerateGAndGAdminCostProfile.cs @@ -1,5 +1,3 @@ -using api.Dtos; - namespace api.Services { public interface IGenerateGAndGAdminCostProfile diff --git a/backend/api/Services/GenerateCostProfiles/INetSaleGasProfileService.cs b/backend/api/Services/GenerateCostProfiles/INetSaleGasProfileService.cs index 68c646d9a..cb46775f6 100644 --- a/backend/api/Services/GenerateCostProfiles/INetSaleGasProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/INetSaleGasProfileService.cs @@ -1,5 +1,3 @@ -using api.Dtos; - namespace api.Services.GenerateCostProfiles { public interface INetSaleGasProfileService diff --git a/backend/api/Services/GenerateCostProfiles/IOpexCostProfileService.cs b/backend/api/Services/GenerateCostProfiles/IOpexCostProfileService.cs index ab738b93f..50fd7a88a 100644 --- a/backend/api/Services/GenerateCostProfiles/IOpexCostProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/IOpexCostProfileService.cs @@ -1,6 +1,3 @@ -using api.Dtos; -using api.Models; - namespace api.Services { public interface IOpexCostProfileService diff --git a/backend/api/Services/GenerateCostProfiles/IStudyCostProfileService.cs b/backend/api/Services/GenerateCostProfiles/IStudyCostProfileService.cs index 84b7a1533..476007849 100644 --- a/backend/api/Services/GenerateCostProfiles/IStudyCostProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/IStudyCostProfileService.cs @@ -1,4 +1,3 @@ -using api.Dtos; using api.Models; namespace api.Services diff --git a/backend/api/Services/GenerateCostProfiles/IWellCostProfileService.cs b/backend/api/Services/GenerateCostProfiles/IWellCostProfileService.cs index 0882390bb..ecd55c7d7 100644 --- a/backend/api/Services/GenerateCostProfiles/IWellCostProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/IWellCostProfileService.cs @@ -1,4 +1,3 @@ -using api.Dtos; using api.Models; namespace api.Services; diff --git a/backend/api/Services/GenerateCostProfiles/ImportedElectricityProfileService.cs b/backend/api/Services/GenerateCostProfiles/ImportedElectricityProfileService.cs index 1c390fa5d..f76e14af4 100644 --- a/backend/api/Services/GenerateCostProfiles/ImportedElectricityProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/ImportedElectricityProfileService.cs @@ -1,34 +1,18 @@ -using api.Adapters; -using api.Context; -using api.Dtos; using api.Helpers; using api.Models; -using AutoMapper; - namespace api.Services.GenerateCostProfiles; -public class ImportedElectricityProfileService : IImportedElectricityProfileService +public class ImportedElectricityProfileService( + ICaseService caseService, + ITopsideService topsideService, + IDrainageStrategyService drainageStrategyService) + : IImportedElectricityProfileService { - private readonly ICaseService _caseService; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly ITopsideService _topsideService; - - public ImportedElectricityProfileService( - ICaseService caseService, - ITopsideService topsideService, - IDrainageStrategyService drainageStrategyService - ) - { - _caseService = caseService; - _topsideService = topsideService; - _drainageStrategyService = drainageStrategyService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes(caseId); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes(caseId); + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.ImportedElectricity!, d => d.ImportedElectricityOverride!, @@ -44,7 +28,7 @@ public async Task Generate(Guid caseId) return; } - var topside = await _topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); + var topside = await topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); var facilitiesAvailability = caseItem.FacilitiesAvailability; diff --git a/backend/api/Services/GenerateCostProfiles/NetSaleGasProfileService.cs b/backend/api/Services/GenerateCostProfiles/NetSaleGasProfileService.cs index 0ee4b6ddb..4f1d44999 100644 --- a/backend/api/Services/GenerateCostProfiles/NetSaleGasProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/NetSaleGasProfileService.cs @@ -3,30 +3,17 @@ namespace api.Services.GenerateCostProfiles; -public class NetSaleGasProfileService : INetSaleGasProfileService +public class NetSaleGasProfileService( + ICaseService caseService, + IProjectService projectService, + ITopsideService topsideService, + IDrainageStrategyService drainageStrategyService) + : INetSaleGasProfileService { - private readonly ICaseService _caseService; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IProjectService _projectService; - private readonly ITopsideService _topsideService; - - public NetSaleGasProfileService( - ICaseService caseService, - IProjectService projectService, - ITopsideService topsideService, - IDrainageStrategyService drainageStrategyService - ) - { - _caseService = caseService; - _projectService = projectService; - _topsideService = topsideService; - _drainageStrategyService = drainageStrategyService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes(caseId); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes(caseId); + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.NetSalesGas!, d => d.NetSalesGasOverride!, @@ -42,8 +29,8 @@ public async Task Generate(Guid caseId) return; } - var topside = await _topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); - var project = await _projectService.GetProject(caseItem.ProjectId); + var topside = await topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); + var project = await projectService.GetProject(caseItem.ProjectId); var fuelConsumptions = EmissionCalculationHelper.CalculateTotalFuelConsumptions(caseItem, topside, drainageStrategy); var flarings = EmissionCalculationHelper.CalculateFlaring(project, drainageStrategy); diff --git a/backend/api/Services/GenerateCostProfiles/OpexCostProfileService.cs b/backend/api/Services/GenerateCostProfiles/OpexCostProfileService.cs index bf0887fad..1ff143a81 100644 --- a/backend/api/Services/GenerateCostProfiles/OpexCostProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/OpexCostProfileService.cs @@ -1,46 +1,21 @@ -using api.Context; -using api.Dtos; -using api.Exceptions; using api.Models; -using AutoMapper; - namespace api.Services; -public class OpexCostProfileService : IOpexCostProfileService +public class OpexCostProfileService( + ICaseService caseService, + IProjectService projectService, + IDrainageStrategyService drainageStrategyService, + IWellProjectWellService wellProjectWellService, + ITopsideService topsideService) + : IOpexCostProfileService { - private readonly ICaseService _caseService; - private readonly IProjectService _projectService; - private readonly ILogger _logger; - private readonly IDrainageStrategyService _drainageStrategyService; - private readonly IWellProjectService _wellProjectService; - private readonly IWellProjectWellService _wellProjectWellService; - private readonly ITopsideService _topsideService; - - public OpexCostProfileService( - ILoggerFactory loggerFactory, - ICaseService caseService, - IProjectService projectService, - IDrainageStrategyService drainageStrategyService, - IWellProjectService wellProjectService, - IWellProjectWellService wellProjectWellService, - ITopsideService topsideService) - { - _logger = loggerFactory.CreateLogger(); - _projectService = projectService; - _drainageStrategyService = drainageStrategyService; - _caseService = caseService; - _wellProjectService = wellProjectService; - _wellProjectWellService = wellProjectWellService; - _topsideService = topsideService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCase(caseId); - var project = await _projectService.GetProjectWithoutAssets(caseItem.ProjectId); + var caseItem = await caseService.GetCase(caseId); + var project = await projectService.GetProjectWithoutAssets(caseItem.ProjectId); - var drainageStrategy = await _drainageStrategyService.GetDrainageStrategyWithIncludes( + var drainageStrategy = await drainageStrategyService.GetDrainageStrategyWithIncludes( caseItem.DrainageStrategyLink, d => d.ProductionProfileOil!, d => d.AdditionalProductionProfileOil!, @@ -64,7 +39,7 @@ public async Task CalculateWellInterventionCostProfile(Case caseItem, Project pr var lastYear = lastYearofProduction ?? 0; - var linkedWells = await _wellProjectWellService.GetWellProjectWellsForWellProject(caseItem.WellProjectLink); + var linkedWells = await wellProjectWellService.GetWellProjectWellsForWellProject(caseItem.WellProjectLink); if (linkedWells.Count == 0) { CalculationHelper.ResetTimeSeries(caseItem.WellInterventionCostProfile); @@ -150,7 +125,7 @@ public async Task CalculateOffshoreFacilitiesOperationsCostProfile(Case caseItem int firstYear = firstYearOfProduction.Value; int lastYear = lastYearofProduction.Value; - var topside = await _topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); + var topside = await topsideService.GetTopsideWithIncludes(caseItem.TopsideLink); var facilityOpex = topside.FacilityOpex; diff --git a/backend/api/Services/GenerateCostProfiles/StudyCostProfileService.cs b/backend/api/Services/GenerateCostProfiles/StudyCostProfileService.cs index ad5ec44e7..999157cbe 100644 --- a/backend/api/Services/GenerateCostProfiles/StudyCostProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/StudyCostProfileService.cs @@ -4,37 +4,18 @@ namespace api.Services; -public class StudyCostProfileService : IStudyCostProfileService +public class StudyCostProfileService( + ICaseService caseService, + IWellProjectService wellProjectService, + ITopsideService topsideService, + ISubstructureService substructureService, + ISurfService surfService, + ITransportService transportService) + : IStudyCostProfileService { - private readonly ICaseService _caseService; - private readonly ILogger _logger; - private readonly IWellProjectService _wellProjectService; - private readonly ITopsideService _topsideService; - private readonly ISubstructureService _substructureService; - private readonly ISurfService _surfService; - private readonly ITransportService _transportService; - - public StudyCostProfileService( - ILoggerFactory loggerFactory, - ICaseService caseService, - IWellProjectService wellProjectService, - ITopsideService topsideService, - ISubstructureService substructureService, - ISurfService surfService, - ITransportService transportService) - { - _logger = loggerFactory.CreateLogger(); - _caseService = caseService; - _wellProjectService = wellProjectService; - _topsideService = topsideService; - _substructureService = substructureService; - _surfService = surfService; - _transportService = transportService; - } - public async Task Generate(Guid caseId) { - var caseItem = await _caseService.GetCaseWithIncludes( + var caseItem = await caseService.GetCaseWithIncludes( caseId, c => c.TotalFeasibilityAndConceptStudies!, c => c.TotalFeasibilityAndConceptStudiesOverride!, @@ -176,25 +157,25 @@ public async Task SumAllCostFacility(Case caseItem) { var sumFacilityCost = 0.0; - var substructure = await _substructureService.GetSubstructureWithIncludes( + var substructure = await substructureService.GetSubstructureWithIncludes( caseItem.SubstructureLink, s => s.CostProfileOverride!, s => s.CostProfile! ); - var surf = await _surfService.GetSurfWithIncludes( + var surf = await surfService.GetSurfWithIncludes( caseItem.SurfLink, s => s.CostProfileOverride!, s => s.CostProfile! ); - var topside = await _topsideService.GetTopsideWithIncludes( + var topside = await topsideService.GetTopsideWithIncludes( caseItem.TopsideLink, t => t.CostProfileOverride!, t => t.CostProfile! ); - var transport = await _transportService.GetTransportWithIncludes( + var transport = await transportService.GetTransportWithIncludes( caseItem.TransportLink, t => t.CostProfileOverride!, t => t.CostProfile! @@ -212,7 +193,7 @@ public async Task SumWellCost(Case caseItem) { var sumWellCost = 0.0; - var wellProject = await _wellProjectService.GetWellProjectWithIncludes( + var wellProject = await wellProjectService.GetWellProjectWithIncludes( caseItem.WellProjectLink, w => w.OilProducerCostProfileOverride!, w => w.OilProducerCostProfile!, diff --git a/backend/api/Services/GenerateCostProfiles/WellCostProfileService.cs b/backend/api/Services/GenerateCostProfiles/WellCostProfileService.cs index 652a27262..e04030f29 100644 --- a/backend/api/Services/GenerateCostProfiles/WellCostProfileService.cs +++ b/backend/api/Services/GenerateCostProfiles/WellCostProfileService.cs @@ -1,27 +1,12 @@ using api.Context; -using api.Dtos; -using api.Exceptions; using api.Models; -using AutoMapper; - using Microsoft.EntityFrameworkCore; namespace api.Services; -public class WellCostProfileService : IWellCostProfileService +public class WellCostProfileService(DcdDbContext context) : IWellCostProfileService { - private readonly DcdDbContext _context; - private readonly IMapper _mapper; - - public WellCostProfileService( - DcdDbContext context, - IMapper mapper) - { - _context = context; - _mapper = mapper; - } - public async Task UpdateCostProfilesForWellsFromDrillingSchedules(List drillingScheduleIds) { if (drillingScheduleIds.Count == 0) @@ -202,7 +187,7 @@ private static TimeSeries GenerateWellProjectCostProfileFromDrillingSche private async Task> GetAllExplorationWellsForExploration(Guid explorationId) { - return await _context.ExplorationWell + return await context.ExplorationWell .Include(ew => ew.DrillingSchedule) .Include(ew => ew.Well) .Where(ew => ew.ExplorationId == explorationId).ToListAsync(); @@ -210,7 +195,7 @@ private async Task> GetAllExplorationWellsForExploration(G private IQueryable GetAllExplorationWells() { - return _context.ExplorationWell + return context.ExplorationWell .Include(ew => ew.DrillingSchedule) .Include(ew => ew.Well) .Include(ew => ew.Exploration) @@ -223,7 +208,7 @@ private IQueryable GetAllExplorationWells() private async Task> GetAllWellProjectWellsForWellProject(Guid wellProjectId) { - return await _context.WellProjectWell + return await context.WellProjectWell .Include(ew => ew.DrillingSchedule) .Include(ew => ew.Well) .Where(ew => ew.WellProjectId == wellProjectId).ToListAsync(); @@ -231,7 +216,7 @@ private async Task> GetAllWellProjectWellsForWellProject(G private IQueryable GetAllWellProjectWells() { - return _context.WellProjectWell + return context.WellProjectWell .Include(ew => ew.DrillingSchedule) .Include(ew => ew.Well) .Include(ew => ew.WellProject) diff --git a/backend/api/Services/ICostProfileFromDrillingScheduleHelper.cs b/backend/api/Services/ICostProfileFromDrillingScheduleHelper.cs index 9db4e9794..f31d52295 100644 --- a/backend/api/Services/ICostProfileFromDrillingScheduleHelper.cs +++ b/backend/api/Services/ICostProfileFromDrillingScheduleHelper.cs @@ -1,4 +1,3 @@ -using api.Dtos; using api.Models; namespace api.Services; diff --git a/backend/api/Services/IDuplicateCaseService.cs b/backend/api/Services/IDuplicateCaseService.cs index 938887daf..5e7c7aa93 100644 --- a/backend/api/Services/IDuplicateCaseService.cs +++ b/backend/api/Services/IDuplicateCaseService.cs @@ -1,5 +1,4 @@ using api.Dtos; -using api.Models; namespace api.Services; diff --git a/backend/api/Services/Mapping/ConversionMapperService.cs b/backend/api/Services/Mapping/ConversionMapperService.cs index 0aaaadd2f..f8e0750f6 100644 --- a/backend/api/Services/Mapping/ConversionMapperService.cs +++ b/backend/api/Services/Mapping/ConversionMapperService.cs @@ -7,26 +7,17 @@ namespace api.Services; -public class ConversionMapperService : IConversionMapperService +public class ConversionMapperService(IMapper mapper, ILogger logger) : IConversionMapperService { - private readonly IMapper _mapper; - private readonly ILogger _logger; - - public ConversionMapperService(IMapper mapper, ILogger logger) - { - _mapper = mapper; - _logger = logger; - } - public TDto MapToDto(T entity, Guid id, PhysUnit physUnit) where T : class where TDto : class { - var dto = _mapper.Map(entity, opts => opts.Items["ConversionUnit"] = physUnit.ToString()); + var dto = mapper.Map(entity, opts => opts.Items["ConversionUnit"] = physUnit.ToString()); if (dto == null) { var entityType = typeof(T).Name; - _logger.LogError("Mapping of {EntityType} with id {Id} resulted in a null DTO.", entityType, id); + logger.LogError("Mapping of {EntityType} with id {Id} resulted in a null DTO.", entityType, id); throw new MappingException($"Mapping of {entityType} resulted in a null DTO.", id); } return dto; @@ -36,11 +27,11 @@ public T MapToEntity(TDto dto, T existing, Guid id, PhysUnit physUnit) where T : class where TDto : class { - var entity = _mapper.Map(dto, existing, opts => opts.Items["ConversionUnit"] = physUnit.ToString()); + var entity = mapper.Map(dto, existing, opts => opts.Items["ConversionUnit"] = physUnit.ToString()); if (entity == null) { var entityType = typeof(T).Name; - _logger.LogError("Mapping of {EntityType} with id {Id} resulted in a null entity.", entityType, id); + logger.LogError("Mapping of {EntityType} with id {Id} resulted in a null entity.", entityType, id); throw new MappingException($"Mapping of {entityType} resulted in a null entity.", id); } return entity; diff --git a/backend/api/Services/Mapping/MapperService.cs b/backend/api/Services/Mapping/MapperService.cs index 06190e147..e6ff4595b 100644 --- a/backend/api/Services/Mapping/MapperService.cs +++ b/backend/api/Services/Mapping/MapperService.cs @@ -6,26 +6,17 @@ namespace api.Services; -public class MapperService : IMapperService +public class MapperService(IMapper mapper, ILogger logger) : IMapperService { - private readonly IMapper _mapper; - private readonly ILogger _logger; - - public MapperService(IMapper mapper, ILogger logger) - { - _mapper = mapper; - _logger = logger; - } - public TDto MapToDto(T entity, Guid id) where T : class where TDto : class { - var dto = _mapper.Map(entity); + var dto = mapper.Map(entity); if (dto == null) { var entityType = typeof(T).Name; - _logger.LogError("Mapping of {EntityType} with id {Id} resulted in a null DTO.", entityType, id); + logger.LogError("Mapping of {EntityType} with id {Id} resulted in a null DTO.", entityType, id); throw new MappingException($"Mapping of {entityType} resulted in a null DTO.", id); } return dto; @@ -35,11 +26,11 @@ public T MapToEntity(TDto dto, T existing, Guid id) where T : class where TDto : class { - var entity = _mapper.Map(dto, existing); + var entity = mapper.Map(dto, existing); if (entity == null) { var entityType = typeof(T).Name; - _logger.LogError("Mapping of {EntityType} with id {Id} resulted in a null entity.", entityType, id); + logger.LogError("Mapping of {EntityType} with id {Id} resulted in a null entity.", entityType, id); throw new MappingException($"Mapping of {entityType} resulted in a null entity.", id); } return entity; diff --git a/backend/api/Services/ProspExcelImportService.cs b/backend/api/Services/ProspExcelImportService.cs index 5e2536c27..295e8eaff 100644 --- a/backend/api/Services/ProspExcelImportService.cs +++ b/backend/api/Services/ProspExcelImportService.cs @@ -12,52 +12,23 @@ namespace api.Services; -public class ProspExcelImportService +public class ProspExcelImportService( + ICaseService caseService, + ISurfService surfService, + ISubstructureService substructureService, + ITopsideService topsideService, + ITransportService transportService, + ISubstructureTimeSeriesService substructureTimeSeriesService, + ISurfTimeSeriesService surfTimeSeriesService, + ITopsideTimeSeriesService topsideTimeSeriesService, + ITransportTimeSeriesService transportTimeSeriesService, + IConfiguration config, + IMapper mapper) { private const string SheetName = "main"; - private readonly ICaseService _caseService; - private readonly Prosp _prospConfig; - private readonly ISubstructureService _substructureService; - private readonly ISurfService _surfService; - private readonly ITopsideService _topsideService; - private readonly ITransportService _transportService; - private readonly ISubstructureTimeSeriesService _substructureTimeSeriesService; - private readonly ISurfTimeSeriesService _surfTimeSeriesService; - private readonly ITopsideTimeSeriesService _topsideTimeSeriesService; - private readonly ITransportTimeSeriesService _transportTimeSeriesService; - private readonly IMapper _mapper; - - - public ProspExcelImportService( - ICaseService caseService, - ILoggerFactory loggerFactory, - ISurfService surfService, - ISubstructureService substructureService, - ITopsideService topsideService, - ITransportService transportService, - ISubstructureTimeSeriesService substructureTimeSeriesService, - ISurfTimeSeriesService surfTimeSeriesService, - ITopsideTimeSeriesService topsideTimeSeriesService, - ITransportTimeSeriesService transportTimeSeriesService, - IConfiguration config, - IMapper mapper - ) - { - loggerFactory.CreateLogger(); - _surfService = surfService; - _substructureService = substructureService; - _topsideService = topsideService; - _transportService = transportService; - _substructureTimeSeriesService = substructureTimeSeriesService; - _surfTimeSeriesService = surfTimeSeriesService; - _topsideTimeSeriesService = topsideTimeSeriesService; - _transportTimeSeriesService = transportTimeSeriesService; - _prospConfig = CreateConfig(config); - _caseService = caseService; - _mapper = mapper; - } + private readonly Prosp _prospConfig = CreateConfig(config); - private Prosp CreateConfig(IConfiguration config) + private static Prosp CreateConfig(IConfiguration config) { var prospImportConfig = config.GetSection("FileImportSettings:Prosp").Get(); if (prospImportConfig == null) @@ -155,7 +126,7 @@ private async Task ImportSurf(List cellData, Guid sourceCaseId, Guid proje var importedCurrency = ReadIntValue(cellData, _prospConfig.Surf.importedCurrency); var currency = importedCurrency == 1 ? Currency.NOK : importedCurrency == 2 ? Currency.USD : 0; - var surfLink = (await _caseService.GetCase(sourceCaseId)).SurfLink; + var surfLink = (await caseService.GetCase(sourceCaseId)).SurfLink; var updatedSurfDto = new PROSPUpdateSurfDto { @@ -177,8 +148,8 @@ private async Task ImportSurf(List cellData, Guid sourceCaseId, Guid proje CessationCost = cessationCost, }; - await _surfService.UpdateSurf(projectId, sourceCaseId, surfLink, updatedSurfDto); - await _surfTimeSeriesService.AddOrUpdateSurfCostProfile(projectId, sourceCaseId, surfLink, costProfile); + await surfService.UpdateSurf(projectId, sourceCaseId, surfLink, updatedSurfDto); + await surfTimeSeriesService.AddOrUpdateSurfCostProfile(projectId, sourceCaseId, surfLink, costProfile); } private async Task ImportTopside(List cellData, Guid sourceCaseId, Guid projectId) @@ -228,7 +199,7 @@ private async Task ImportTopside(List cellData, Guid sourceCaseId, Guid pr var importedCurrency = ReadIntValue(cellData, _prospConfig.TopSide.importedCurrency); var currency = importedCurrency == 1 ? Currency.NOK : importedCurrency == 2 ? Currency.USD : 0; - var topsideLink = (await _caseService.GetCase(sourceCaseId)).TopsideLink; + var topsideLink = (await caseService.GetCase(sourceCaseId)).TopsideLink; var updateTopsideDto = new PROSPUpdateTopsideDto { DG3Date = dG3Date, @@ -257,8 +228,8 @@ private async Task ImportTopside(List cellData, Guid sourceCaseId, Guid pr PeakElectricityImported = peakElectricityImported, }; - await _topsideService.UpdateTopside(projectId, sourceCaseId, topsideLink, updateTopsideDto); - await _topsideTimeSeriesService.AddOrUpdateTopsideCostProfile(projectId, sourceCaseId, topsideLink, costProfile); + await topsideService.UpdateTopside(projectId, sourceCaseId, topsideLink, updateTopsideDto); + await topsideTimeSeriesService.AddOrUpdateTopsideCostProfile(projectId, sourceCaseId, topsideLink, costProfile); } private async Task ImportSubstructure(List cellData, Guid sourceCaseId, Guid projectId) @@ -291,7 +262,7 @@ private async Task ImportSubstructure(List cellData, Guid sourceCaseId, Gu var importedCurrency = ReadIntValue(cellData, _prospConfig.SubStructure.importedCurrency); var currency = importedCurrency == 1 ? Currency.NOK : importedCurrency == 2 ? Currency.USD : 0; - var substructureLink = (await _caseService.GetCase(sourceCaseId)).SubstructureLink; + var substructureLink = (await caseService.GetCase(sourceCaseId)).SubstructureLink; var updateSubstructureDto = new PROSPUpdateSubstructureDto { DryWeight = dryWeight, @@ -304,8 +275,8 @@ private async Task ImportSubstructure(List cellData, Guid sourceCaseId, Gu CostYear = costYear, }; - await _substructureService.UpdateSubstructure(projectId, sourceCaseId, substructureLink, updateSubstructureDto); - await _substructureTimeSeriesService.AddOrUpdateSubstructureCostProfile(projectId, sourceCaseId, substructureLink, costProfile); + await substructureService.UpdateSubstructure(projectId, sourceCaseId, substructureLink, updateSubstructureDto); + await substructureTimeSeriesService.AddOrUpdateSubstructureCostProfile(projectId, sourceCaseId, substructureLink, costProfile); } private async Task ImportTransport(List cellData, Guid sourceCaseId, Guid projectId) @@ -337,7 +308,7 @@ private async Task ImportTransport(List cellData, Guid sourceCaseId, Guid var gasExportPipelineLength = ReadDoubleValue(cellData, _prospConfig.Transport.gasExportPipelineLength); var currency = importedCurrency == 1 ? Currency.NOK : importedCurrency == 2 ? Currency.USD : 0; - var transportLink = (await _caseService.GetCase(sourceCaseId)).TransportLink; + var transportLink = (await caseService.GetCase(sourceCaseId)).TransportLink; var updateTransportDto = new PROSPUpdateTransportDto { DG3Date = dG3Date, @@ -350,8 +321,8 @@ private async Task ImportTransport(List cellData, Guid sourceCaseId, Guid GasExportPipelineLength = gasExportPipelineLength, }; - await _transportService.UpdateTransport(projectId, sourceCaseId, transportLink, updateTransportDto); - await _transportTimeSeriesService.AddOrUpdateTransportCostProfile(projectId, sourceCaseId, transportLink, costProfile); + await transportService.UpdateTransport(projectId, sourceCaseId, transportLink, updateTransportDto); + await transportTimeSeriesService.AddOrUpdateTransportCostProfile(projectId, sourceCaseId, transportLink, costProfile); } public async Task ImportProsp(Stream stream, Guid sourceCaseId, Guid projectId, Dictionary assets, @@ -362,7 +333,7 @@ public async Task ImportProsp(Stream stream, Guid sourceCaseId, Guid projectId, var mainSheet = workbookPart?.Workbook.Descendants() .FirstOrDefault(x => x.Name?.ToString()?.ToLower() == SheetName); - var caseItem = await _caseService.GetCase(sourceCaseId); + var caseItem = await caseService.GetCase(sourceCaseId); caseItem.SharepointFileId = sharepointFileId; caseItem.SharepointFileName = sharepointFileName; caseItem.SharepointFileUrl = sharepointFileUrl; @@ -419,13 +390,13 @@ public async Task ImportProsp(Stream stream, Guid sourceCaseId, Guid projectId, SharepointFileUrl = sharepointFileUrl, }; - await _caseService.UpdateCase(projectId, sourceCaseId, caseDto); + await caseService.UpdateCase(projectId, sourceCaseId, caseDto); } } public async Task ClearImportedProspData(Guid sourceCaseId, Guid projectId) { - var caseItem = await _caseService.GetCase(sourceCaseId); + var caseItem = await caseService.GetCase(sourceCaseId); caseItem.SharepointFileId = null; caseItem.SharepointFileName = null; caseItem.SharepointFileUrl = null; @@ -435,14 +406,14 @@ public async Task ClearImportedProspData(Guid sourceCaseId, Guid projectId) await ClearImportedSubstructure(caseItem); await ClearImportedTransport(caseItem); - var caseDto = _mapper.Map(caseItem); + var caseDto = mapper.Map(caseItem); if (caseDto == null) { throw new Exception(); } - await _caseService.UpdateCase(projectId, sourceCaseId, caseDto); + await caseService.UpdateCase(projectId, sourceCaseId, caseDto); } private async Task ClearImportedSurf(Case caseItem) @@ -455,8 +426,8 @@ private async Task ClearImportedSurf(Case caseItem) var costProfileDto = new UpdateSurfCostProfileDto(); - await _surfService.UpdateSurf(caseItem.ProjectId, caseItem.Id, surfLink, dto); - await _surfTimeSeriesService.AddOrUpdateSurfCostProfile(caseItem.ProjectId, caseItem.Id, surfLink, costProfileDto); + await surfService.UpdateSurf(caseItem.ProjectId, caseItem.Id, surfLink, dto); + await surfTimeSeriesService.AddOrUpdateSurfCostProfile(caseItem.ProjectId, caseItem.Id, surfLink, costProfileDto); } private async Task ClearImportedTopside(Case caseItem) @@ -470,8 +441,8 @@ private async Task ClearImportedTopside(Case caseItem) var costProfileDto = new UpdateTopsideCostProfileDto(); - await _topsideService.UpdateTopside(caseItem.ProjectId, caseItem.Id, topsideLink, dto); - await _topsideTimeSeriesService.AddOrUpdateTopsideCostProfile(caseItem.ProjectId, caseItem.Id, topsideLink, costProfileDto); + await topsideService.UpdateTopside(caseItem.ProjectId, caseItem.Id, topsideLink, dto); + await topsideTimeSeriesService.AddOrUpdateTopsideCostProfile(caseItem.ProjectId, caseItem.Id, topsideLink, costProfileDto); } private async Task ClearImportedSubstructure(Case caseItem) @@ -484,8 +455,8 @@ private async Task ClearImportedSubstructure(Case caseItem) var costProfileDto = new UpdateSubstructureCostProfileDto(); - await _substructureService.UpdateSubstructure(caseItem.ProjectId, caseItem.Id, substructureLink, dto); - await _substructureTimeSeriesService.AddOrUpdateSubstructureCostProfile(caseItem.ProjectId, caseItem.Id, substructureLink, costProfileDto); + await substructureService.UpdateSubstructure(caseItem.ProjectId, caseItem.Id, substructureLink, dto); + await substructureTimeSeriesService.AddOrUpdateSubstructureCostProfile(caseItem.ProjectId, caseItem.Id, substructureLink, costProfileDto); } private async Task ClearImportedTransport(Case caseItem) @@ -498,8 +469,8 @@ private async Task ClearImportedTransport(Case caseItem) var costProfileDto = new UpdateTransportCostProfileDto(); - await _transportService.UpdateTransport(caseItem.ProjectId, caseItem.Id, transportLink, dto); - await _transportTimeSeriesService.AddOrUpdateTransportCostProfile(caseItem.ProjectId, caseItem.Id, transportLink, costProfileDto); + await transportService.UpdateTransport(caseItem.ProjectId, caseItem.Id, transportLink, dto); + await transportTimeSeriesService.AddOrUpdateTransportCostProfile(caseItem.ProjectId, caseItem.Id, transportLink, costProfileDto); } private static Concept MapSubstructureConcept(int importValue) diff --git a/backend/api/Services/ProspSharepointImportService.cs b/backend/api/Services/ProspSharepointImportService.cs index 9c9ffa850..f233ace4d 100644 --- a/backend/api/Services/ProspSharepointImportService.cs +++ b/backend/api/Services/ProspSharepointImportService.cs @@ -7,26 +7,11 @@ namespace api.Services; -public class ProspSharepointImportService +public class ProspSharepointImportService( + GraphServiceClient graphServiceClient, + ProspExcelImportService prospExcelImportService, + ILogger logger) { - private static ILogger? _logger; - private readonly IConfiguration _config; - private readonly GraphServiceClient _graphServiceClient; - private readonly ProspExcelImportService _prospExcelImportService; - - public ProspSharepointImportService( - IConfiguration config, - GraphServiceClient graphServiceClient, - ProspExcelImportService prospExcelImportService, - ILoggerFactory loggerFactory - ) - { - _graphServiceClient = graphServiceClient; - _config = config; - _prospExcelImportService = prospExcelImportService; - _logger = loggerFactory.CreateLogger(); - } - public async Task> GetDeltaDriveItemCollectionFromSite(string? url) { var driveItems = new List(); @@ -49,7 +34,7 @@ public async Task> GetDeltaDriveItemCollectionFromSite(string? u } catch (Exception? e) { - _logger?.LogError(e, $"failed retrieving list of latest DriveItems in Site: {e.Message}"); + logger.LogError(e, $"failed retrieving list of latest DriveItems in Site: {e.Message}"); } return driveItems; @@ -61,12 +46,12 @@ private async Task> GetDeltaDriveItemCollectionFromSite(string i IDriveItemDeltaCollectionPage? driveItemsDelta; if (!string.IsNullOrWhiteSpace(itemPath)) { - driveItemsDelta = await _graphServiceClient.Sites[siteId].Drives[driveId].Root + driveItemsDelta = await graphServiceClient.Sites[siteId].Drives[driveId].Root .ItemWithPath("/" + itemPath).Delta().Request().GetAsync(); } else { - driveItemsDelta = await _graphServiceClient.Sites[siteId].Drives[driveId].Root + driveItemsDelta = await graphServiceClient.Sites[siteId].Drives[driveId].Root .Delta().Request().GetAsync(); } @@ -83,7 +68,7 @@ private async Task> GetDeltaDriveItemCollectionFromSite(string i private async Task GetDocumentLibraryDriveId(string siteId, string? documentLibraryName) { - var getDrivesInSite = await _graphServiceClient.Sites[siteId].Drives + var getDrivesInSite = await graphServiceClient.Sites[siteId].Drives .Request() .GetAsync(); @@ -98,13 +83,7 @@ private async Task> GetDeltaDriveItemCollectionFromSite(string i return driveId; } - public class AccessDeniedException : Exception - { - public AccessDeniedException(string message, Exception innerException) - : base(message, innerException) - { - } - } + public class AccessDeniedException(string message, Exception innerException) : Exception(message, innerException); private async Task> GetSiteIdAndParentReferencePath(string? url) { @@ -128,7 +107,7 @@ private async Task> GetSiteIdAndParentReferencePath(string? url) // Example of valid relativepath: /sites/{your site name} such as /sites/ConceptApp-Test var relativePath = $@"/sites/{siteNameFromUrl}"; - var site = await _graphServiceClient.Sites.GetByPath(relativePath, hostName) + var site = await graphServiceClient.Sites.GetByPath(relativePath, hostName) .Request() .GetAsync(); @@ -144,17 +123,17 @@ private async Task> GetSiteIdAndParentReferencePath(string? url) } catch (UriFormatException ex) { - _logger?.LogError(ex, "Invalid URI format: {Url}", url); + logger?.LogError(ex, "Invalid URI format: {Url}", url); throw; // Consider how to handle this error. Maybe wrap it in a custom exception for higher-level handling. } catch (ServiceException ex) when (ex.StatusCode == System.Net.HttpStatusCode.Forbidden) { - _logger?.LogError(ex, "Access Denied when attempting to access SharePoint site: {Url}", url); + logger?.LogError(ex, "Access Denied when attempting to access SharePoint site: {Url}", url); throw new AccessDeniedException("Access to SharePoint resource was denied.", ex); } catch (Exception ex) { - _logger?.LogError(ex, "An error occurred while attempting to access SharePoint site: {Url}", url); + logger?.LogError(ex, "An error occurred while attempting to access SharePoint site: {Url}", url); throw; // Re-throw the exception to be handled upstream. } @@ -184,7 +163,7 @@ public async Task ConvertSharepointFilesToProjectDto(Guid projectId, SharePointI } var caseId = new Guid(importDto.Id); - await _prospExcelImportService.ClearImportedProspData(caseId, projectId); + await prospExcelImportService.ClearImportedProspData(caseId, projectId); } var siteId = GetSiteIdAndParentReferencePath(dtos.FirstOrDefault()!.SharePointSiteUrl)?.Result[0]; @@ -202,7 +181,7 @@ public async Task ConvertSharepointFilesToProjectDto(Guid projectId, SharePointI { try { - var driveItemStream = await _graphServiceClient.Sites[siteId] + var driveItemStream = await graphServiceClient.Sites[siteId] .Drives[driveId].Items[item.Value] .Content.Request() .GetAsync(); @@ -228,7 +207,7 @@ public async Task ConvertSharepointFilesToProjectDto(Guid projectId, SharePointI var assets = MapAssets(iteminfo.Surf, iteminfo.Substructure, iteminfo.Topside, iteminfo.Transport); - await _prospExcelImportService.ImportProsp(caseWithFileStream.Value, caseWithFileStream.Key, + await prospExcelImportService.ImportProsp(caseWithFileStream.Value, caseWithFileStream.Key, projectId, assets, iteminfo.SharePointFileId, diff --git a/backend/api/Services/RefreshProjectService.cs b/backend/api/Services/RefreshProjectService.cs index ae2a68ea1..7ef28e171 100644 --- a/backend/api/Services/RefreshProjectService.cs +++ b/backend/api/Services/RefreshProjectService.cs @@ -1,19 +1,12 @@ namespace api.Services; -public class RefreshProjectService : BackgroundService +public class RefreshProjectService( + IServiceScopeFactory scopeFactory, + ILogger logger, + IConfiguration configuration) + : BackgroundService { private const int generalDelay = 1 * 1000 * 3600; // Each hour - private readonly ILogger _logger; - private readonly IConfiguration _configuration; - - private readonly IServiceScopeFactory _scopeFactory; - public RefreshProjectService(IServiceScopeFactory scopeFactory, ILogger logger, - IConfiguration configuration) - { - _logger = logger; - _configuration = configuration; - _scopeFactory = scopeFactory; - } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { @@ -26,10 +19,10 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) private Task UpdateProjects() { - _logger.LogInformation("HostingService: Running"); + logger.LogInformation("HostingService: Running"); if (Showtime()) { - using var scope = _scopeFactory.CreateScope(); + using var scope = scopeFactory.CreateScope(); var projectService = scope.ServiceProvider.GetRequiredService(); try { @@ -37,20 +30,22 @@ private Task UpdateProjects() } catch (Exception e) { - _logger.LogCritical("Update from Project Master failed: {}", e); + logger.LogCritical("Update from Project Master failed: {}", e); } } + return Task.FromResult("Done"); } private bool Showtime() { - var runtime = _configuration.GetSection("HostedService").GetValue("RunTime"); + var runtime = configuration.GetSection("HostedService").GetValue("RunTime"); if (string.IsNullOrEmpty(runtime)) { - _logger.LogInformation("HostingService: No runtime specified"); + logger.LogInformation("HostingService: No runtime specified"); return false; } + var hour = int.Parse(runtime.Split(':')[0]); var minute = int.Parse(runtime.Split(':')[1]); var second = int.Parse(runtime.Split(':')[2]); @@ -60,7 +55,7 @@ private bool Showtime() if ((now > start) && (now < end)) { - _logger.LogInformation("HostingService: Running Update Project from Project Master"); + logger.LogInformation("HostingService: Running Update Project from Project Master"); return true; } diff --git a/backend/api/Services/STEAService.cs b/backend/api/Services/STEAService.cs index 82d401c44..c84cb44a9 100644 --- a/backend/api/Services/STEAService.cs +++ b/backend/api/Services/STEAService.cs @@ -1,5 +1,4 @@ using api.Adapters; -using api.Context; using api.Dtos; using api.Models; @@ -7,35 +6,23 @@ namespace api.Services; -public class STEAService : ISTEAService +public class STEAService( + ILogger logger, + IProjectService projectService, + IMapper mapper) : ISTEAService { - private readonly IProjectService _projectService; - private readonly ILogger _logger; - private readonly IMapper _mapper; - - public STEAService( - ILoggerFactory loggerFactory, - IProjectService projectService, - IMapper mapper - ) - { - _projectService = projectService; - _logger = loggerFactory.CreateLogger(); - _mapper = mapper; - } - public async Task GetInputToSTEA(Guid ProjectId) { - var project = await _projectService.GetProjectWithCasesAndAssets(ProjectId); + var project = await projectService.GetProjectWithCasesAndAssets(ProjectId); var sTEACaseDtos = new List(); - var projectDto = _mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); + var projectDto = mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); foreach (Case c in project.Cases!) { if (c.Archived) { continue; } - var caseDto = _mapper.Map(c); + var caseDto = mapper.Map(c); if (projectDto == null || caseDto == null) { - _logger.LogError("Failed to map project or case to dto"); + logger.LogError("Failed to map project or case to dto"); throw new Exception("Failed to map project or case to dto"); } STEACaseDto sTEACaseDto = STEACaseDtoBuilder.Build(caseDto, projectDto); @@ -44,7 +31,7 @@ public async Task GetInputToSTEA(Guid ProjectId) if (projectDto == null) { - _logger.LogError("Failed to map project to dto"); + logger.LogError("Failed to map project to dto"); throw new Exception("Failed to map project to dto"); } return STEAProjectDtoBuilder.Build(projectDto, sTEACaseDtos); diff --git a/backend/api/Services/TechnicalInput/TechnicalInputService.cs b/backend/api/Services/TechnicalInput/TechnicalInputService.cs index a7ead50b4..ef41cb112 100644 --- a/backend/api/Services/TechnicalInput/TechnicalInputService.cs +++ b/backend/api/Services/TechnicalInput/TechnicalInputService.cs @@ -1,10 +1,6 @@ -using System.Globalization; - -using api.Adapters; using api.Context; using api.Dtos; using api.Models; -using api.Repositories; using AutoMapper; @@ -12,43 +8,19 @@ namespace api.Services; -public class TechnicalInputService : ITechnicalInputService +public class TechnicalInputService( + DcdDbContext context, + IProjectService projectService, + IExplorationOperationalWellCostsService explorationOperationalWellCostsService, + IDevelopmentOperationalWellCostsService developmentOperationalWellCostsService, + ICostProfileFromDrillingScheduleHelper costProfileFromDrillingScheduleHelper, + ILogger logger, + IMapper mapper) + : ITechnicalInputService { - private readonly DcdDbContext _context; - private readonly IProjectService _projectService; - private readonly IExplorationOperationalWellCostsService _explorationOperationalWellCostsService; - private readonly IDevelopmentOperationalWellCostsService _developmentOperationalWellCostsService; - private readonly ICostProfileFromDrillingScheduleHelper _costProfileFromDrillingScheduleHelper; - private readonly ILogger _logger; - private readonly IMapper _mapper; - - - public TechnicalInputService( - DcdDbContext context, - IProjectService projectService, - IExplorationOperationalWellCostsService explorationOperationalWellCostsService, - IDevelopmentOperationalWellCostsService developmentOperationalWellCostsService, - ICostProfileFromDrillingScheduleHelper costProfileFromDrillingScheduleHelper, - ILoggerFactory loggerFactory, - IMapper mapper - ) - { - _context = context; - - _projectService = projectService; - - _explorationOperationalWellCostsService = explorationOperationalWellCostsService; - _developmentOperationalWellCostsService = developmentOperationalWellCostsService; - - _costProfileFromDrillingScheduleHelper = costProfileFromDrillingScheduleHelper; - - _logger = loggerFactory.CreateLogger(); - _mapper = mapper; - } - public async Task UpdateTehnicalInput(Guid projectId, UpdateTechnicalInputDto technicalInputDto) { - var project = await _projectService.GetProjectWithCasesAndAssets(projectId); + var project = await projectService.GetProjectWithCasesAndAssets(projectId); await UpdateProject(project, technicalInputDto.ProjectDto); @@ -72,14 +44,14 @@ public async Task UpdateTehnicalInput(Guid projectId, UpdateT } } - await _context.SaveChangesAsync(); + await context.SaveChangesAsync(); - var returnProject = await _projectService.GetProjectWithCasesAndAssets(projectId); - var returnProjectDto = _mapper.Map(returnProject, opts => opts.Items["ConversionUnit"] = returnProject.PhysicalUnit.ToString()); + var returnProject = await projectService.GetProjectWithCasesAndAssets(projectId); + var returnProjectDto = mapper.Map(returnProject, opts => opts.Items["ConversionUnit"] = returnProject.PhysicalUnit.ToString()); if (returnProjectDto == null) { - _logger.LogError("Failed to map project to dto"); + logger.LogError("Failed to map project to dto"); throw new Exception("Failed to map project to dto"); } @@ -97,32 +69,32 @@ private async Task DeleteWells(DeleteWellDto[] deleteWellDtos) foreach (var wellDto in deleteWellDtos) { - var well = await _context.Wells!.FindAsync(wellDto.Id); + var well = await context.Wells!.FindAsync(wellDto.Id); if (well != null) { - var explorationWells = _context.ExplorationWell!.Where(ew => ew.WellId == well.Id); + var explorationWells = context.ExplorationWell!.Where(ew => ew.WellId == well.Id); foreach (var explorationWell in explorationWells) { - _context.ExplorationWell!.Remove(explorationWell); + context.ExplorationWell!.Remove(explorationWell); affectedAssets[nameof(Exploration)].Add(explorationWell.ExplorationId); } - var wellProjectWells = _context.WellProjectWell!.Where(ew => ew.WellId == well.Id); + var wellProjectWells = context.WellProjectWell!.Where(ew => ew.WellId == well.Id); foreach (var wellProjectWell in wellProjectWells) { - _context.WellProjectWell!.Remove(wellProjectWell); + context.WellProjectWell!.Remove(wellProjectWell); affectedAssets[nameof(WellProject)].Add(wellProjectWell.WellProjectId); } - _context.Wells.Remove(well); + context.Wells.Remove(well); } } - await _context.SaveChangesAsync(); + await context.SaveChangesAsync(); foreach (var explorationId in affectedAssets[nameof(Exploration)]) { - await _costProfileFromDrillingScheduleHelper.UpdateExplorationCostProfiles(explorationId); + await costProfileFromDrillingScheduleHelper.UpdateExplorationCostProfiles(explorationId); } foreach (var wellProjectId in affectedAssets[nameof(WellProject)]) { - await _costProfileFromDrillingScheduleHelper.UpdateWellProjectCostProfiles(wellProjectId); + await costProfileFromDrillingScheduleHelper.UpdateWellProjectCostProfiles(wellProjectId); } } @@ -138,13 +110,13 @@ private async Task DeleteWells(DeleteWellDto[] deleteWellDtos) { foreach (var wellDto in createWellDtos) { - var well = _mapper.Map(wellDto); + var well = mapper.Map(wellDto); if (well == null) { throw new ArgumentNullException(nameof(well)); } well.ProjectId = projectId; - _context.Wells!.Add(well); + context.Wells!.Add(well); } } @@ -157,45 +129,45 @@ private async Task DeleteWells(DeleteWellDto[] deleteWellDtos) { updatedWells.Add(wellDto.Id); } - _mapper.Map(wellDto, existing); - _context.Wells!.Update(existing); + mapper.Map(wellDto, existing); + context.Wells!.Update(existing); } } if (createWellDtos?.Any() == true || updateWellDtos?.Any() == true) { - await _context.SaveChangesAsync(); + await context.SaveChangesAsync(); } if (updatedWells.Count != 0) { - await _costProfileFromDrillingScheduleHelper.UpdateCostProfilesForWells(updatedWells); + await costProfileFromDrillingScheduleHelper.UpdateCostProfilesForWells(updatedWells); } return null; } private async Task GetWell(Guid wellId) { - var well = await _context.Wells! + var well = await context.Wells! .Include(e => e.WellProjectWells) .Include(e => e.ExplorationWells) .FirstOrDefaultAsync(w => w.Id == wellId); if (well == null) { - throw new ArgumentException(string.Format("Well {0} not found.", wellId)); + throw new ArgumentException($"Well {wellId} not found."); } return well; } private async Task UpdateProject(Project project, UpdateProjectDto updatedDto) { - _mapper.Map(updatedDto, project); + mapper.Map(updatedDto, project); project.ModifyTime = DateTimeOffset.UtcNow; - await _context.SaveChangesAsync(); + await context.SaveChangesAsync(); - var projectDto = _mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); + var projectDto = mapper.Map(project, opts => opts.Items["ConversionUnit"] = project.PhysicalUnit.ToString()); if (projectDto == null) { - _logger.LogError("Failed to map project to dto"); + logger.LogError("Failed to map project to dto"); throw new Exception("Failed to map project to dto"); } @@ -206,17 +178,17 @@ private async Task UpdateExplorationOperatio { if (project.ExplorationOperationalWellCosts == null) { - _logger.LogError("Exploration operational well costs not found"); + logger.LogError("Exploration operational well costs not found"); throw new Exception("Exploration operational well costs not found"); } - var item = await _explorationOperationalWellCostsService.GetOperationalWellCosts(project.ExplorationOperationalWellCosts.Id) ?? new ExplorationOperationalWellCosts(); - _mapper.Map(updatedDto, item); - var updatedItem = _context.ExplorationOperationalWellCosts!.Update(item); - await _context.SaveChangesAsync(); - var explorationOperationalWellCostsDto = _mapper.Map(updatedItem.Entity); + var item = await explorationOperationalWellCostsService.GetOperationalWellCosts(project.ExplorationOperationalWellCosts.Id) ?? new ExplorationOperationalWellCosts(); + mapper.Map(updatedDto, item); + var updatedItem = context.ExplorationOperationalWellCosts!.Update(item); + await context.SaveChangesAsync(); + var explorationOperationalWellCostsDto = mapper.Map(updatedItem.Entity); if (explorationOperationalWellCostsDto == null) { - _logger.LogError("Failed to map exploration operational well costs to dto"); + logger.LogError("Failed to map exploration operational well costs to dto"); throw new Exception("Failed to map exploration operational well costs to dto"); } return explorationOperationalWellCostsDto; @@ -226,17 +198,17 @@ private async Task UpdateDevelopmentOperatio { if (project.DevelopmentOperationalWellCosts == null) { - _logger.LogError("Development operational well costs not found"); + logger.LogError("Development operational well costs not found"); throw new Exception("Development operational well costs not found"); } - var item = await _developmentOperationalWellCostsService.GetOperationalWellCosts(project.DevelopmentOperationalWellCosts.Id) ?? new DevelopmentOperationalWellCosts(); - _mapper.Map(updatedDto, item); - var updatedItem = _context.DevelopmentOperationalWellCosts!.Update(item); - await _context.SaveChangesAsync(); - var developmentOperationalWellCostsDto = _mapper.Map(updatedItem.Entity); + var item = await developmentOperationalWellCostsService.GetOperationalWellCosts(project.DevelopmentOperationalWellCosts.Id) ?? new DevelopmentOperationalWellCosts(); + mapper.Map(updatedDto, item); + var updatedItem = context.DevelopmentOperationalWellCosts!.Update(item); + await context.SaveChangesAsync(); + var developmentOperationalWellCostsDto = mapper.Map(updatedItem.Entity); if (developmentOperationalWellCostsDto == null) { - _logger.LogError("Failed to map development operational well costs to dto"); + logger.LogError("Failed to map development operational well costs to dto"); throw new Exception("Failed to map development operational well costs to dto"); } return developmentOperationalWellCostsDto; diff --git a/backend/tests/Services/DrainageStrategyTimeSeriesServiceTests.cs b/backend/tests/Services/DrainageStrategyTimeSeriesServiceTests.cs index b19ff2a90..3785c3d4e 100644 --- a/backend/tests/Services/DrainageStrategyTimeSeriesServiceTests.cs +++ b/backend/tests/Services/DrainageStrategyTimeSeriesServiceTests.cs @@ -1,4 +1,3 @@ -using api.Context; using api.Dtos; using api.Enums; using api.Exceptions; @@ -6,10 +5,6 @@ using api.Repositories; using api.Services; -using AutoMapper; - -using Microsoft.EntityFrameworkCore; - using NSubstitute; using Xunit; @@ -19,7 +14,7 @@ namespace tests.Services public class DrainageStrategyTimeSeriesServiceTests { private readonly IDrainageStrategyTimeSeriesService _drainageStrategyTimeSeriesService; - private readonly ILoggerFactory _loggerFactory = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly IDrainageStrategyTimeSeriesRepository _repository = Substitute.For(); private readonly IDrainageStrategyRepository _drainageStrategyRepository = Substitute.For(); private readonly ICaseRepository _caseRepository = Substitute.For(); @@ -30,7 +25,7 @@ public class DrainageStrategyTimeSeriesServiceTests public DrainageStrategyTimeSeriesServiceTests() { _drainageStrategyTimeSeriesService = new DrainageStrategyTimeSeriesService( - _loggerFactory, + _logger, _caseRepository, _repository, _drainageStrategyRepository, diff --git a/backend/tests/Services/SubstructureServiceTests.cs b/backend/tests/Services/SubstructureServiceTests.cs index c394ad377..f433a2dc7 100644 --- a/backend/tests/Services/SubstructureServiceTests.cs +++ b/backend/tests/Services/SubstructureServiceTests.cs @@ -1,11 +1,8 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; using api.Services; -using AutoMapper; - using Microsoft.EntityFrameworkCore; using NSubstitute; @@ -17,27 +14,15 @@ namespace tests.Services public class SubstructureServiceTests { private readonly SubstructureService _substructureService; - private readonly IProjectService _projectService = Substitute.For(); - private readonly ILoggerFactory _loggerFactory = Substitute.For(); - private readonly IMapper _mapper = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly ISubstructureRepository _repository = Substitute.For(); private readonly ICaseRepository _caseRepository = Substitute.For(); private readonly IMapperService _mapperService = Substitute.For(); private readonly IProjectAccessService _projectAccessService = Substitute.For(); - public SubstructureServiceTests() { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: "TestDb") - .Options; - - var context = Substitute.For(options, null); - _substructureService = new SubstructureService( - context, - _projectService, - _loggerFactory, - _mapper, + _substructureService = new SubstructureService(_logger, _repository, _caseRepository, _mapperService, diff --git a/backend/tests/Services/SubstructureServiceTimeSeriesTests.cs b/backend/tests/Services/SubstructureServiceTimeSeriesTests.cs index 187034009..5a1a02374 100644 --- a/backend/tests/Services/SubstructureServiceTimeSeriesTests.cs +++ b/backend/tests/Services/SubstructureServiceTimeSeriesTests.cs @@ -1,13 +1,8 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; using api.Services; -using AutoMapper; - -using Microsoft.EntityFrameworkCore; - using NSubstitute; using Xunit; @@ -17,9 +12,7 @@ namespace tests.Services public class SubstructureServiceTimeSeriesTests { private readonly SubstructureTimeSeriesService _substructureService; - private readonly IProjectService _projectService = Substitute.For(); - private readonly ILoggerFactory _loggerFactory = Substitute.For(); - private readonly IMapper _mapper = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly ISubstructureRepository _substructureRepository = Substitute.For(); private readonly ISubstructureTimeSeriesRepository _repository = Substitute.For(); @@ -27,11 +20,10 @@ public class SubstructureServiceTimeSeriesTests private readonly IMapperService _mapperService = Substitute.For(); private readonly IProjectAccessService _projectAccessService = Substitute.For(); - public SubstructureServiceTimeSeriesTests() { _substructureService = new SubstructureTimeSeriesService( - _loggerFactory, + _logger, _substructureRepository, _repository, _caseRepository, diff --git a/backend/tests/Services/SurfServiceTests.cs b/backend/tests/Services/SurfServiceTests.cs index b804e9412..d85eca6a0 100644 --- a/backend/tests/Services/SurfServiceTests.cs +++ b/backend/tests/Services/SurfServiceTests.cs @@ -1,11 +1,8 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; using api.Services; -using AutoMapper; - using Microsoft.EntityFrameworkCore; using NSubstitute; @@ -17,17 +14,16 @@ namespace tests.Services public class SurfServiceTests { private readonly SurfService _surfService; - private readonly ILoggerFactory _loggerFactory = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly ISurfRepository _repository = Substitute.For(); private readonly ICaseRepository _caseRepository = Substitute.For(); private readonly IMapperService _mapperService = Substitute.For(); private readonly IProjectAccessService _projectAccessService = Substitute.For(); - public SurfServiceTests() { _surfService = new SurfService( - _loggerFactory, + _logger, _repository, _caseRepository, _mapperService, diff --git a/backend/tests/Services/SurfServiceTimeSeriesTests.cs b/backend/tests/Services/SurfServiceTimeSeriesTests.cs index e1f87ce7c..aef0bbb72 100644 --- a/backend/tests/Services/SurfServiceTimeSeriesTests.cs +++ b/backend/tests/Services/SurfServiceTimeSeriesTests.cs @@ -1,13 +1,8 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; using api.Services; -using AutoMapper; - -using Microsoft.EntityFrameworkCore; - using NSubstitute; using Xunit; @@ -17,20 +12,17 @@ namespace tests.Services public class SurfServiceTimeSeriesTests { private readonly SurfTimeSeriesService _surfService; - private readonly IProjectService _projectService = Substitute.For(); - private readonly ILoggerFactory _loggerFactory = Substitute.For(); - private readonly IMapper _mapper = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly ISurfTimeSeriesRepository _repository = Substitute.For(); private readonly ISurfRepository _surfRepository = Substitute.For(); private readonly ICaseRepository _caseRepository = Substitute.For(); private readonly IMapperService _mapperService = Substitute.For(); private readonly IProjectAccessService _projectAccessService = Substitute.For(); - public SurfServiceTimeSeriesTests() { _surfService = new SurfTimeSeriesService( - _loggerFactory, + _logger, _repository, _surfRepository, _caseRepository, diff --git a/backend/tests/Services/TopsideServiceTests.cs b/backend/tests/Services/TopsideServiceTests.cs index 83ea04a7f..5414ac5df 100644 --- a/backend/tests/Services/TopsideServiceTests.cs +++ b/backend/tests/Services/TopsideServiceTests.cs @@ -1,11 +1,8 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; using api.Services; -using AutoMapper; - using Microsoft.EntityFrameworkCore; using NSubstitute; @@ -17,17 +14,16 @@ namespace tests.Services public class TopsideServiceTests { private readonly TopsideService _topsideService; - private readonly ILoggerFactory _loggerFactory = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly ITopsideRepository _repository = Substitute.For(); private readonly ICaseRepository _caseRepository = Substitute.For(); private readonly IMapperService _mapperService = Substitute.For(); private readonly IProjectAccessService _projectAccessService = Substitute.For(); - public TopsideServiceTests() { _topsideService = new TopsideService( - _loggerFactory, + _logger, _repository, _caseRepository, _mapperService, diff --git a/backend/tests/Services/TopsideTimeSerivceServiceTests.cs b/backend/tests/Services/TopsideTimeSerivceServiceTests.cs index 459a8a6fc..270c7f6c5 100644 --- a/backend/tests/Services/TopsideTimeSerivceServiceTests.cs +++ b/backend/tests/Services/TopsideTimeSerivceServiceTests.cs @@ -1,13 +1,8 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; using api.Services; -using AutoMapper; - -using Microsoft.EntityFrameworkCore; - using NSubstitute; using Xunit; @@ -17,20 +12,17 @@ namespace tests.Services public class TopsideTimeSerivceServiceTests { private readonly TopsideTimeSeriesService _topsideService; - private readonly IProjectService _projectService = Substitute.For(); - private readonly ILoggerFactory _loggerFactory = Substitute.For(); - private readonly IMapper _mapper = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly ITopsideRepository _topsideRepository = Substitute.For(); private readonly ITopsideTimeSeriesRepository _repository = Substitute.For(); private readonly ICaseRepository _caseRepository = Substitute.For(); private readonly IMapperService _mapperService = Substitute.For(); private readonly IProjectAccessService _projectAccessService = Substitute.For(); - public TopsideTimeSerivceServiceTests() { _topsideService = new TopsideTimeSeriesService( - _loggerFactory, + _logger, _repository, _topsideRepository, _caseRepository, diff --git a/backend/tests/Services/TransportServiceTests.cs b/backend/tests/Services/TransportServiceTests.cs index 92585165e..3d623f6a2 100644 --- a/backend/tests/Services/TransportServiceTests.cs +++ b/backend/tests/Services/TransportServiceTests.cs @@ -1,11 +1,8 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; using api.Services; -using AutoMapper; - using Microsoft.EntityFrameworkCore; using NSubstitute; @@ -17,17 +14,16 @@ namespace tests.Services public class TransportServiceTests { private readonly TransportService _transportService; - private readonly ILoggerFactory _loggerFactory = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly ITransportRepository _repository = Substitute.For(); private readonly ICaseRepository _caseRepository = Substitute.For(); private readonly IMapperService _mapperService = Substitute.For(); private readonly IProjectAccessService _projectAccessService = Substitute.For(); - public TransportServiceTests() { _transportService = new TransportService( - _loggerFactory, + _logger, _caseRepository, _repository, _mapperService, diff --git a/backend/tests/Services/TransportServiceTimeSeriesTests.cs b/backend/tests/Services/TransportServiceTimeSeriesTests.cs index 114c13d23..aec80ccb6 100644 --- a/backend/tests/Services/TransportServiceTimeSeriesTests.cs +++ b/backend/tests/Services/TransportServiceTimeSeriesTests.cs @@ -1,13 +1,8 @@ -using api.Context; using api.Dtos; using api.Models; using api.Repositories; using api.Services; -using AutoMapper; - -using Microsoft.EntityFrameworkCore; - using NSubstitute; using Xunit; @@ -17,18 +12,17 @@ namespace tests.Services public class TransportServiceTimeSeriesTests { private readonly TransportTimeSeriesService _transportService; - private readonly ILoggerFactory _loggerFactory = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); private readonly ITransportTimeSeriesRepository _repository = Substitute.For(); private readonly ITransportRepository _transportRepository = Substitute.For(); private readonly ICaseRepository _caseRepository = Substitute.For(); private readonly IMapperService _mapperService = Substitute.For(); private readonly IProjectAccessService _projectAccessService = Substitute.For(); - public TransportServiceTimeSeriesTests() { _transportService = new TransportTimeSeriesService( - _loggerFactory, + _logger, _caseRepository, _transportRepository, _repository,