diff --git a/.github/workflows/build-and-push-package.yml b/.github/workflows/build-and-push-package.yml deleted file mode 100644 index 71a811578..000000000 --- a/.github/workflows/build-and-push-package.yml +++ /dev/null @@ -1,88 +0,0 @@ -name: Build and Push NuGet Package - -on: - push: - tags: - - 'production-*' - -env: - DOTNET_VERSION: '8.0.x' - -jobs: - build-and-test: - runs-on: ubuntu-latest - permissions: - packages: write - contents: write - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.ref }} - fetch-depth: 0 # Shallow clones disabled for a better relevancy of SC analysis - - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: ${{ env.DOTNET_VERSION }} - - - name: Set up curl and jq - run: sudo apt-get install -y curl jq - - - name: Check for custom version in commit message or check the feed for the latest version and increment it - id: check_custom_version - run: | - # Search the last 10 commits for the version update indicator - COMMIT_HASH=$(git log -n 10 --pretty=format:"%H %s" | grep -P '\(#update package version to \d+\.\d+\.\d+\)' | grep -oP '^\w+' | head -n 1) - - if [[ -n "$COMMIT_HASH" ]]; then - echo "Found commit with version update indicator: $COMMIT_HASH" - - # Check if the commit is already tagged - if git rev-parse "processed-nuget-version-${COMMIT_HASH}" >/dev/null 2>&1; then - echo "This commit has already been processed for version update. Skipping." - else - # Extract the version from the commit message - CUSTOM_VERSION=$(git show -s --format=%s $COMMIT_HASH | grep -oP '\(#update package version to \K([0-9]+\.[0-9]+\.[0-9]+)') - - if [[ -n "$CUSTOM_VERSION" ]]; then - echo "Using custom version: $CUSTOM_VERSION" - echo "NEW_VERSION=$CUSTOM_VERSION" >> $GITHUB_ENV - - # Tag the commit to prevent reprocessing - git tag "processed-nuget-version-${COMMIT_HASH}" - git push origin "processed-nuget-version-${COMMIT_HASH}" - else - echo "Failed to extract version from commit message. Exiting." - exit 1 - fi - fi - fi - - if [[ -z "$CUSTOM_VERSION" ]]; then - echo "No unprocessed custom version found in the last 10 commits. Proceeding to fetch and increment the latest version from the feed." - - # Fetch the latest version and increment the version - PACKAGE_ID="Dfe.PersonsApi.Client" - FEED_URL="https://nuget.pkg.github.com/DFE-Digital/query?q=$PACKAGE_ID" - LATEST_VERSION=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" "$FEED_URL" | jq -r '.data[0].version') - - if [[ -z "$LATEST_VERSION" || "$LATEST_VERSION" == "null" ]]; then - echo "No existing version found in the feed. Defaulting to version 1.0.0" - NEW_VERSION="1.0.0" - else - echo "Latest version is $LATEST_VERSION" - IFS='.' read -r -a VERSION_PARTS <<< "$LATEST_VERSION" - NEW_VERSION="${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.$((VERSION_PARTS[2] + 1))" - echo "Incrementing to new version: $NEW_VERSION" - fi - - echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV - fi - shell: /usr/bin/bash -e {0} - - - name: Build, pack and publish - working-directory: Dfe.PersonsApi.Client - run: | - dotnet build -c Release - dotnet pack -c Release -p:PackageVersion=${{ env.NEW_VERSION }} --output . - dotnet nuget push "*.nupkg" --api-key ${{ secrets.GITHUB_TOKEN }} --source https://nuget.pkg.github.com/DFE-Digital/index.json diff --git a/Dfe.Academies.Api.Infrastructure/InfrastructureServiceCollectionExtensions.cs b/Dfe.Academies.Api.Infrastructure/InfrastructureServiceCollectionExtensions.cs index 7871fef8a..58a37b971 100644 --- a/Dfe.Academies.Api.Infrastructure/InfrastructureServiceCollectionExtensions.cs +++ b/Dfe.Academies.Api.Infrastructure/InfrastructureServiceCollectionExtensions.cs @@ -1,13 +1,8 @@ -using Dfe.Academies.Application.Common.Interfaces; -using Dfe.Academies.Domain.Constituencies; +using Dfe.Academies.Domain.Interfaces.Repositories; using Dfe.Academies.Infrastructure; using Dfe.Academies.Infrastructure.Repositories; -using Dfe.Academies.Infrastructure.Security.Authorization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; -using Dfe.Academies.Domain.Interfaces.Repositories; -using Dfe.Academies.Infrastructure.QueryServices; -using Dfe.Academies.Domain.ValueObjects; namespace Microsoft.Extensions.DependencyInjection { @@ -39,41 +34,6 @@ public static IServiceCollection AddInfrastructureDependencyGroup( return services; } - public static IServiceCollection AddPersonsApiInfrastructureDependencyGroup( - this IServiceCollection services, IConfiguration config) - { - //Repos - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - - // Query Services - services.AddScoped(); - services.AddScoped(); - - //Cache service - services.AddServiceCaching(config); - - //Db - var connectionString = config.GetConnectionString("DefaultConnection"); - - services.AddDbContext(options => - options.UseSqlServer(connectionString)); - - services.AddDbContext(options => - options.UseSqlServer(connectionString)); - - services.AddDbContext(options => - options.UseSqlServer(connectionString)); - - AddInfrastructureHealthChecks(services); - - // Authentication - services.AddCustomAuthorization(config); - - return services; - } - public static void AddInfrastructureHealthChecks(this IServiceCollection services) { services.AddHealthChecks() .AddDbContextCheck("Academies Database"); diff --git a/Dfe.Academies.Api.Infrastructure/MopContext.cs b/Dfe.Academies.Api.Infrastructure/MopContext.cs deleted file mode 100644 index 861c4fadc..000000000 --- a/Dfe.Academies.Api.Infrastructure/MopContext.cs +++ /dev/null @@ -1,85 +0,0 @@ -using Dfe.Academies.Domain.Constituencies; -using Dfe.Academies.Domain.ValueObjects; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Dfe.Academies.Infrastructure; - -public class MopContext : DbContext -{ - const string DEFAULT_SCHEMA = "mop"; - - public MopContext() - { - - } - - public MopContext(DbContextOptions options) : base(options) - { - - } - - public DbSet MemberContactDetails { get; set; } = null!; - public DbSet Constituencies { get; set; } = null!; - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - if (!optionsBuilder.IsConfigured) - { - optionsBuilder.UseSqlServer("Server=localhost;Database=sip;Integrated Security=true;TrustServerCertificate=True"); - } - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity(ConfigureMemberContactDetails); - modelBuilder.Entity(ConfigureConstituency); - - base.OnModelCreating(modelBuilder); - } - - private static void ConfigureMemberContactDetails(EntityTypeBuilder memberContactDetailsConfiguration) - { - memberContactDetailsConfiguration.HasKey(e => e.Id); - - memberContactDetailsConfiguration.ToTable("MemberContactDetails", DEFAULT_SCHEMA); - memberContactDetailsConfiguration.Property(e => e.Id).HasColumnName("memberID") - .HasConversion( - v => v.Value, - v => new MemberId(v)); - memberContactDetailsConfiguration.Property(e => e.Email).HasColumnName("email"); - memberContactDetailsConfiguration.Property(e => e.Phone).HasColumnName("phone"); - memberContactDetailsConfiguration.Property(e => e.TypeId).HasColumnName("typeId"); - } - - private void ConfigureConstituency(EntityTypeBuilder constituencyConfiguration) - { - constituencyConfiguration.ToTable("Constituencies", DEFAULT_SCHEMA); - constituencyConfiguration.Property(e => e.Id).HasColumnName("constituencyId") - .HasConversion( - v => v.Value, - v => new ConstituencyId(v)); - constituencyConfiguration.Property(e => e.MemberId) - .HasConversion( - v => v.Value, - v => new MemberId(v)); - constituencyConfiguration.Property(e => e.ConstituencyName).HasColumnName("constituencyName"); - - constituencyConfiguration.OwnsOne(e => e.NameDetails, nameDetails => - { - nameDetails.Property(nd => nd.NameListAs).HasColumnName("nameListAs"); - nameDetails.Property(nd => nd.NameDisplayAs).HasColumnName("nameDisplayAs"); - nameDetails.Property(nd => nd.NameFullTitle).HasColumnName("nameFullTitle"); - }); - - constituencyConfiguration.Property(e => e.LastRefresh).HasColumnName("lastRefresh"); - - constituencyConfiguration - .HasOne(c => c.MemberContactDetails) - .WithOne() - .HasForeignKey(c => c.MemberId) - .HasPrincipalKey(m => m.Id); - } - - -} diff --git a/Dfe.Academies.Api.Infrastructure/QueryServices/EstablishmentQueryService.cs b/Dfe.Academies.Api.Infrastructure/QueryServices/EstablishmentQueryService.cs deleted file mode 100644 index b220462cb..000000000 --- a/Dfe.Academies.Api.Infrastructure/QueryServices/EstablishmentQueryService.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Dfe.Academies.Application.Common.Interfaces; -using Dfe.Academies.Application.Common.Models; -using Microsoft.EntityFrameworkCore; - -namespace Dfe.Academies.Infrastructure.QueryServices -{ - internal class EstablishmentQueryService(MstrContext context) : IEstablishmentQueryService - { - public IQueryable? GetPersonsAssociatedWithAcademyByUrn(int urn) - { - var establishmentExists = context.Establishments.AsNoTracking().Any(e => e.URN == urn); - if (!establishmentExists) - { - return null; - } - - var query = from ee in context.Establishments.AsNoTracking() - join eeg in context.EducationEstablishmentGovernances.AsNoTracking() - on ee.SK equals eeg.EducationEstablishmentId - join grt in context.GovernanceRoleTypes.AsNoTracking() - on eeg.GovernanceRoleTypeId equals grt.SK - where ee.URN == urn - select new AcademyGovernanceQueryModel(eeg, grt, ee); - - return query; - } - } -} diff --git a/Dfe.Academies.Api.Infrastructure/QueryServices/TrustQueryService.cs b/Dfe.Academies.Api.Infrastructure/QueryServices/TrustQueryService.cs deleted file mode 100644 index 43ac2d5e3..000000000 --- a/Dfe.Academies.Api.Infrastructure/QueryServices/TrustQueryService.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Dfe.Academies.Application.Common.Interfaces; -using Dfe.Academies.Application.Common.Models; -using Microsoft.EntityFrameworkCore; - -namespace Dfe.Academies.Infrastructure.QueryServices -{ - internal class TrustQueryService(MstrContext context) : ITrustQueryService - { - public IQueryable? GetTrustGovernanceByGroupIdOrUkprn(string? groupId, string? ukPrn) - { - - // Check if the trust exists based on GroupID or UKPRN - var trustExists = context.Trusts.AsNoTracking().Any(t => - (!string.IsNullOrEmpty(groupId) && t.GroupID == groupId) || - (!string.IsNullOrEmpty(ukPrn) && t.UKPRN == ukPrn)); - - if (!trustExists) - { - return null; - } - - var query = from t in context.Trusts.AsNoTracking() - join tg in context.TrustGovernances.AsNoTracking() - on t.SK equals tg.TrustId - join grt in context.GovernanceRoleTypes.AsNoTracking() - on tg.GovernanceRoleTypeId equals grt.SK - where (!string.IsNullOrEmpty(groupId) && t.GroupID == groupId) || - (!string.IsNullOrEmpty(ukPrn) && t.UKPRN == ukPrn) - select new TrustGovernanceQueryModel(t, grt, tg); - - return query; - } - } - -} diff --git a/Dfe.Academies.Api.Infrastructure/Repositories/ConstituencyRepository.cs b/Dfe.Academies.Api.Infrastructure/Repositories/ConstituencyRepository.cs deleted file mode 100644 index 3ebe7d59f..000000000 --- a/Dfe.Academies.Api.Infrastructure/Repositories/ConstituencyRepository.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Dfe.Academies.Domain.Constituencies; -using Dfe.Academies.Domain.Interfaces.Repositories; -using Microsoft.EntityFrameworkCore; - -namespace Dfe.Academies.Infrastructure.Repositories -{ - public class ConstituencyRepository(MopContext context) : IConstituencyRepository - { - public async Task GetMemberOfParliamentByConstituencyAsync(string constituencyName, CancellationToken cancellationToken) - { - return await context.Constituencies - .AsNoTracking() - .Include(c => c.MemberContactDetails) - .Where(c => c.ConstituencyName == constituencyName - && c.MemberContactDetails.TypeId == 1 - && !c.EndDate.HasValue) - .FirstOrDefaultAsync(cancellationToken); - } - - public IQueryable GetMembersOfParliamentByConstituenciesQueryable(List constituencyNames) - { - return context.Constituencies - .AsNoTracking() - .Include(c => c.MemberContactDetails) - .Where(c => constituencyNames.Contains(c.ConstituencyName) - && c.MemberContactDetails.TypeId == 1 - && !c.EndDate.HasValue); - } - } -} diff --git a/Dfe.Academies.Api.Infrastructure/Security/Authorization/AuthorizationExtensions.cs b/Dfe.Academies.Api.Infrastructure/Security/Authorization/AuthorizationExtensions.cs deleted file mode 100644 index 20a1e438b..000000000 --- a/Dfe.Academies.Api.Infrastructure/Security/Authorization/AuthorizationExtensions.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Identity.Web; -using System.Diagnostics.CodeAnalysis; - -namespace Dfe.Academies.Infrastructure.Security.Authorization -{ - [ExcludeFromCodeCoverage] - public static class AuthorizationExtensions - { - public static IServiceCollection AddCustomAuthorization(this IServiceCollection services, IConfiguration configuration) - { - services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddMicrosoftIdentityWebApi(configuration.GetSection("AzureAd")); - - services.AddAuthorization(options => - { - options.DefaultPolicy = new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .Build(); - - var roles = configuration.GetSection("Authorization:Roles").Get(); - if (roles != null) - { - foreach (var role in roles) - { - options.AddPolicy(role, policy => policy.RequireRole(role)); - } - } - - var claims = configuration.GetSection("Authorization:Claims").Get>(); - if (claims != null) - { - foreach (var claim in claims) - { - options.AddPolicy($"{claim.Key}", policy => - policy.RequireClaim(claim.Key, claim.Value)); - } - } - }); - - return services; - } - } - -} diff --git a/Dfe.Academies.Application/ApplicationServiceCollectionExtensions.cs b/Dfe.Academies.Application/ApplicationServiceCollectionExtensions.cs index d15690807..3e9c67806 100644 --- a/Dfe.Academies.Application/ApplicationServiceCollectionExtensions.cs +++ b/Dfe.Academies.Application/ApplicationServiceCollectionExtensions.cs @@ -22,27 +22,5 @@ public static IServiceCollection AddApplicationDependencyGroup( return services; } - - public static IServiceCollection AddPersonsApiApplicationDependencyGroup( - this IServiceCollection services, IConfiguration config) - { - var performanceLoggingEnabled = config.GetValue("Features:PerformanceLoggingEnabled"); - - services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); - - services.AddMediatR(cfg => - { - cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()); - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>)); - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>)); - - if (performanceLoggingEnabled) - { - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>)); - } - }); - - return services; - } } } \ No newline at end of file diff --git a/Dfe.Academies.Application/Common/Interfaces/IEstablishmentQueryService.cs b/Dfe.Academies.Application/Common/Interfaces/IEstablishmentQueryService.cs deleted file mode 100644 index 502ea1353..000000000 --- a/Dfe.Academies.Application/Common/Interfaces/IEstablishmentQueryService.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Dfe.Academies.Application.Common.Models; - -namespace Dfe.Academies.Application.Common.Interfaces -{ - public interface IEstablishmentQueryService - { - IQueryable? GetPersonsAssociatedWithAcademyByUrn(int urn); - } -} diff --git a/Dfe.Academies.Application/Common/Interfaces/ITrustQueryService.cs b/Dfe.Academies.Application/Common/Interfaces/ITrustQueryService.cs deleted file mode 100644 index 3575019a3..000000000 --- a/Dfe.Academies.Application/Common/Interfaces/ITrustQueryService.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Dfe.Academies.Application.Common.Models; - -namespace Dfe.Academies.Application.Common.Interfaces -{ - public interface ITrustQueryService - { - IQueryable? GetTrustGovernanceByGroupIdOrUkprn(string? groupId, string? ukPrn); - } -} diff --git a/Dfe.Academies.Application/Common/Models/AcademyGovernance.cs b/Dfe.Academies.Application/Common/Models/AcademyGovernance.cs deleted file mode 100644 index 553687caa..000000000 --- a/Dfe.Academies.Application/Common/Models/AcademyGovernance.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Dfe.Academies.Application.Common.Models -{ - public class AcademyGovernance : Person - { - public string? UKPRN { get; set; } - public int? URN { get; set; } - } -} diff --git a/Dfe.Academies.Application/Common/Models/AcademyGovernanceQueryModel.cs b/Dfe.Academies.Application/Common/Models/AcademyGovernanceQueryModel.cs deleted file mode 100644 index db01184ab..000000000 --- a/Dfe.Academies.Application/Common/Models/AcademyGovernanceQueryModel.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Dfe.Academies.Domain.Establishment; - -namespace Dfe.Academies.Application.Common.Models -{ - public record AcademyGovernanceQueryModel( - EducationEstablishmentGovernance EducationEstablishmentGovernance, - GovernanceRoleType GovernanceRoleType, - Domain.Establishment.Establishment Establishment - ); -} diff --git a/Dfe.Academies.Application/Common/Models/MemberOfParliament.cs b/Dfe.Academies.Application/Common/Models/MemberOfParliament.cs deleted file mode 100644 index 9842d5e8a..000000000 --- a/Dfe.Academies.Application/Common/Models/MemberOfParliament.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Dfe.Academies.Application.Common.Models -{ - public class MemberOfParliament : Person - { - public required string ConstituencyName { get; set; } - } -} diff --git a/Dfe.Academies.Application/Common/Models/Person.cs b/Dfe.Academies.Application/Common/Models/Person.cs deleted file mode 100644 index b7e13ac02..000000000 --- a/Dfe.Academies.Application/Common/Models/Person.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Dfe.Academies.Application.Common.Models -{ - public class Person - { - private ICollection? _roles; - - public int Id { get; set; } - public required string FirstName { get; set; } - public required string LastName { get; set; } - public required string Email { get; set; } - public required string DisplayName { get; set; } - public required string DisplayNameWithTitle { get; set; } - public string? Phone { get; set; } - public required ICollection Roles - { - get => _roles ??= new List(); - set => _roles = value ?? []; - } - public required DateTime? UpdatedAt { get; set; } - - } -} diff --git a/Dfe.Academies.Application/Common/Models/Result.cs b/Dfe.Academies.Application/Common/Models/Result.cs deleted file mode 100644 index 20b878e34..000000000 --- a/Dfe.Academies.Application/Common/Models/Result.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Dfe.Academies.Application.Common.Models -{ - public class Result - { - public T? Value { get; } - public bool IsSuccess { get; } - public string? Error { get; } - - private Result(T value, bool isSuccess, string? error) - { - Value = value; - IsSuccess = isSuccess; - Error = error; - } - - public static Result Success(T value) => new Result(value, true, null); - public static Result Failure(string error) => new Result(default!, false, error); - } - -} diff --git a/Dfe.Academies.Application/Common/Models/TrustGovernance.cs b/Dfe.Academies.Application/Common/Models/TrustGovernance.cs deleted file mode 100644 index 5fcc06a06..000000000 --- a/Dfe.Academies.Application/Common/Models/TrustGovernance.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Dfe.Academies.Application.Common.Models -{ - public class TrustGovernance : Person - { - public string? UKPRN { get; set; } - public string? TRN { get; set; } - } -} diff --git a/Dfe.Academies.Application/Common/Models/TrustGovernanceQueryModel.cs b/Dfe.Academies.Application/Common/Models/TrustGovernanceQueryModel.cs deleted file mode 100644 index fcfae95fe..000000000 --- a/Dfe.Academies.Application/Common/Models/TrustGovernanceQueryModel.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Dfe.Academies.Domain.Establishment; - -namespace Dfe.Academies.Application.Common.Models -{ - public record TrustGovernanceQueryModel( - Domain.Trust.Trust Trust, - GovernanceRoleType GovernanceRoleType, - Domain.Trust.TrustGovernance TrustGovernance - ); -} diff --git a/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituencies/GetMemberOfParliamentByConstituencies.cs b/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituencies/GetMemberOfParliamentByConstituencies.cs deleted file mode 100644 index 1bdec82fe..000000000 --- a/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituencies/GetMemberOfParliamentByConstituencies.cs +++ /dev/null @@ -1,39 +0,0 @@ -using AutoMapper; -using AutoMapper.QueryableExtensions; -using Dfe.Academies.Application.Common.Models; -using Dfe.Academies.Domain.Interfaces.Repositories; -using DfE.CoreLibs.Caching.Helpers; -using DfE.CoreLibs.Caching.Interfaces; -using MediatR; -using Microsoft.EntityFrameworkCore; - -namespace Dfe.Academies.Application.Constituencies.Queries.GetMemberOfParliamentByConstituencies -{ - public record GetMembersOfParliamentByConstituenciesQuery(List ConstituencyNames) : IRequest>>; - - public class GetMembersOfParliamentByConstituenciesQueryHandler( - IConstituencyRepository constituencyRepository, - IMapper mapper, - ICacheService cacheService) - : IRequestHandler>> - { - public async Task>> Handle(GetMembersOfParliamentByConstituenciesQuery request, CancellationToken cancellationToken) - { - var cacheKey = $"MemberOfParliament_{CacheKeyHelper.GenerateHashedCacheKey(request.ConstituencyNames)}"; - - return await cacheService.GetOrAddAsync(cacheKey, async () => - { - var constituenciesQuery = constituencyRepository - .GetMembersOfParliamentByConstituenciesQueryable(request.ConstituencyNames); - - var membersOfParliament = await constituenciesQuery - .ProjectTo(mapper.ConfigurationProvider) - .ToListAsync(cancellationToken); - - return Result>.Success(membersOfParliament); - - }, nameof(GetMembersOfParliamentByConstituenciesQueryHandler)); - } - } - -} diff --git a/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituencies/GetMemberOfParliamentByConstituenciesValidator.cs b/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituencies/GetMemberOfParliamentByConstituenciesValidator.cs deleted file mode 100644 index d81624d5f..000000000 --- a/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituencies/GetMemberOfParliamentByConstituenciesValidator.cs +++ /dev/null @@ -1,15 +0,0 @@ -using FluentValidation; - -namespace Dfe.Academies.Application.Constituencies.Queries.GetMemberOfParliamentByConstituencies -{ - public class GetMemberOfParliamentByConstituenciesValidator : AbstractValidator - { - public GetMemberOfParliamentByConstituenciesValidator() - { - RuleFor(x => x.ConstituencyNames) - .NotNull().WithMessage("Constituency names cannot be null.") - .NotEmpty().WithMessage("Constituency names cannot be empty.") - .Must(c => c.Count > 0).WithMessage("At least one constituency must be provided."); - } - } -} diff --git a/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituency/GetMemberOfParliamentByConstituency.cs b/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituency/GetMemberOfParliamentByConstituency.cs deleted file mode 100644 index 27d4e56c6..000000000 --- a/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituency/GetMemberOfParliamentByConstituency.cs +++ /dev/null @@ -1,39 +0,0 @@ -using AutoMapper; -using Dfe.Academies.Application.Common.Models; -using Dfe.Academies.Domain.Interfaces.Repositories; -using DfE.CoreLibs.Caching.Helpers; -using DfE.CoreLibs.Caching.Interfaces; -using MediatR; - -namespace Dfe.Academies.Application.Constituencies.Queries.GetMemberOfParliamentByConstituency -{ - public record GetMemberOfParliamentByConstituencyQuery(string ConstituencyName) : IRequest>; - - public class GetMemberOfParliamentByConstituencyQueryHandler( - IConstituencyRepository constituencyRepository, - IMapper mapper, - ICacheService cacheService) - : IRequestHandler> - { - public async Task> Handle(GetMemberOfParliamentByConstituencyQuery request, CancellationToken cancellationToken) - { - var cacheKey = $"MemberOfParliament_{CacheKeyHelper.GenerateHashedCacheKey(request.ConstituencyName)}"; - - return await cacheService.GetOrAddAsync(cacheKey, async () => - { - var constituencyWithMember = await constituencyRepository - .GetMemberOfParliamentByConstituencyAsync(request.ConstituencyName, cancellationToken); - - if (constituencyWithMember == null) - { - return Result.Failure("Constituency not found."); - } - - var result = mapper.Map(constituencyWithMember); - - return Result.Success(result); - - }, nameof(GetMemberOfParliamentByConstituencyQueryHandler)); - } - } -} diff --git a/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituency/GetMemberOfParliamentByConstituencyQueryValidator.cs b/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituency/GetMemberOfParliamentByConstituencyQueryValidator.cs deleted file mode 100644 index 8991e2bdb..000000000 --- a/Dfe.Academies.Application/Constituencies/Queries/GetMemberOfParliamentByConstituency/GetMemberOfParliamentByConstituencyQueryValidator.cs +++ /dev/null @@ -1,14 +0,0 @@ -using FluentValidation; - -namespace Dfe.Academies.Application.Constituencies.Queries.GetMemberOfParliamentByConstituency -{ - public class GetMemberOfParliamentByConstituencyQueryValidator : AbstractValidator - { - public GetMemberOfParliamentByConstituencyQueryValidator() - { - RuleFor(x => x.ConstituencyName) - .NotNull().WithMessage("Constituency name cannot be null.") - .NotEmpty().WithMessage("Constituency name cannot be empty."); - } - } -} diff --git a/Dfe.Academies.Application/Establishment/Queries/GetAllPersonsAssociatedWithAcademyByUrn/GetAllPersonsAssociatedWithAcademyByUrn.cs b/Dfe.Academies.Application/Establishment/Queries/GetAllPersonsAssociatedWithAcademyByUrn/GetAllPersonsAssociatedWithAcademyByUrn.cs deleted file mode 100644 index db07cf934..000000000 --- a/Dfe.Academies.Application/Establishment/Queries/GetAllPersonsAssociatedWithAcademyByUrn/GetAllPersonsAssociatedWithAcademyByUrn.cs +++ /dev/null @@ -1,41 +0,0 @@ -using AutoMapper; -using AutoMapper.QueryableExtensions; -using Dfe.Academies.Application.Common.Interfaces; -using Dfe.Academies.Application.Common.Models; -using DfE.CoreLibs.Caching.Helpers; -using DfE.CoreLibs.Caching.Interfaces; -using MediatR; -using Microsoft.EntityFrameworkCore; - -namespace Dfe.Academies.Application.Establishment.Queries.GetAllPersonsAssociatedWithAcademyByUrn -{ - public record GetAllPersonsAssociatedWithAcademyByUrnQuery(int Urn) : IRequest?>>; - - public class GetAllPersonsAssociatedWithAcademyByUrnQueryHandler( - IEstablishmentQueryService establishmentQueryService, - IMapper mapper, - ICacheService cacheService) - : IRequestHandler?>> - { - public async Task?>> Handle(GetAllPersonsAssociatedWithAcademyByUrnQuery request, CancellationToken cancellationToken) - { - var cacheKey = $"PersonsAssociatedWithAcademy_{CacheKeyHelper.GenerateHashedCacheKey(request.Urn.ToString())}"; - - return await cacheService.GetOrAddAsync(cacheKey, async () => - { - var query = establishmentQueryService.GetPersonsAssociatedWithAcademyByUrn(request.Urn); - - if (query == null) - { - return Result?>.Failure("Academy not found."); - } - - var result = Result?>.Success(await query - .ProjectTo(mapper.ConfigurationProvider) - .ToListAsync(cancellationToken)); - - return result; - }, nameof(GetAllPersonsAssociatedWithAcademyByUrnQueryHandler)); - } - } -} diff --git a/Dfe.Academies.Application/Establishment/Queries/GetAllPersonsAssociatedWithAcademyByUrn/GetAllPersonsAssociatedWithAcademyByUrnValidator.cs b/Dfe.Academies.Application/Establishment/Queries/GetAllPersonsAssociatedWithAcademyByUrn/GetAllPersonsAssociatedWithAcademyByUrnValidator.cs deleted file mode 100644 index 00beb8285..000000000 --- a/Dfe.Academies.Application/Establishment/Queries/GetAllPersonsAssociatedWithAcademyByUrn/GetAllPersonsAssociatedWithAcademyByUrnValidator.cs +++ /dev/null @@ -1,14 +0,0 @@ -using FluentValidation; - -namespace Dfe.Academies.Application.Establishment.Queries.GetAllPersonsAssociatedWithAcademyByUrn -{ - public class GetAllPersonsAssociatedWithAcademyByUrnValidator : AbstractValidator - { - public GetAllPersonsAssociatedWithAcademyByUrnValidator() - { - RuleFor(query => query.Urn) - .GreaterThan(0).WithMessage("URN must be greater than 0.") - .NotEmpty().WithMessage("URN is required."); - } - } -} diff --git a/Dfe.Academies.Application/Establishment/Queries/GetMemberOfParliamentBySchool/GetMemberOfParliamentBySchool.cs b/Dfe.Academies.Application/Establishment/Queries/GetMemberOfParliamentBySchool/GetMemberOfParliamentBySchool.cs deleted file mode 100644 index a48b4caf7..000000000 --- a/Dfe.Academies.Application/Establishment/Queries/GetMemberOfParliamentBySchool/GetMemberOfParliamentBySchool.cs +++ /dev/null @@ -1,44 +0,0 @@ -using AutoMapper; -using Dfe.Academies.Application.Common.Models; -using Dfe.Academies.Domain.Interfaces.Repositories; -using DfE.CoreLibs.Caching.Helpers; -using DfE.CoreLibs.Caching.Interfaces; -using MediatR; - -namespace Dfe.Academies.Application.Establishment.Queries.GetMemberOfParliamentBySchool -{ - public record GetMemberOfParliamentBySchoolQuery(int Urn) : IRequest>; - - public class GetMemberOfParliamentBySchoolQueryHandler( - IEstablishmentRepository establishmentRepository, - IConstituencyRepository constituencyRepository, - IMapper mapper, - ICacheService cacheService) - : IRequestHandler> - { - public async Task> Handle(GetMemberOfParliamentBySchoolQuery request, CancellationToken cancellationToken) - { - var cacheKey = $"MPbySchool_{CacheKeyHelper.GenerateHashedCacheKey(request.Urn.ToString())}"; - - return await cacheService.GetOrAddAsync(cacheKey, async () => - { - var establishment = await establishmentRepository.GetEstablishmentByUrn(request.Urn.ToString(), cancellationToken); - if (establishment == null) - { - return Result.Failure("School not found."); - } - - var constituency = await constituencyRepository.GetMemberOfParliamentByConstituencyAsync(establishment.ParliamentaryConstituency!, cancellationToken); - if (constituency == null) - { - return Result.Failure("Constituency not found for the given establishment."); - } - - var mp = mapper.Map(constituency); - - return Result.Success(mp); - - }, nameof(GetMemberOfParliamentBySchoolQueryHandler)); - } - } -} diff --git a/Dfe.Academies.Application/Establishment/Queries/GetMemberOfParliamentBySchool/GetMemberOfParliamentBySchoolValidator.cs b/Dfe.Academies.Application/Establishment/Queries/GetMemberOfParliamentBySchool/GetMemberOfParliamentBySchoolValidator.cs deleted file mode 100644 index 41c5981f5..000000000 --- a/Dfe.Academies.Application/Establishment/Queries/GetMemberOfParliamentBySchool/GetMemberOfParliamentBySchoolValidator.cs +++ /dev/null @@ -1,14 +0,0 @@ -using FluentValidation; - -namespace Dfe.Academies.Application.Establishment.Queries.GetMemberOfParliamentBySchool -{ - public class GetMemberOfParliamentBySchoolQueryValidator : AbstractValidator - { - public GetMemberOfParliamentBySchoolQueryValidator() - { - RuleFor(query => query.Urn) - .GreaterThan(0).WithMessage("URN must be greater than 0.") - .NotEmpty().WithMessage("URN is required."); - } - } -} \ No newline at end of file diff --git a/Dfe.Academies.Application/MappingProfiles/AcademyWithGovernanceProfile.cs b/Dfe.Academies.Application/MappingProfiles/AcademyWithGovernanceProfile.cs deleted file mode 100644 index 6301f7387..000000000 --- a/Dfe.Academies.Application/MappingProfiles/AcademyWithGovernanceProfile.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Dfe.Academies.Application.Common.Models; - -namespace Dfe.Academies.Application.MappingProfiles -{ - public class AcademyWithGovernanceProfile : Profile - { - public AcademyWithGovernanceProfile() - { - CreateMap() - .ForMember(dest => dest.Id, opt => opt.MapFrom(src => (int)src.EducationEstablishmentGovernance.SK)) - .ForMember(dest => dest.UKPRN, opt => opt.MapFrom(src => src.Establishment.UKPRN)) - .ForMember(dest => dest.URN, opt => opt.MapFrom(src => src.Establishment.URN)) - .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.EducationEstablishmentGovernance.Forename1)) - .ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.EducationEstablishmentGovernance.Surname)) - .ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.EducationEstablishmentGovernance.Email)) - .ForMember(dest => dest.DisplayName, opt => opt.MapFrom(src => $"{src.EducationEstablishmentGovernance.Forename1} {src.EducationEstablishmentGovernance.Surname}")) - .ForMember(dest => dest.DisplayNameWithTitle, opt => opt.MapFrom(src => $"{src.EducationEstablishmentGovernance.Title} {src.EducationEstablishmentGovernance.Forename1} {src.EducationEstablishmentGovernance.Surname}")) - .ForMember(dest => dest.Roles, opt => opt.MapFrom(src => new List { src.GovernanceRoleType.Name })) - .ForMember(dest => dest.UpdatedAt, opt => opt.MapFrom(src => src.EducationEstablishmentGovernance.Modified)); - } - } -} \ No newline at end of file diff --git a/Dfe.Academies.Application/MappingProfiles/ConstituencyProfile.cs b/Dfe.Academies.Application/MappingProfiles/ConstituencyProfile.cs deleted file mode 100644 index a94c60057..000000000 --- a/Dfe.Academies.Application/MappingProfiles/ConstituencyProfile.cs +++ /dev/null @@ -1,24 +0,0 @@ -using AutoMapper; -using Dfe.Academies.Application.Common.Models; -using Dfe.Academies.Domain.Constituencies; - -namespace Dfe.Academies.Application.MappingProfiles -{ - public class ConstituencyProfile : Profile - { - public ConstituencyProfile() - { - CreateMap() - .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.MemberId.Value)) - .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.NameDetails.NameListAs.Split(",", StringSplitOptions.None)[1].Trim())) - .ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.NameDetails.NameListAs.Split(",", StringSplitOptions.None)[0].Trim())) - .ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.MemberContactDetails.Email)) - .ForMember(dest => dest.DisplayName, opt => opt.MapFrom(src => src.NameDetails.NameDisplayAs)) - .ForMember(dest => dest.DisplayNameWithTitle, opt => opt.MapFrom(src => src.NameDetails.NameFullTitle)) - .ForMember(dest => dest.Roles, opt => opt.MapFrom(src => new List { "Member of Parliament" })) - .ForMember(dest => dest.UpdatedAt, opt => opt.MapFrom(src => src.LastRefresh)) - .ForMember(dest => dest.Phone, opt => opt.MapFrom(src => src.MemberContactDetails.Phone)) - .ForMember(dest => dest.ConstituencyName, opt => opt.MapFrom(src => src.ConstituencyName)); - } - } -} \ No newline at end of file diff --git a/Dfe.Academies.Application/MappingProfiles/TrustWithGovernanceProfile.cs b/Dfe.Academies.Application/MappingProfiles/TrustWithGovernanceProfile.cs deleted file mode 100644 index 90e3f329d..000000000 --- a/Dfe.Academies.Application/MappingProfiles/TrustWithGovernanceProfile.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Dfe.Academies.Application.Common.Models; - -namespace Dfe.Academies.Application.MappingProfiles -{ - public class TrustWithGovernanceProfile : Profile - { - public TrustWithGovernanceProfile() - { - CreateMap() - .ForMember(dest => dest.Id, opt => opt.MapFrom(src => (int)src.TrustGovernance.SK)) - .ForMember(dest => dest.UKPRN, opt => opt.MapFrom(src => src.Trust.UKPRN)) - .ForMember(dest => dest.TRN, opt => opt.MapFrom(src => src.Trust.GroupID)) - .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.TrustGovernance.Forename1)) - .ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.TrustGovernance.Surname)) - .ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.TrustGovernance.Email)) - .ForMember(dest => dest.DisplayName, opt => opt.MapFrom(src => $"{src.TrustGovernance.Forename1} {src.TrustGovernance.Surname}")) - .ForMember(dest => dest.DisplayNameWithTitle, opt => opt.MapFrom(src => $"{src.TrustGovernance.Title} {src.TrustGovernance.Forename1} {src.TrustGovernance.Surname}")) - .ForMember(dest => dest.Roles, opt => opt.MapFrom(src => new List { src.GovernanceRoleType.Name })) - .ForMember(dest => dest.UpdatedAt, opt => opt.MapFrom(src => src.TrustGovernance.Modified)); - } - } -} \ No newline at end of file diff --git a/Dfe.Academies.Application/Trust/Queries/GetAllPersonsAssociatedWithTrustByTrnOrUkprn/GetAllPersonsAssociatedWithTrustByTrnOrUkprn.cs b/Dfe.Academies.Application/Trust/Queries/GetAllPersonsAssociatedWithTrustByTrnOrUkprn/GetAllPersonsAssociatedWithTrustByTrnOrUkprn.cs deleted file mode 100644 index a51a1a89e..000000000 --- a/Dfe.Academies.Application/Trust/Queries/GetAllPersonsAssociatedWithTrustByTrnOrUkprn/GetAllPersonsAssociatedWithTrustByTrnOrUkprn.cs +++ /dev/null @@ -1,46 +0,0 @@ -using AutoMapper; -using AutoMapper.QueryableExtensions; -using Dfe.Academies.Application.Common.Interfaces; -using Dfe.Academies.Application.Common.Models; -using Dfe.Academies.Utils.Enums; -using Dfe.Academies.Utils.Helpers; -using DfE.CoreLibs.Caching.Helpers; -using DfE.CoreLibs.Caching.Interfaces; -using MediatR; -using Microsoft.EntityFrameworkCore; - -namespace Dfe.Academies.Application.Trust.Queries.GetAllPersonsAssociatedWithTrustByTrnOrUkprn -{ - public record GetAllPersonsAssociatedWithTrustByTrnOrUkprnQuery(string Id) : IRequest?>>; - - public class GetAllPersonsAssociatedWithTrustByTrnOrUkprnQueryHandler( - ITrustQueryService trustQueryService, - IMapper mapper, - ICacheService cacheService) - : IRequestHandler?>> - { - public async Task?>> Handle(GetAllPersonsAssociatedWithTrustByTrnOrUkprnQuery request, CancellationToken cancellationToken) - { - var idType = IdentifierHelper.DetermineIdType(request.Id, TrustIdValidator.GetTrustIdValidators()); - - var groupId = idType == TrustIdType.Trn ? request.Id : null; - var ukPrn = idType == TrustIdType.UkPrn ? request.Id : null; - - var cacheKey = $"PersonsAssociatedWithTrust_{CacheKeyHelper.GenerateHashedCacheKey(request.Id)}"; - - return await cacheService.GetOrAddAsync(cacheKey, async () => - { - var query = trustQueryService.GetTrustGovernanceByGroupIdOrUkprn(groupId, ukPrn); - if (query == null) - { - return Result?>.Failure("Trust not found."); - } - - return Result?>.Success(await query - .ProjectTo(mapper.ConfigurationProvider) - .ToListAsync(cancellationToken)); - - }, nameof(GetAllPersonsAssociatedWithTrustByTrnOrUkprnQueryHandler)); - } - } -} diff --git a/Dfe.Academies.Application/Trust/Queries/GetAllPersonsAssociatedWithTrustByTrnOrUkprn/GetAllPersonsAssociatedWithTrustByTrnOrUkprnValidator.cs b/Dfe.Academies.Application/Trust/Queries/GetAllPersonsAssociatedWithTrustByTrnOrUkprn/GetAllPersonsAssociatedWithTrustByTrnOrUkprnValidator.cs deleted file mode 100644 index d2401c665..000000000 --- a/Dfe.Academies.Application/Trust/Queries/GetAllPersonsAssociatedWithTrustByTrnOrUkprn/GetAllPersonsAssociatedWithTrustByTrnOrUkprnValidator.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Dfe.Academies.Application.Establishment.Queries.GetAllPersonsAssociatedWithAcademyByUrn; -using Dfe.Academies.Utils.Enums; -using Dfe.Academies.Utils.Helpers; -using FluentValidation; - -namespace Dfe.Academies.Application.Trust.Queries.GetAllPersonsAssociatedWithTrustByTrnOrUkprn -{ - public class GetAllPersonsAssociatedWithTrustByTrnOrUkprnValidator : AbstractValidator - { - public GetAllPersonsAssociatedWithTrustByTrnOrUkprnValidator() - { - RuleFor(query => query.Id) - .NotEmpty().WithMessage("An identifier must be provided.") - .Must(id => TrustIdValidator.GetTrustIdValidators()[TrustIdType.Trn](id) - || TrustIdValidator.GetTrustIdValidators()[TrustIdType.UkPrn](id)) - .WithMessage("The identifier must be either a valid TRN (TR{5 digits}) or a valid UKPRN (8 digits)."); - } - } -} \ No newline at end of file diff --git a/Dfe.Academies.Domain/Constituencies/Constituency.cs b/Dfe.Academies.Domain/Constituencies/Constituency.cs deleted file mode 100644 index 834f4452e..000000000 --- a/Dfe.Academies.Domain/Constituencies/Constituency.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Dfe.Academies.Domain.Common; -using Dfe.Academies.Domain.ValueObjects; - -namespace Dfe.Academies.Domain.Constituencies -{ -#pragma warning disable CS8618 - public class Constituency : IAggregateRoot - { - public ConstituencyId Id { get; } - public MemberId MemberId { get; private set; } - public string ConstituencyName { get; private set; } - public NameDetails NameDetails { get; private set; } - public DateTime LastRefresh { get; private set; } - public DateOnly? EndDate { get; private set; } - - public virtual MemberContactDetails MemberContactDetails { get; private set; } - public Constituency() { } - - public Constituency( - ConstituencyId constituencyId, - MemberId memberId, - string constituencyName, - NameDetails nameDetails, - DateTime lastRefresh, - DateOnly? endDate, - MemberContactDetails memberContactDetails) - { - Id = constituencyId ?? throw new ArgumentNullException(nameof(constituencyId)); - MemberId = memberId ?? throw new ArgumentNullException(nameof(memberId)); - ConstituencyName = constituencyName; - NameDetails = nameDetails ?? throw new ArgumentNullException(nameof(nameDetails)); - LastRefresh = lastRefresh; - EndDate = endDate; - MemberContactDetails = memberContactDetails; - } - } -#pragma warning restore CS8618 -} diff --git a/Dfe.Academies.Domain/Constituencies/MemberContactDetails.cs b/Dfe.Academies.Domain/Constituencies/MemberContactDetails.cs deleted file mode 100644 index 806a5d8db..000000000 --- a/Dfe.Academies.Domain/Constituencies/MemberContactDetails.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Dfe.Academies.Domain.Common; -using Dfe.Academies.Domain.ValueObjects; - -namespace Dfe.Academies.Domain.Constituencies -{ -#pragma warning disable CS8618 - - public class MemberContactDetails : IEntity - { - public MemberId Id { get; private set; } - public string? Email { get; private set; } - public string? Phone { get; private set; } - public int TypeId { get; private set; } - - private MemberContactDetails() { } - - public MemberContactDetails( - MemberId memberId, - int typeId, - string? email = null, - string? phone = null) - { - if (typeId <= 0) throw new ArgumentException("TypeId must be positive", nameof(typeId)); - - Id = memberId ?? throw new ArgumentNullException(nameof(memberId)); - TypeId = typeId; - Email = email; - Phone = phone; - } - } -#pragma warning restore CS8618 - -} diff --git a/Dfe.Academies.Domain/Interfaces/Repositories/IConstituencyRepository.cs b/Dfe.Academies.Domain/Interfaces/Repositories/IConstituencyRepository.cs deleted file mode 100644 index 45b3ca275..000000000 --- a/Dfe.Academies.Domain/Interfaces/Repositories/IConstituencyRepository.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Dfe.Academies.Domain.Constituencies; - -namespace Dfe.Academies.Domain.Interfaces.Repositories -{ - public interface IConstituencyRepository - { - Task GetMemberOfParliamentByConstituencyAsync(string constituencyName, CancellationToken cancellationToken); - IQueryable GetMembersOfParliamentByConstituenciesQueryable(List constituencyNames); - - } -} diff --git a/Dfe.Academies.Domain/ValueObjects/ConstituencyId.cs b/Dfe.Academies.Domain/ValueObjects/ConstituencyId.cs deleted file mode 100644 index 43f6261ed..000000000 --- a/Dfe.Academies.Domain/ValueObjects/ConstituencyId.cs +++ /dev/null @@ -1,6 +0,0 @@ -using Dfe.Academies.Domain.Common; - -namespace Dfe.Academies.Domain.ValueObjects -{ - public record ConstituencyId(int Value) : IStronglyTypedId; -} diff --git a/Dfe.Academies.Domain/ValueObjects/MemberId.cs b/Dfe.Academies.Domain/ValueObjects/MemberId.cs deleted file mode 100644 index 90819ba87..000000000 --- a/Dfe.Academies.Domain/ValueObjects/MemberId.cs +++ /dev/null @@ -1,6 +0,0 @@ -using Dfe.Academies.Domain.Common; - -namespace Dfe.Academies.Domain.ValueObjects -{ - public record MemberId(int Value) : IStronglyTypedId; -} diff --git a/Dfe.Academies.Domain/ValueObjects/NameDetails.cs b/Dfe.Academies.Domain/ValueObjects/NameDetails.cs deleted file mode 100644 index 1845b7413..000000000 --- a/Dfe.Academies.Domain/ValueObjects/NameDetails.cs +++ /dev/null @@ -1,6 +0,0 @@ -using Dfe.Academies.Domain.Common; - -namespace Dfe.Academies.Domain.ValueObjects -{ - public record NameDetails(string NameListAs, string NameDisplayAs, string NameFullTitle) : IStronglyTypedId; -} \ No newline at end of file diff --git a/Dfe.Academies.TramsDataApi.Tests.Integration/Controllers/V1/EstablishmentsControllerTests.cs b/Dfe.Academies.TramsDataApi.Tests.Integration/Controllers/V1/EstablishmentsControllerTests.cs index 8b8620a27..02f4cadce 100644 --- a/Dfe.Academies.TramsDataApi.Tests.Integration/Controllers/V1/EstablishmentsControllerTests.cs +++ b/Dfe.Academies.TramsDataApi.Tests.Integration/Controllers/V1/EstablishmentsControllerTests.cs @@ -1,8 +1,8 @@ -using Dfe.Academies.Tests.Common.Customizations; using DfE.CoreLibs.Testing.AutoFixture.Attributes; using DfE.CoreLibs.Testing.Mocks.WebApplicationFactory; using Dfe.TramsDataApi.Client.Contracts; using TramsDataApi; +using Dfe.Academies.Tests.Common.Customizations; namespace Dfe.Academies.TramsDataApi.Tests.Integration.Controllers.V1; diff --git a/Dfe.PersonsApi.Client/Dfe.PersonsApi.Client.csproj b/Dfe.PersonsApi.Client/Dfe.PersonsApi.Client.csproj deleted file mode 100644 index 947298372..000000000 --- a/Dfe.PersonsApi.Client/Dfe.PersonsApi.Client.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - net8.0 - enable - enable - true - $(NoWarn);1591 - true - 1.0.0 - readme.md - DfE Persons API Client - The Persons API Client Library provides a convenient and straightforward way to interact with the Persons API, a service that delivers contact and basic personal details of key individuals responsible within various organizations associated with the DfE. - DFE-Digital - - - - - - - - - - - - - - - - - - diff --git a/Dfe.PersonsApi.Client/Extensions/ServiceCollectionExtensions.cs b/Dfe.PersonsApi.Client/Extensions/ServiceCollectionExtensions.cs deleted file mode 100644 index eba42247d..000000000 --- a/Dfe.PersonsApi.Client/Extensions/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Dfe.PersonsApi.Client.Security; -using Dfe.PersonsApi.Client.Settings; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; - -namespace Dfe.PersonsApi.Client.Extensions -{ - [ExcludeFromCodeCoverage] - public static class ServiceCollectionExtensions - { - public static IServiceCollection AddPersonsApiClient( - this IServiceCollection services, - IConfiguration configuration, - HttpClient? existingHttpClient = null) - where TClientInterface : class - where TClientImplementation : class, TClientInterface - { - var apiSettings = new PersonsApiClientSettings(); - configuration.GetSection("PersonsApiClient").Bind(apiSettings); - - services.AddSingleton(apiSettings); - services.AddSingleton(); - - if (existingHttpClient != null) - { - services.AddSingleton(existingHttpClient); - services.AddTransient(serviceProvider => - { - return ActivatorUtilities.CreateInstance( - serviceProvider, existingHttpClient, apiSettings.BaseUrl!); - }); - } - else - { - services.AddHttpClient((httpClient, serviceProvider) => - { - httpClient.BaseAddress = new Uri(apiSettings.BaseUrl!); - - return ActivatorUtilities.CreateInstance( - serviceProvider, httpClient, apiSettings.BaseUrl!); - }) - .AddHttpMessageHandler(serviceProvider => - { - var tokenService = serviceProvider.GetRequiredService(); - return new BearerTokenHandler(tokenService); - }); - } - return services; - } - } -} diff --git a/Dfe.PersonsApi.Client/Generated/Client.g.cs b/Dfe.PersonsApi.Client/Generated/Client.g.cs deleted file mode 100644 index bdaa19d61..000000000 --- a/Dfe.PersonsApi.Client/Generated/Client.g.cs +++ /dev/null @@ -1,1012 +0,0 @@ -//---------------------- -// -// Generated using the NSwag toolchain v14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org) -// -//---------------------- - -using Dfe.PersonsApi.Client.Contracts; - -#pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." -#pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." -#pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' -#pragma warning disable 612 // Disable "CS0612 '...' is obsolete" -#pragma warning disable 649 // Disable "CS0649 Field is never assigned to, and will always have its default value null" -#pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... -#pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." -#pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" -#pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant" -#pragma warning disable 8603 // Disable "CS8603 Possible null reference return" -#pragma warning disable 8604 // Disable "CS8604 Possible null reference argument for parameter" -#pragma warning disable 8625 // Disable "CS8625 Cannot convert null literal to non-nullable reference type" -#pragma warning disable 8765 // Disable "CS8765 Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes)." - -namespace Dfe.PersonsApi.Client -{ - using System = global::System; - - [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class ConstituenciesClient : IConstituenciesClient - { - #pragma warning disable 8618 - private string _baseUrl; - #pragma warning restore 8618 - - private System.Net.Http.HttpClient _httpClient; - private static System.Lazy _settings = new System.Lazy(CreateSerializerSettings, true); - private Newtonsoft.Json.JsonSerializerSettings _instanceSettings; - - #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - public ConstituenciesClient(string baseUrl, System.Net.Http.HttpClient httpClient) - #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - { - BaseUrl = baseUrl; - _httpClient = httpClient; - Initialize(); - } - - private static Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings() - { - var settings = new Newtonsoft.Json.JsonSerializerSettings(); - UpdateJsonSerializerSettings(settings); - return settings; - } - - public string BaseUrl - { - get { return _baseUrl; } - set - { - _baseUrl = value; - if (!string.IsNullOrEmpty(_baseUrl) && !_baseUrl.EndsWith("/")) - _baseUrl += '/'; - } - } - - protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _instanceSettings ?? _settings.Value; } } - - static partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings); - - partial void Initialize(); - - partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); - partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); - partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); - - /// - /// Retrieve Member of Parliament by constituency name - /// - /// The constituency name. - /// A Person object representing the Member of Parliament. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetMemberOfParliamentByConstituencyAsync(string constituencyName) - { - return GetMemberOfParliamentByConstituencyAsync(constituencyName, System.Threading.CancellationToken.None); - } - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Retrieve Member of Parliament by constituency name - /// - /// The constituency name. - /// A Person object representing the Member of Parliament. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetMemberOfParliamentByConstituencyAsync(string constituencyName, System.Threading.CancellationToken cancellationToken) - { - if (constituencyName == null) - throw new System.ArgumentNullException("constituencyName"); - - var client_ = _httpClient; - var disposeClient_ = false; - try - { - using (var request_ = new System.Net.Http.HttpRequestMessage()) - { - request_.Method = new System.Net.Http.HttpMethod("GET"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); - - var urlBuilder_ = new System.Text.StringBuilder(); - if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/Constituencies/{constituencyName}/mp" - urlBuilder_.Append("v1/Constituencies/"); - urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(constituencyName, System.Globalization.CultureInfo.InvariantCulture))); - urlBuilder_.Append("/mp"); - - PrepareRequest(client_, request_, urlBuilder_); - - var url_ = urlBuilder_.ToString(); - request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); - - PrepareRequest(client_, request_, url_); - - var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - var disposeResponse_ = true; - try - { - var headers_ = new System.Collections.Generic.Dictionary>(); - foreach (var item_ in response_.Headers) - headers_[item_.Key] = item_.Value; - if (response_.Content != null && response_.Content.Headers != null) - { - foreach (var item_ in response_.Content.Headers) - headers_[item_.Key] = item_.Value; - } - - ProcessResponse(client_, response_); - - var status_ = (int)response_.StatusCode; - if (status_ == 200) - { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); - if (objectResponse_.Object == null) - { - throw new PersonsApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); - } - return objectResponse_.Object; - } - else - if (status_ == 404) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("Constituency not found.", status_, responseText_, headers_, null); - } - else - if (status_ == 400) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("Constituency cannot be null or empty.", status_, responseText_, headers_, null); - } - else - { - var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); - } - } - finally - { - if (disposeResponse_) - response_.Dispose(); - } - } - } - finally - { - if (disposeClient_) - client_.Dispose(); - } - } - - /// - /// Retrieve a collection of Member of Parliament by a collection of constituency names - /// - /// The request. - /// A collection of MemberOfParliament objects. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetMembersOfParliamentByConstituenciesAsync(GetMembersOfParliamentByConstituenciesQuery request) - { - return GetMembersOfParliamentByConstituenciesAsync(request, System.Threading.CancellationToken.None); - } - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Retrieve a collection of Member of Parliament by a collection of constituency names - /// - /// The request. - /// A collection of MemberOfParliament objects. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetMembersOfParliamentByConstituenciesAsync(GetMembersOfParliamentByConstituenciesQuery request, System.Threading.CancellationToken cancellationToken) - { - if (request == null) - throw new System.ArgumentNullException("request"); - - var client_ = _httpClient; - var disposeClient_ = false; - try - { - using (var request_ = new System.Net.Http.HttpRequestMessage()) - { - var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(request, JsonSerializerSettings); - var content_ = new System.Net.Http.StringContent(json_); - content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); - request_.Content = content_; - request_.Method = new System.Net.Http.HttpMethod("POST"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); - - var urlBuilder_ = new System.Text.StringBuilder(); - if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/Constituencies/mps" - urlBuilder_.Append("v1/Constituencies/mps"); - - PrepareRequest(client_, request_, urlBuilder_); - - var url_ = urlBuilder_.ToString(); - request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); - - PrepareRequest(client_, request_, url_); - - var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - var disposeResponse_ = true; - try - { - var headers_ = new System.Collections.Generic.Dictionary>(); - foreach (var item_ in response_.Headers) - headers_[item_.Key] = item_.Value; - if (response_.Content != null && response_.Content.Headers != null) - { - foreach (var item_ in response_.Content.Headers) - headers_[item_.Key] = item_.Value; - } - - ProcessResponse(client_, response_); - - var status_ = (int)response_.StatusCode; - if (status_ == 200) - { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); - if (objectResponse_.Object == null) - { - throw new PersonsApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); - } - return objectResponse_.Object; - } - else - if (status_ == 400) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("Constituency names cannot be null or empty.", status_, responseText_, headers_, null); - } - else - { - var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); - } - } - finally - { - if (disposeResponse_) - response_.Dispose(); - } - } - } - finally - { - if (disposeClient_) - client_.Dispose(); - } - } - - protected struct ObjectResponseResult - { - public ObjectResponseResult(T responseObject, string responseText) - { - this.Object = responseObject; - this.Text = responseText; - } - - public T Object { get; } - - public string Text { get; } - } - - public bool ReadResponseAsString { get; set; } - - protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) - { - if (response == null || response.Content == null) - { - return new ObjectResponseResult(default(T), string.Empty); - } - - if (ReadResponseAsString) - { - var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); - return new ObjectResponseResult(typedBody, responseText); - } - catch (Newtonsoft.Json.JsonException exception) - { - var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; - throw new PersonsApiException(message, (int)response.StatusCode, responseText, headers, exception); - } - } - else - { - try - { - using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) - using (var streamReader = new System.IO.StreamReader(responseStream)) - using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) - { - var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); - var typedBody = serializer.Deserialize(jsonTextReader); - return new ObjectResponseResult(typedBody, string.Empty); - } - } - catch (Newtonsoft.Json.JsonException exception) - { - var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; - throw new PersonsApiException(message, (int)response.StatusCode, string.Empty, headers, exception); - } - } - } - - private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) - { - if (value == null) - { - return ""; - } - - if (value is System.Enum) - { - var name = System.Enum.GetName(value.GetType(), value); - if (name != null) - { - var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); - if (field != null) - { - var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) - as System.Runtime.Serialization.EnumMemberAttribute; - if (attribute != null) - { - return attribute.Value != null ? attribute.Value : name; - } - } - - var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); - return converted == null ? string.Empty : converted; - } - } - else if (value is bool) - { - return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); - } - else if (value is byte[]) - { - return System.Convert.ToBase64String((byte[]) value); - } - else if (value is string[]) - { - return string.Join(",", (string[])value); - } - else if (value.GetType().IsArray) - { - var valueArray = (System.Array)value; - var valueTextArray = new string[valueArray.Length]; - for (var i = 0; i < valueArray.Length; i++) - { - valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); - } - return string.Join(",", valueTextArray); - } - - var result = System.Convert.ToString(value, cultureInfo); - return result == null ? "" : result; - } - } - - [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class EstablishmentsClient : IEstablishmentsClient - { - #pragma warning disable 8618 - private string _baseUrl; - #pragma warning restore 8618 - - private System.Net.Http.HttpClient _httpClient; - private static System.Lazy _settings = new System.Lazy(CreateSerializerSettings, true); - private Newtonsoft.Json.JsonSerializerSettings _instanceSettings; - - #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - public EstablishmentsClient(string baseUrl, System.Net.Http.HttpClient httpClient) - #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - { - BaseUrl = baseUrl; - _httpClient = httpClient; - Initialize(); - } - - private static Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings() - { - var settings = new Newtonsoft.Json.JsonSerializerSettings(); - UpdateJsonSerializerSettings(settings); - return settings; - } - - public string BaseUrl - { - get { return _baseUrl; } - set - { - _baseUrl = value; - if (!string.IsNullOrEmpty(_baseUrl) && !_baseUrl.EndsWith("/")) - _baseUrl += '/'; - } - } - - protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _instanceSettings ?? _settings.Value; } } - - static partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings); - - partial void Initialize(); - - partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); - partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); - partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); - - /// - /// Retrieve All Members Associated With an Academy by Urn - /// - /// The URN. - /// A Collection of Persons Associated With the Academy. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetAllPersonsAssociatedWithAcademyByUrnAsync(int urn) - { - return GetAllPersonsAssociatedWithAcademyByUrnAsync(urn, System.Threading.CancellationToken.None); - } - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Retrieve All Members Associated With an Academy by Urn - /// - /// The URN. - /// A Collection of Persons Associated With the Academy. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetAllPersonsAssociatedWithAcademyByUrnAsync(int urn, System.Threading.CancellationToken cancellationToken) - { - if (urn == null) - throw new System.ArgumentNullException("urn"); - - var client_ = _httpClient; - var disposeClient_ = false; - try - { - using (var request_ = new System.Net.Http.HttpRequestMessage()) - { - request_.Method = new System.Net.Http.HttpMethod("GET"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); - - var urlBuilder_ = new System.Text.StringBuilder(); - if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/Establishments/{urn}/getAssociatedPersons" - urlBuilder_.Append("v1/Establishments/"); - urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(urn, System.Globalization.CultureInfo.InvariantCulture))); - urlBuilder_.Append("/getAssociatedPersons"); - - PrepareRequest(client_, request_, urlBuilder_); - - var url_ = urlBuilder_.ToString(); - request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); - - PrepareRequest(client_, request_, url_); - - var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - var disposeResponse_ = true; - try - { - var headers_ = new System.Collections.Generic.Dictionary>(); - foreach (var item_ in response_.Headers) - headers_[item_.Key] = item_.Value; - if (response_.Content != null && response_.Content.Headers != null) - { - foreach (var item_ in response_.Content.Headers) - headers_[item_.Key] = item_.Value; - } - - ProcessResponse(client_, response_); - - var status_ = (int)response_.StatusCode; - if (status_ == 200) - { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); - if (objectResponse_.Object == null) - { - throw new PersonsApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); - } - return objectResponse_.Object; - } - else - if (status_ == 404) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("Academy not found.\nor\nConstituency not found for the given establishment.", status_, responseText_, headers_, null); - } - else - { - var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); - } - } - finally - { - if (disposeResponse_) - response_.Dispose(); - } - } - } - finally - { - if (disposeClient_) - client_.Dispose(); - } - } - - /// - /// Get Member of Parliament by School (Urn) - /// - /// The URN. - /// Member of Parliament - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetMemberOfParliamentBySchoolUrnAsync(int urn) - { - return GetMemberOfParliamentBySchoolUrnAsync(urn, System.Threading.CancellationToken.None); - } - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Get Member of Parliament by School (Urn) - /// - /// The URN. - /// Member of Parliament - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetMemberOfParliamentBySchoolUrnAsync(int urn, System.Threading.CancellationToken cancellationToken) - { - if (urn == null) - throw new System.ArgumentNullException("urn"); - - var client_ = _httpClient; - var disposeClient_ = false; - try - { - using (var request_ = new System.Net.Http.HttpRequestMessage()) - { - request_.Method = new System.Net.Http.HttpMethod("GET"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); - - var urlBuilder_ = new System.Text.StringBuilder(); - if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/Establishments/{urn}/getMpBySchool" - urlBuilder_.Append("v1/Establishments/"); - urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(urn, System.Globalization.CultureInfo.InvariantCulture))); - urlBuilder_.Append("/getMpBySchool"); - - PrepareRequest(client_, request_, urlBuilder_); - - var url_ = urlBuilder_.ToString(); - request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); - - PrepareRequest(client_, request_, url_); - - var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - var disposeResponse_ = true; - try - { - var headers_ = new System.Collections.Generic.Dictionary>(); - foreach (var item_ in response_.Headers) - headers_[item_.Key] = item_.Value; - if (response_.Content != null && response_.Content.Headers != null) - { - foreach (var item_ in response_.Content.Headers) - headers_[item_.Key] = item_.Value; - } - - ProcessResponse(client_, response_); - - var status_ = (int)response_.StatusCode; - if (status_ == 200) - { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); - if (objectResponse_.Object == null) - { - throw new PersonsApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); - } - return objectResponse_.Object; - } - else - if (status_ == 404) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("School Not found.", status_, responseText_, headers_, null); - } - else - { - var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); - } - } - finally - { - if (disposeResponse_) - response_.Dispose(); - } - } - } - finally - { - if (disposeClient_) - client_.Dispose(); - } - } - - protected struct ObjectResponseResult - { - public ObjectResponseResult(T responseObject, string responseText) - { - this.Object = responseObject; - this.Text = responseText; - } - - public T Object { get; } - - public string Text { get; } - } - - public bool ReadResponseAsString { get; set; } - - protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) - { - if (response == null || response.Content == null) - { - return new ObjectResponseResult(default(T), string.Empty); - } - - if (ReadResponseAsString) - { - var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); - return new ObjectResponseResult(typedBody, responseText); - } - catch (Newtonsoft.Json.JsonException exception) - { - var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; - throw new PersonsApiException(message, (int)response.StatusCode, responseText, headers, exception); - } - } - else - { - try - { - using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) - using (var streamReader = new System.IO.StreamReader(responseStream)) - using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) - { - var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); - var typedBody = serializer.Deserialize(jsonTextReader); - return new ObjectResponseResult(typedBody, string.Empty); - } - } - catch (Newtonsoft.Json.JsonException exception) - { - var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; - throw new PersonsApiException(message, (int)response.StatusCode, string.Empty, headers, exception); - } - } - } - - private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) - { - if (value == null) - { - return ""; - } - - if (value is System.Enum) - { - var name = System.Enum.GetName(value.GetType(), value); - if (name != null) - { - var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); - if (field != null) - { - var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) - as System.Runtime.Serialization.EnumMemberAttribute; - if (attribute != null) - { - return attribute.Value != null ? attribute.Value : name; - } - } - - var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); - return converted == null ? string.Empty : converted; - } - } - else if (value is bool) - { - return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); - } - else if (value is byte[]) - { - return System.Convert.ToBase64String((byte[]) value); - } - else if (value is string[]) - { - return string.Join(",", (string[])value); - } - else if (value.GetType().IsArray) - { - var valueArray = (System.Array)value; - var valueTextArray = new string[valueArray.Length]; - for (var i = 0; i < valueArray.Length; i++) - { - valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); - } - return string.Join(",", valueTextArray); - } - - var result = System.Convert.ToString(value, cultureInfo); - return result == null ? "" : result; - } - } - - [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class TrustsClient : ITrustsClient - { - #pragma warning disable 8618 - private string _baseUrl; - #pragma warning restore 8618 - - private System.Net.Http.HttpClient _httpClient; - private static System.Lazy _settings = new System.Lazy(CreateSerializerSettings, true); - private Newtonsoft.Json.JsonSerializerSettings _instanceSettings; - - #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - public TrustsClient(string baseUrl, System.Net.Http.HttpClient httpClient) - #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - { - BaseUrl = baseUrl; - _httpClient = httpClient; - Initialize(); - } - - private static Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings() - { - var settings = new Newtonsoft.Json.JsonSerializerSettings(); - UpdateJsonSerializerSettings(settings); - return settings; - } - - public string BaseUrl - { - get { return _baseUrl; } - set - { - _baseUrl = value; - if (!string.IsNullOrEmpty(_baseUrl) && !_baseUrl.EndsWith("/")) - _baseUrl += '/'; - } - } - - protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _instanceSettings ?? _settings.Value; } } - - static partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings); - - partial void Initialize(); - - partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); - partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); - partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); - - /// - /// Retrieve All Members Associated With a Trust by Either UKPRN or TRN - /// - /// The identifier (UKPRN or TRN). - /// A Collection of Persons Associated With the Trust. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetAllPersonsAssociatedWithTrustByTrnOrUkPrnAsync(string id) - { - return GetAllPersonsAssociatedWithTrustByTrnOrUkPrnAsync(id, System.Threading.CancellationToken.None); - } - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Retrieve All Members Associated With a Trust by Either UKPRN or TRN - /// - /// The identifier (UKPRN or TRN). - /// A Collection of Persons Associated With the Trust. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetAllPersonsAssociatedWithTrustByTrnOrUkPrnAsync(string id, System.Threading.CancellationToken cancellationToken) - { - if (id == null) - throw new System.ArgumentNullException("id"); - - var client_ = _httpClient; - var disposeClient_ = false; - try - { - using (var request_ = new System.Net.Http.HttpRequestMessage()) - { - request_.Method = new System.Net.Http.HttpMethod("GET"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); - - var urlBuilder_ = new System.Text.StringBuilder(); - if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/Trusts/{id}/getAssociatedPersons" - urlBuilder_.Append("v1/Trusts/"); - urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); - urlBuilder_.Append("/getAssociatedPersons"); - - PrepareRequest(client_, request_, urlBuilder_); - - var url_ = urlBuilder_.ToString(); - request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); - - PrepareRequest(client_, request_, url_); - - var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - var disposeResponse_ = true; - try - { - var headers_ = new System.Collections.Generic.Dictionary>(); - foreach (var item_ in response_.Headers) - headers_[item_.Key] = item_.Value; - if (response_.Content != null && response_.Content.Headers != null) - { - foreach (var item_ in response_.Content.Headers) - headers_[item_.Key] = item_.Value; - } - - ProcessResponse(client_, response_); - - var status_ = (int)response_.StatusCode; - if (status_ == 200) - { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); - if (objectResponse_.Object == null) - { - throw new PersonsApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); - } - return objectResponse_.Object; - } - else - if (status_ == 404) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("Trust not found.", status_, responseText_, headers_, null); - } - else - { - var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new PersonsApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); - } - } - finally - { - if (disposeResponse_) - response_.Dispose(); - } - } - } - finally - { - if (disposeClient_) - client_.Dispose(); - } - } - - protected struct ObjectResponseResult - { - public ObjectResponseResult(T responseObject, string responseText) - { - this.Object = responseObject; - this.Text = responseText; - } - - public T Object { get; } - - public string Text { get; } - } - - public bool ReadResponseAsString { get; set; } - - protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) - { - if (response == null || response.Content == null) - { - return new ObjectResponseResult(default(T), string.Empty); - } - - if (ReadResponseAsString) - { - var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); - return new ObjectResponseResult(typedBody, responseText); - } - catch (Newtonsoft.Json.JsonException exception) - { - var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; - throw new PersonsApiException(message, (int)response.StatusCode, responseText, headers, exception); - } - } - else - { - try - { - using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) - using (var streamReader = new System.IO.StreamReader(responseStream)) - using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) - { - var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); - var typedBody = serializer.Deserialize(jsonTextReader); - return new ObjectResponseResult(typedBody, string.Empty); - } - } - catch (Newtonsoft.Json.JsonException exception) - { - var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; - throw new PersonsApiException(message, (int)response.StatusCode, string.Empty, headers, exception); - } - } - } - - private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) - { - if (value == null) - { - return ""; - } - - if (value is System.Enum) - { - var name = System.Enum.GetName(value.GetType(), value); - if (name != null) - { - var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); - if (field != null) - { - var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) - as System.Runtime.Serialization.EnumMemberAttribute; - if (attribute != null) - { - return attribute.Value != null ? attribute.Value : name; - } - } - - var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); - return converted == null ? string.Empty : converted; - } - } - else if (value is bool) - { - return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); - } - else if (value is byte[]) - { - return System.Convert.ToBase64String((byte[]) value); - } - else if (value is string[]) - { - return string.Join(",", (string[])value); - } - else if (value.GetType().IsArray) - { - var valueArray = (System.Array)value; - var valueTextArray = new string[valueArray.Length]; - for (var i = 0; i < valueArray.Length; i++) - { - valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); - } - return string.Join(",", valueTextArray); - } - - var result = System.Convert.ToString(value, cultureInfo); - return result == null ? "" : result; - } - } - -} - -#pragma warning restore 108 -#pragma warning restore 114 -#pragma warning restore 472 -#pragma warning restore 612 -#pragma warning restore 1573 -#pragma warning restore 1591 -#pragma warning restore 8073 -#pragma warning restore 3016 -#pragma warning restore 8603 -#pragma warning restore 8604 -#pragma warning restore 8625 \ No newline at end of file diff --git a/Dfe.PersonsApi.Client/Generated/Contracts.g.cs b/Dfe.PersonsApi.Client/Generated/Contracts.g.cs deleted file mode 100644 index 87c282fa3..000000000 --- a/Dfe.PersonsApi.Client/Generated/Contracts.g.cs +++ /dev/null @@ -1,309 +0,0 @@ -//---------------------- -// -// Generated using the NSwag toolchain v14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org) -// -//---------------------- - -#pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." -#pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." -#pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' -#pragma warning disable 612 // Disable "CS0612 '...' is obsolete" -#pragma warning disable 649 // Disable "CS0649 Field is never assigned to, and will always have its default value null" -#pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... -#pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." -#pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" -#pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant" -#pragma warning disable 8603 // Disable "CS8603 Possible null reference return" -#pragma warning disable 8604 // Disable "CS8604 Possible null reference argument for parameter" -#pragma warning disable 8625 // Disable "CS8625 Cannot convert null literal to non-nullable reference type" -#pragma warning disable 8765 // Disable "CS8765 Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes)." - -namespace Dfe.PersonsApi.Client.Contracts -{ - using System = global::System; - - [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial interface IConstituenciesClient - { - /// - /// Retrieve Member of Parliament by constituency name - /// - /// The constituency name. - /// A Person object representing the Member of Parliament. - /// A server side error occurred. - System.Threading.Tasks.Task GetMemberOfParliamentByConstituencyAsync(string constituencyName); - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Retrieve Member of Parliament by constituency name - /// - /// The constituency name. - /// A Person object representing the Member of Parliament. - /// A server side error occurred. - System.Threading.Tasks.Task GetMemberOfParliamentByConstituencyAsync(string constituencyName, System.Threading.CancellationToken cancellationToken); - - /// - /// Retrieve a collection of Member of Parliament by a collection of constituency names - /// - /// The request. - /// A collection of MemberOfParliament objects. - /// A server side error occurred. - System.Threading.Tasks.Task> GetMembersOfParliamentByConstituenciesAsync(GetMembersOfParliamentByConstituenciesQuery request); - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Retrieve a collection of Member of Parliament by a collection of constituency names - /// - /// The request. - /// A collection of MemberOfParliament objects. - /// A server side error occurred. - System.Threading.Tasks.Task> GetMembersOfParliamentByConstituenciesAsync(GetMembersOfParliamentByConstituenciesQuery request, System.Threading.CancellationToken cancellationToken); - - } - - [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial interface IEstablishmentsClient - { - /// - /// Retrieve All Members Associated With an Academy by Urn - /// - /// The URN. - /// A Collection of Persons Associated With the Academy. - /// A server side error occurred. - System.Threading.Tasks.Task> GetAllPersonsAssociatedWithAcademyByUrnAsync(int urn); - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Retrieve All Members Associated With an Academy by Urn - /// - /// The URN. - /// A Collection of Persons Associated With the Academy. - /// A server side error occurred. - System.Threading.Tasks.Task> GetAllPersonsAssociatedWithAcademyByUrnAsync(int urn, System.Threading.CancellationToken cancellationToken); - - /// - /// Get Member of Parliament by School (Urn) - /// - /// The URN. - /// Member of Parliament - /// A server side error occurred. - System.Threading.Tasks.Task GetMemberOfParliamentBySchoolUrnAsync(int urn); - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Get Member of Parliament by School (Urn) - /// - /// The URN. - /// Member of Parliament - /// A server side error occurred. - System.Threading.Tasks.Task GetMemberOfParliamentBySchoolUrnAsync(int urn, System.Threading.CancellationToken cancellationToken); - - } - - [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial interface ITrustsClient - { - /// - /// Retrieve All Members Associated With a Trust by Either UKPRN or TRN - /// - /// The identifier (UKPRN or TRN). - /// A Collection of Persons Associated With the Trust. - /// A server side error occurred. - System.Threading.Tasks.Task> GetAllPersonsAssociatedWithTrustByTrnOrUkPrnAsync(string id); - - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. - /// - /// Retrieve All Members Associated With a Trust by Either UKPRN or TRN - /// - /// The identifier (UKPRN or TRN). - /// A Collection of Persons Associated With the Trust. - /// A server side error occurred. - System.Threading.Tasks.Task> GetAllPersonsAssociatedWithTrustByTrnOrUkPrnAsync(string id, System.Threading.CancellationToken cancellationToken); - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class MemberOfParliament : Person - { - [Newtonsoft.Json.JsonProperty("constituencyName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string ConstituencyName { get; set; } - - public string ToJson() - { - - return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); - - } - public static MemberOfParliament FromJson(string data) - { - - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); - - } - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Person - { - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public int Id { get; set; } - - [Newtonsoft.Json.JsonProperty("firstName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string FirstName { get; set; } - - [Newtonsoft.Json.JsonProperty("lastName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string LastName { get; set; } - - [Newtonsoft.Json.JsonProperty("email", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Email { get; set; } - - [Newtonsoft.Json.JsonProperty("displayName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string DisplayName { get; set; } - - [Newtonsoft.Json.JsonProperty("displayNameWithTitle", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string DisplayNameWithTitle { get; set; } - - [Newtonsoft.Json.JsonProperty("phone", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Phone { get; set; } - - [Newtonsoft.Json.JsonProperty("roles", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.List Roles { get; set; } - - [Newtonsoft.Json.JsonProperty("updatedAt", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.DateTime? UpdatedAt { get; set; } - - public string ToJson() - { - - return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); - - } - public static Person FromJson(string data) - { - - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); - - } - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class GetMembersOfParliamentByConstituenciesQuery - { - [Newtonsoft.Json.JsonProperty("constituencyNames", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.List ConstituencyNames { get; set; } - - public string ToJson() - { - - return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); - - } - public static GetMembersOfParliamentByConstituenciesQuery FromJson(string data) - { - - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); - - } - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class AcademyGovernance : Person - { - [Newtonsoft.Json.JsonProperty("ukprn", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Ukprn { get; set; } - - [Newtonsoft.Json.JsonProperty("urn", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public int? Urn { get; set; } - - public string ToJson() - { - - return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); - - } - public static AcademyGovernance FromJson(string data) - { - - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); - - } - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class TrustGovernance : Person - { - [Newtonsoft.Json.JsonProperty("ukprn", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Ukprn { get; set; } - - [Newtonsoft.Json.JsonProperty("trn", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Trn { get; set; } - - public string ToJson() - { - - return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); - - } - public static TrustGovernance FromJson(string data) - { - - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); - - } - - } - - - - [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class PersonsApiException : System.Exception - { - public int StatusCode { get; private set; } - - public string Response { get; private set; } - - public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } - - public PersonsApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception innerException) - : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + ((response == null) ? "(null)" : response.Substring(0, response.Length >= 512 ? 512 : response.Length)), innerException) - { - StatusCode = statusCode; - Response = response; - Headers = headers; - } - - public override string ToString() - { - return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString()); - } - } - - [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class PersonsApiException : PersonsApiException - { - public TResult Result { get; private set; } - - public PersonsApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception innerException) - : base(message, statusCode, response, headers, innerException) - { - Result = result; - } - } - -} - -#pragma warning restore 108 -#pragma warning restore 114 -#pragma warning restore 472 -#pragma warning restore 612 -#pragma warning restore 1573 -#pragma warning restore 1591 -#pragma warning restore 8073 -#pragma warning restore 3016 -#pragma warning restore 8603 -#pragma warning restore 8604 -#pragma warning restore 8625 \ No newline at end of file diff --git a/Dfe.PersonsApi.Client/Generated/swagger.json b/Dfe.PersonsApi.Client/Generated/swagger.json deleted file mode 100644 index 4c72d9c4a..000000000 --- a/Dfe.PersonsApi.Client/Generated/swagger.json +++ /dev/null @@ -1,320 +0,0 @@ -{ - "x-generator": "NSwag v14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))", - "openapi": "3.0.0", - "info": { - "title": "PersonsApi", - "version": "1.0.0" - }, - "paths": { - "/v1/Constituencies/{constituencyName}/mp": { - "get": { - "tags": [ - "Constituencies" - ], - "summary": "Retrieve Member of Parliament by constituency name", - "operationId": "Constituencies_GetMemberOfParliamentByConstituency", - "parameters": [ - { - "name": "constituencyName", - "in": "path", - "required": true, - "description": "The constituency name.", - "schema": { - "type": "string" - }, - "x-position": 1 - } - ], - "responses": { - "200": { - "description": "A Person object representing the Member of Parliament.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MemberOfParliament" - } - } - } - }, - "404": { - "description": "Constituency not found." - }, - "400": { - "description": "Constituency cannot be null or empty." - } - } - } - }, - "/v1/Constituencies/mps": { - "post": { - "tags": [ - "Constituencies" - ], - "summary": "Retrieve a collection of Member of Parliament by a collection of constituency names", - "operationId": "Constituencies_GetMembersOfParliamentByConstituencies", - "requestBody": { - "x-name": "request", - "description": "The request.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GetMembersOfParliamentByConstituenciesQuery" - } - } - }, - "required": true, - "x-position": 1 - }, - "responses": { - "200": { - "description": "A collection of MemberOfParliament objects.", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/MemberOfParliament" - } - } - } - } - }, - "400": { - "description": "Constituency names cannot be null or empty." - } - } - } - }, - "/v1/Establishments/{urn}/getAssociatedPersons": { - "get": { - "tags": [ - "Establishments" - ], - "summary": "Retrieve All Members Associated With an Academy by Urn", - "operationId": "Establishments_GetAllPersonsAssociatedWithAcademyByUrn", - "parameters": [ - { - "name": "urn", - "in": "path", - "required": true, - "description": "The URN.", - "schema": { - "type": "integer", - "format": "int32" - }, - "x-position": 1 - } - ], - "responses": { - "200": { - "description": "A Collection of Persons Associated With the Academy.", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AcademyGovernance" - } - } - } - } - }, - "404": { - "description": "Academy not found.\nor\nConstituency not found for the given establishment." - } - } - } - }, - "/v1/Establishments/{urn}/getMpBySchool": { - "get": { - "tags": [ - "Establishments" - ], - "summary": "Get Member of Parliament by School (Urn)", - "operationId": "Establishments_GetMemberOfParliamentBySchoolUrn", - "parameters": [ - { - "name": "urn", - "in": "path", - "required": true, - "description": "The URN.", - "schema": { - "type": "integer", - "format": "int32" - }, - "x-position": 1 - } - ], - "responses": { - "200": { - "description": "Member of Parliament", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MemberOfParliament" - } - } - } - }, - "404": { - "description": "School Not found." - } - } - } - }, - "/v1/Trusts/{id}/getAssociatedPersons": { - "get": { - "tags": [ - "Trusts" - ], - "summary": "Retrieve All Members Associated With a Trust by Either UKPRN or TRN", - "operationId": "Trusts_GetAllPersonsAssociatedWithTrustByTrnOrUkPrn", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "description": "The identifier (UKPRN or TRN).", - "schema": { - "type": "string" - }, - "x-position": 1 - } - ], - "responses": { - "200": { - "description": "A Collection of Persons Associated With the Trust.", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/TrustGovernance" - } - } - } - } - }, - "404": { - "description": "Trust not found." - } - } - } - } - }, - "components": { - "schemas": { - "MemberOfParliament": { - "allOf": [ - { - "$ref": "#/components/schemas/Person" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "constituencyName": { - "type": "string" - } - } - } - ] - }, - "Person": { - "type": "object", - "additionalProperties": false, - "properties": { - "id": { - "type": "integer", - "format": "int32" - }, - "firstName": { - "type": "string" - }, - "lastName": { - "type": "string" - }, - "email": { - "type": "string" - }, - "displayName": { - "type": "string" - }, - "displayNameWithTitle": { - "type": "string" - }, - "phone": { - "type": "string", - "nullable": true - }, - "roles": { - "type": "array", - "items": { - "type": "string" - } - }, - "updatedAt": { - "type": "string", - "format": "date-time", - "nullable": true - } - } - }, - "GetMembersOfParliamentByConstituenciesQuery": { - "type": "object", - "additionalProperties": false, - "properties": { - "constituencyNames": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "AcademyGovernance": { - "allOf": [ - { - "$ref": "#/components/schemas/Person" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "ukprn": { - "type": "string", - "nullable": true - }, - "urn": { - "type": "integer", - "format": "int32", - "nullable": true - } - } - } - ] - }, - "TrustGovernance": { - "allOf": [ - { - "$ref": "#/components/schemas/Person" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "ukprn": { - "type": "string", - "nullable": true - }, - "trn": { - "type": "string", - "nullable": true - } - } - } - ] - } - } - } -} \ No newline at end of file diff --git a/Dfe.PersonsApi.Client/Security/BearerTokenHandler.cs b/Dfe.PersonsApi.Client/Security/BearerTokenHandler.cs deleted file mode 100644 index 66633935c..000000000 --- a/Dfe.PersonsApi.Client/Security/BearerTokenHandler.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Net.Http.Headers; - -namespace Dfe.PersonsApi.Client.Security -{ - [ExcludeFromCodeCoverage] - public class BearerTokenHandler(ITokenAcquisitionService tokenAcquisitionService) : DelegatingHandler - { - protected override async Task SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) - { - var token = await tokenAcquisitionService.GetTokenAsync(); - - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); - - return await base.SendAsync(request, cancellationToken); - } - } -} diff --git a/Dfe.PersonsApi.Client/Security/ITokenAcquisitionService.cs b/Dfe.PersonsApi.Client/Security/ITokenAcquisitionService.cs deleted file mode 100644 index 4d61acc1e..000000000 --- a/Dfe.PersonsApi.Client/Security/ITokenAcquisitionService.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Dfe.PersonsApi.Client.Security -{ - public interface ITokenAcquisitionService - { - Task GetTokenAsync(); - } -} diff --git a/Dfe.PersonsApi.Client/Security/TokenAcquisitionService.cs b/Dfe.PersonsApi.Client/Security/TokenAcquisitionService.cs deleted file mode 100644 index 1109ea00b..000000000 --- a/Dfe.PersonsApi.Client/Security/TokenAcquisitionService.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Dfe.PersonsApi.Client.Settings; -using Microsoft.Identity.Client; -using System.Diagnostics.CodeAnalysis; - -namespace Dfe.PersonsApi.Client.Security -{ - [ExcludeFromCodeCoverage] - public class TokenAcquisitionService : ITokenAcquisitionService - { - private readonly PersonsApiClientSettings _settings; - private readonly Lazy _app; - - public TokenAcquisitionService(PersonsApiClientSettings settings) - { - _settings = settings ?? throw new ArgumentNullException(nameof(settings)); - - _app = new Lazy(() => - ConfidentialClientApplicationBuilder.Create(_settings.ClientId) - .WithClientSecret(_settings.ClientSecret) - .WithAuthority(new Uri(_settings.Authority!)) - .Build()); - } - - public async Task GetTokenAsync() - { - var authResult = await _app.Value.AcquireTokenForClient(new[] { _settings.Scope }) - .ExecuteAsync(); - - return authResult.AccessToken; - } - } -} \ No newline at end of file diff --git a/Dfe.PersonsApi.Client/Settings/PersonsApiClientSettings.cs b/Dfe.PersonsApi.Client/Settings/PersonsApiClientSettings.cs deleted file mode 100644 index e160840b2..000000000 --- a/Dfe.PersonsApi.Client/Settings/PersonsApiClientSettings.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Dfe.PersonsApi.Client.Settings -{ - public class PersonsApiClientSettings - { - public string? BaseUrl { get; set; } - public string? ClientId { get; set; } - public string? ClientSecret { get; set; } - public string? Authority { get; set; } - public string? Scope { get; set; } - } -} diff --git a/Dfe.PersonsApi.Client/nswag.json b/Dfe.PersonsApi.Client/nswag.json deleted file mode 100644 index 9ef55b071..000000000 --- a/Dfe.PersonsApi.Client/nswag.json +++ /dev/null @@ -1,145 +0,0 @@ -{ - "runtime": "Net80", - "defaultVariables": "CSharpOutputPath=../Dfe.PersonsApi.Client", - "documentGenerator": { - "aspNetCoreToOpenApi": { - "project": "../PersonsApi/PersonsApi.csproj", - "msBuildProjectExtensionsPath": null, - "configuration": "Debug", - "runtime": "", - "targetFramework": "net8.0", - "noBuild": true, - "verbose": true, - "workingDirectory": "../PersonsApi", - "requireParametersWithoutDefault": true, - "apiGroupNames": null, - "defaultPropertyNameHandling": "CamelCase", - "defaultReferenceTypeNullHandling": "Null", - "defaultDictionaryValueReferenceTypeNullHandling": "NotNull", - "defaultResponseReferenceTypeNullHandling": "NotNull", - "defaultEnumHandling": "Integer", - "flattenInheritanceHierarchy": false, - "generateKnownTypes": true, - "generateEnumMappingDescription": false, - "generateXmlObjects": false, - "generateAbstractProperties": true, - "generateAbstractSchemas": true, - "ignoreObsoleteProperties": false, - "allowReferencesWithProperties": false, - "excludedTypeNames": [], - "serviceHost": null, - "serviceBasePath": null, - "serviceSchemes": [], - "infoTitle": "Persons API", - "infoDescription": "API documentation for Persons API", - "infoVersion": "1.0.0", - "documentTemplate": null, - "documentProcessorTypes": [], - "operationProcessorTypes": [], - "typeNameGeneratorType": null, - "schemaNameGeneratorType": null, - "contractResolverType": null, - "serializerSettingsType": null, - "useDocumentProvider": false, - "documentName": "v1", - "aspNetCoreEnvironment": "CodeGeneration", - "createWebHostBuilderMethod": null, - "startupType": null, - "allowNullableBodyParameters": true, - "output": "$(CSharpOutputPath)/Generated/swagger.json", - "outputType": "OpenApi3", - "newLineBehavior": "Auto", - "assemblyPaths": [], - "assemblyConfig": null, - "referencePaths": [], - "useNuGetCache": false - } - }, - "codeGenerators": { - "openApiToCSharpClient": { - "clientBaseClass": null, - "configurationClass": null, - "generateClientClasses": true, - "generateClientInterfaces": true, - "clientBaseInterface": null, - "injectHttpClient": true, - "disposeHttpClient": false, - "protectedMethods": [], - "generateExceptionClasses": true, - "exceptionClass": "PersonsApiException", - "wrapDtoExceptions": true, - "useHttpClientCreationMethod": false, - "httpClientType": "System.Net.Http.HttpClient", - "useHttpRequestMessageCreationMethod": false, - "useBaseUrl": true, - "generateBaseUrlProperty": true, - "generateSyncMethods": false, - "exposeJsonSerializerSettings": false, - "clientClassAccessModifier": "public", - "typeAccessModifier": "public", - "generateContractsOutput": true, - "contractsNamespace": "Dfe.PersonsApi.Client.Contracts", - "contractsOutputFilePath": "$(CSharpOutputPath)/Generated/Contracts.g.cs", - "parameterDateTimeFormat": "s", - "parameterDateFormat": "yyyy-MM-dd", - "generateUpdateJsonSerializerSettingsMethod": true, - "useRequestAndResponseSerializationSettings": false, - "serializeTypeInformation": false, - "queryNullValue": "", - "className": "{controller}Client", - "operationGenerationMode": "MultipleClientsFromOperationId", - "additionalNamespaceUsages": [], - "additionalContractNamespaceUsages": [], - "generateOptionalParameters": false, - "generateJsonMethods": true, - "generateXmlDocumentation": true, - "enforceFlagEnums": false, - "parameterArrayType": "System.Collections.Generic.IEnumerable", - "parameterDictionaryType": "System.Collections.Generic.IDictionary", - "responseArrayType": "System.Collections.ObjectModel.ObservableCollection", - "responseDictionaryType": "System.Collections.Generic.Dictionary", - "wrapResponses": false, - "wrapResponseMethods": [], - "generateResponseClasses": true, - "responseClass": "PersonsApiResponse", - "namespace": "Dfe.PersonsApi.Client", - "requiredPropertiesMustBeDefined": true, - "dateType": "System.DateTime", - "jsonConverters": null, - "anyType": "object", - "dateTimeType": "System.DateTime", - "timeType": "System.TimeSpan", - "timeSpanType": "System.TimeSpan", - "arrayType": "System.Collections.Generic.List", - "arrayInstanceType": "System.Collections.Generic.List", - "dictionaryType": "System.Collections.Generic.Dictionary", - "dictionaryInstanceType": "System.Collections.Generic.Dictionary", - "arrayBaseType": "System.Collections.Generic.List", - "dictionaryBaseType": "System.Collections.Generic.Dictionary", - "classStyle": "Poco", - "generateDefaultValues": true, - "generateDataAnnotations": false, - "excludedTypeNames": [], - "excludedParameterNames": [], - "handleReferences": false, - "generateImmutableArrayProperties": false, - "generateImmutableDictionaryProperties": false, - "jsonSerializerSettingsTransformationMethod": null, - "inlineNamedArrays": false, - "inlineNamedDictionaries": false, - "inlineNamedTuples": true, - "inlineNamedAny": false, - "generateDtoTypes": true, - "generateOptionalPropertiesAsNullable": false, - "generateNullableReferenceTypes": false, - "templateDirectory": null, - "typeNameGeneratorType": null, - "propertyNameGeneratorType": null, - "enumNameGeneratorType": null, - "serviceHost": null, - "serviceSchemes": null, - "output": "$(CSharpOutputPath)/Generated/Client.g.cs", - "newLineBehavior": "Auto" - } - } -} \ No newline at end of file diff --git a/Dfe.PersonsApi.Client/readme.md b/Dfe.PersonsApi.Client/readme.md deleted file mode 100644 index 8f56ade13..000000000 --- a/Dfe.PersonsApi.Client/readme.md +++ /dev/null @@ -1,20 +0,0 @@ -# Persons API Client Library - -The Persons API Client Library provides a convenient and straightforward way to interact with the Persons API, a service that delivers contact and basic personal details of key individuals responsible within various organizations associated with the Department for Education (DfE). - -## Overview - -The Persons API serves as a centralised resource for obtaining up-to-date contact information and personal details of individuals who hold significant roles across different organizations under the DfE's purview. This API enables seamless access to essential information, ensuring that communication and engagement with these key personnel are both efficient and effective. - -## Key Features - -- **Comprehensive Contact Information**: Access detailed contact information for individuals across multiple organizations. -- **Personal Details**: Retrieve basic personal details, including names, roles, and affiliations within the DfE ecosystem. -- **Simple Integration**: Easily integrate with your .NET applications using this client library, which abstracts the complexities of interacting with the underlying API. - -## Installation - -To install the Persons API Client Library, use the following command in your .NET project: - -```sh -dotnet add package Dfe.PersonsApi.Client \ No newline at end of file diff --git a/Dockerfile.PersonsApi b/Dockerfile.PersonsApi deleted file mode 100644 index 400cfc778..000000000 --- a/Dockerfile.PersonsApi +++ /dev/null @@ -1,28 +0,0 @@ -# Set the major version of dotnet -ARG DOTNET_VERSION=8.0 - -# Build the app using the dotnet SDK -FROM "mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-azurelinux3.0" AS build -WORKDIR /build -ARG CI -ENV CI=${CI} - -COPY . . -COPY ./script/personsapi.docker-entrypoint.sh /app/docker-entrypoint.sh - -RUN --mount=type=secret,id=github_token dotnet nuget add source --username USERNAME --password $(cat /run/secrets/github_token) --store-password-in-clear-text --name github "https://nuget.pkg.github.com/DFE-Digital/index.json" - -# Restore, build and publish the dotnet solution -RUN ["dotnet", "restore", "PersonsApi"] -RUN dotnet build PersonsApi --no-restore -c Release -p CI=${CI} -RUN ["dotnet", "publish", "PersonsApi", "--no-build", "-o", "/app"] - -# Build a runtime environment -FROM "mcr.microsoft.com/dotnet/aspnet:${DOTNET_VERSION}-azurelinux3.0" AS final -WORKDIR /app -LABEL org.opencontainers.image.source="https://github.com/DFE-Digital/academies-api" -LABEL org.opencontainers.image.description="Persons API" - -COPY --from=build /app /app -RUN ["chmod", "+x", "./docker-entrypoint.sh"] -USER $APP_UID diff --git a/PersonsApi/Controllers/ConstituenciesController.cs b/PersonsApi/Controllers/ConstituenciesController.cs deleted file mode 100644 index 3f240ddba..000000000 --- a/PersonsApi/Controllers/ConstituenciesController.cs +++ /dev/null @@ -1,50 +0,0 @@ -using Dfe.Academies.Application.Constituencies.Queries.GetMemberOfParliamentByConstituency; -using Dfe.Academies.Application.Common.Models; -using MediatR; -using Microsoft.AspNetCore.Mvc; -using Swashbuckle.AspNetCore.Annotations; -using Microsoft.AspNetCore.Authorization; -using Dfe.Academies.Application.Constituencies.Queries.GetMemberOfParliamentByConstituencies; -using Dfe.Academies.Application.Common.Exceptions; -using System.Net; - -namespace PersonsApi.Controllers -{ - [ApiController] - [Authorize(Policy = "API.Read")] - [ApiVersion("1.0")] - [Route("v{version:apiVersion}/[controller]")] - public class ConstituenciesController(ISender sender) : ControllerBase - { - /// - /// Retrieve Member of Parliament by constituency name - /// - /// The constituency name. - /// The cancellation token. - [HttpGet("{constituencyName}/mp")] - [SwaggerResponse(200, "A Person object representing the Member of Parliament.", typeof(MemberOfParliament))] - [SwaggerResponse(404, "Constituency not found.")] - [SwaggerResponse(400, "Constituency cannot be null or empty.")] - public async Task GetMemberOfParliamentByConstituencyAsync([FromRoute] string constituencyName, CancellationToken cancellationToken) - { - var result = await sender.Send(new GetMemberOfParliamentByConstituencyQuery(constituencyName), cancellationToken); - - return !result.IsSuccess ? NotFound(new CustomProblemDetails(HttpStatusCode.NotFound, result.Error)) : Ok(result.Value); - } - - /// - /// Retrieve a collection of Member of Parliament by a collection of constituency names - /// - /// The request. - /// The cancellation token. - [HttpPost("mps")] - [SwaggerResponse(200, "A collection of MemberOfParliament objects.", typeof(IEnumerable))] - [SwaggerResponse(400, "Constituency names cannot be null or empty.")] - public async Task GetMembersOfParliamentByConstituenciesAsync([FromBody] GetMembersOfParliamentByConstituenciesQuery request, CancellationToken cancellationToken) - { - var result = await sender.Send(request, cancellationToken); - - return Ok(result.Value); - } - } -} diff --git a/PersonsApi/Controllers/EstablishmentsController.cs b/PersonsApi/Controllers/EstablishmentsController.cs deleted file mode 100644 index d1eb06577..000000000 --- a/PersonsApi/Controllers/EstablishmentsController.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Dfe.Academies.Application.Common.Exceptions; -using Dfe.Academies.Application.Common.Models; -using Dfe.Academies.Application.Establishment.Queries.GetAllPersonsAssociatedWithAcademyByUrn; -using Dfe.Academies.Application.Establishment.Queries.GetMemberOfParliamentBySchool; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Swashbuckle.AspNetCore.Annotations; -using System.Net; - -namespace PersonsApi.Controllers -{ - [ApiController] - [Authorize(Policy = "API.Read")] - [ApiVersion("1.0")] - [Route("v{version:apiVersion}/[controller]")] - public class EstablishmentsController(ISender sender) : ControllerBase - { - /// - /// Retrieve All Members Associated With an Academy by Urn - /// - /// The URN. - /// The cancellation token. - /// - [HttpGet("{urn}/getAssociatedPersons")] - [SwaggerResponse(200, "A Collection of Persons Associated With the Academy.", typeof(List))] - [SwaggerResponse(404, "Academy not found.")] - [SwaggerResponse(404, "Constituency not found for the given establishment.")] - public async Task GetAllPersonsAssociatedWithAcademyByUrnAsync([FromRoute] int urn, CancellationToken cancellationToken) - { - var result = await sender.Send(new GetAllPersonsAssociatedWithAcademyByUrnQuery(urn), cancellationToken); - - return !result.IsSuccess ? NotFound(new CustomProblemDetails(HttpStatusCode.NotFound, result.Error)) : Ok(result.Value); - } - - /// - /// Get Member of Parliament by School (Urn) - /// - /// The URN. - /// The cancellation token. - /// - [HttpGet("{urn}/getMpBySchool")] - [SwaggerResponse(200, "Member of Parliament", typeof(MemberOfParliament))] - [SwaggerResponse(404, "School Not found.")] - public async Task GetMemberOfParliamentBySchoolUrnAsync([FromRoute] int urn, CancellationToken cancellationToken) - { - var result = await sender.Send(new GetMemberOfParliamentBySchoolQuery(urn), cancellationToken); - - return !result.IsSuccess ? NotFound(new CustomProblemDetails(HttpStatusCode.NotFound, result.Error)) : Ok(result.Value); - } - } -} diff --git a/PersonsApi/Controllers/TrustsController.cs b/PersonsApi/Controllers/TrustsController.cs deleted file mode 100644 index 90d328ed9..000000000 --- a/PersonsApi/Controllers/TrustsController.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Dfe.Academies.Application.Common.Exceptions; -using Dfe.Academies.Application.Common.Models; -using Dfe.Academies.Application.Trust.Queries.GetAllPersonsAssociatedWithTrustByTrnOrUkprn; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Swashbuckle.AspNetCore.Annotations; -using System.Net; - -namespace PersonsApi.Controllers -{ - [ApiController] - [Authorize(Policy = "API.Read")] - [ApiVersion("1.0")] - [Route("v{version:apiVersion}/[controller]")] - public class TrustsController(ISender sender) : ControllerBase - { - /// - /// Retrieve All Members Associated With a Trust by Either UKPRN or TRN - /// - /// The identifier (UKPRN or TRN). - /// The cancellation token. - [HttpGet("{id}/getAssociatedPersons")] - [SwaggerResponse(200, "A Collection of Persons Associated With the Trust.", typeof(List))] - [SwaggerResponse(404, "Trust not found.")] - public async Task GetAllPersonsAssociatedWithTrustByTrnOrUkPrnAsync([FromRoute] string id, CancellationToken cancellationToken) - { - var result = await sender.Send(new GetAllPersonsAssociatedWithTrustByTrnOrUkprnQuery(id), cancellationToken); - - return !result.IsSuccess ? NotFound(new CustomProblemDetails(HttpStatusCode.NotFound, result.Error)) : Ok(result.Value); - } - } -} diff --git a/PersonsApi/Middleware/ExceptionHandlerMiddleware.cs b/PersonsApi/Middleware/ExceptionHandlerMiddleware.cs deleted file mode 100644 index 8aa284f34..000000000 --- a/PersonsApi/Middleware/ExceptionHandlerMiddleware.cs +++ /dev/null @@ -1,116 +0,0 @@ -using Dfe.Academies.Application.Common.Exceptions; -using Microsoft.AspNetCore.Mvc; -using PersonsApi.ResponseModels; -using System.Net; -using System.Text.Json; -using ValidationException = Dfe.Academies.Application.Common.Exceptions.ValidationException; - -namespace PersonsApi.Middleware; - -public class ExceptionHandlerMiddleware(RequestDelegate next, ILogger logger) -{ - private static readonly string? _responseContentType = "application/json"; - - public async Task InvokeAsync(HttpContext context) - { - try - { - await next(context); - - // Check for 401 or 403 status codes after the request has been processed - if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized) - { - await HandleUnauthorizedResponseAsync(context); - } - else if (context.Response.StatusCode == (int)HttpStatusCode.Forbidden) - { - await HandleForbiddenResponseAsync(context); - } - else if (context.Response.StatusCode == (int)HttpStatusCode.NotFound) - { - await HandleNotFoundResponseAsync(context); - } - } - catch (ValidationException ex) - { - logger.LogError(ex,"Validation error: {Message}", ex.Message); - await HandleValidationException(context, ex); - } - catch (Exception ex) - { - logger.LogError(ex, "An exception occurred: {Message}. Stack Trace: {StackTrace}", ex.Message, ex.StackTrace); - await HandleExceptionAsync(context, ex); - } - } - - // Handle 404 Not Found - private static async Task HandleNotFoundResponseAsync(HttpContext context) - { - if (!context.Response.HasStarted) - { - context.Response.ContentType = _responseContentType; - context.Response.StatusCode = StatusCodes.Status404NotFound; - - var errorResponse = new CustomProblemDetails(HttpStatusCode.NotFound, "The requested resource could not be found."); - - await context.Response.WriteAsJsonAsync(errorResponse); - } - } - - // Handle validation exceptions - private static async Task HandleValidationException(HttpContext httpContext, Exception ex) - { - var exception = (ValidationException)ex; - - httpContext.Response.StatusCode = StatusCodes.Status400BadRequest; - - await httpContext.Response.WriteAsJsonAsync(new ValidationProblemDetails(exception.Errors) - { - Status = StatusCodes.Status400BadRequest, - Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1" - }); - } - - // Handle 401 Unauthorized - private async Task HandleUnauthorizedResponseAsync(HttpContext context) - { - logger.LogWarning("Unauthorized access attempt detected."); - context.Response.ContentType = _responseContentType; - var errorResponse = new ErrorResponse - { - StatusCode = context.Response.StatusCode, - Message = "You are not authorized to access this resource." - }; - await context.Response.WriteAsync(JsonSerializer.Serialize(errorResponse)); - } - - // Handle 403 Forbidden - private async Task HandleForbiddenResponseAsync(HttpContext context) - { - logger.LogWarning("Forbidden access attempt detected."); - context.Response.ContentType = _responseContentType; - var errorResponse = new ErrorResponse - { - StatusCode = context.Response.StatusCode, - Message = "You do not have permission to access this resource." - }; - await context.Response.WriteAsync(JsonSerializer.Serialize(errorResponse)); - } - - // Handle general exceptions (500 Internal Server Error) - private async Task HandleExceptionAsync(HttpContext context, Exception exception) - { - context.Response.ContentType = _responseContentType; - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - var errorResponse = new ErrorResponse - { - StatusCode = context.Response.StatusCode, - Message = "Internal Server Error: " + exception.Message - }; - - logger.LogError("Unhandled Exception: {Message}", exception.Message); - logger.LogError("Stack Trace: {StackTrace}", exception.StackTrace); - - await context.Response.WriteAsync(JsonSerializer.Serialize(errorResponse)); - } -} \ No newline at end of file diff --git a/PersonsApi/Middleware/UrlDecoderMiddleware.cs b/PersonsApi/Middleware/UrlDecoderMiddleware.cs deleted file mode 100644 index 1f2d336f9..000000000 --- a/PersonsApi/Middleware/UrlDecoderMiddleware.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.WebUtilities; -using System.Web; - -namespace PersonsApi.Middleware -{ - public class UrlDecoderMiddleware(RequestDelegate next) - { - public async Task InvokeAsync(HttpContext context) - { - var queryString = context.Request.QueryString.ToString(); - var decodedQueryString = HttpUtility.UrlDecode(queryString); - var newQuery = QueryHelpers.ParseQuery(decodedQueryString); - var items = newQuery - .SelectMany(x => x.Value, (col, value) => new KeyValuePair(col.Key, value)).ToList(); - var qb = new QueryBuilder(items); - context.Request.QueryString = qb.ToQueryString(); - - await next(context); - } - } -} \ No newline at end of file diff --git a/PersonsApi/PersonsApi.csproj b/PersonsApi/PersonsApi.csproj deleted file mode 100644 index a2d366656..000000000 --- a/PersonsApi/PersonsApi.csproj +++ /dev/null @@ -1,66 +0,0 @@ - - - - net8.0 - enable - enable - true - $(NoWarn);1591 - 8c1ad605-0dd4-443a-ad18-dd22bbb2a9d9 - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - PreserveNewest - true - PreserveNewest - - - - - - - - - - - - - - diff --git a/PersonsApi/Program.cs b/PersonsApi/Program.cs deleted file mode 100644 index 4a1eeccb9..000000000 --- a/PersonsApi/Program.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.AspNetCore.Mvc.ApiExplorer; -using PersonsApi; -using Serilog; - -var builder = WebApplication.CreateBuilder(args); - -var startup = new Startup(builder.Configuration); - -startup.ConfigureServices(builder.Services); - -builder.Host.UseSerilog((context, services, loggerConfiguration) => -{ - loggerConfiguration - .ReadFrom.Configuration(context.Configuration) - .WriteTo.ApplicationInsights(services.GetRequiredService(), TelemetryConverter.Traces) - .Enrich.FromLogContext() - .WriteTo.Console(); -}); - -builder.Services.AddPersonsApiApplicationDependencyGroup(builder.Configuration); - -var app = builder.Build(); - -var provider = app.Services.GetRequiredService(); - -startup.Configure(app, app.Environment, provider); - -ILogger logger = app.Services.GetRequiredService>(); - -logger.LogInformation("Logger is working..."); - -app.MapHealthChecks("/HealthCheck").AllowAnonymous(); - -app.Run(); diff --git a/PersonsApi/Properties/launchSettings.json b/PersonsApi/Properties/launchSettings.json deleted file mode 100644 index fa4b31c2c..000000000 --- a/PersonsApi/Properties/launchSettings.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:37794", - "sslPort": 44333 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "PersonsApi": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "swagger", - "applicationUrl": "https://localhost:7089;http://localhost:5277", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/PersonsApi/ResponseModels/ErrorResponse.cs b/PersonsApi/ResponseModels/ErrorResponse.cs deleted file mode 100644 index 18e66cc7c..000000000 --- a/PersonsApi/ResponseModels/ErrorResponse.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Text.Json; -namespace PersonsApi.ResponseModels -{ - public class ErrorResponse - { - public int StatusCode { get; set; } - public string Message { get; set; } - public override string ToString() - { - return JsonSerializer.Serialize(this); - } - } -} diff --git a/PersonsApi/Startup.cs b/PersonsApi/Startup.cs deleted file mode 100644 index a57fd492f..000000000 --- a/PersonsApi/Startup.cs +++ /dev/null @@ -1,183 +0,0 @@ -using Dfe.Academies.Application.MappingProfiles; -using DfE.CoreLibs.Http.Interfaces; -using DfE.CoreLibs.Http.Middlewares.CorrelationId; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.AspNetCore.Mvc.ApiExplorer; -using Microsoft.FeatureManagement; -using NetEscapades.AspNetCore.SecurityHeaders; -using PersonsApi.Middleware; -using PersonsApi.Swagger; -using Swashbuckle.AspNetCore.SwaggerUI; -using System.Reflection; -using System.Text; -using System.Text.Json.Serialization; - -namespace PersonsApi -{ - public class Startup(IConfiguration configuration) - { - public IConfiguration Configuration { get; } = configuration; - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddControllers().AddJsonOptions(c => {c.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());}); - services.AddApiVersioning(); - services.AddFeatureManagement(); - - services.AddPersonsApiInfrastructureDependencyGroup(Configuration); - - services.AddScoped(); - - services.AddApiVersioning(config => - { - config.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); - config.AssumeDefaultVersionWhenUnspecified = true; - config.ReportApiVersions = true; - }); - services.AddVersionedApiExplorer(setup => - { - setup.GroupNameFormat = "'v'VVV"; - setup.SubstituteApiVersionInUrl = true; - }); - services.AddSwaggerGen(c => - { - string descriptions = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - string descriptionsPath = Path.Combine(AppContext.BaseDirectory, descriptions); - if (File.Exists(descriptionsPath)) c.IncludeXmlComments(descriptionsPath); - - var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - Path.Combine(AppContext.BaseDirectory, xmlFile); - c.EnableAnnotations(); - }); - services.ConfigureOptions(); - services.AddHttpContextAccessor(); - - services - .AddOptions() - .Configure((swaggerUiOptions, httpContextAccessor) => - { - // 2. Take a reference of the original Stream factory which reads from Swashbuckle's embedded resources - var originalIndexStreamFactory = swaggerUiOptions.IndexStream; - // 3. Override the Stream factory - swaggerUiOptions.IndexStream = () => - { - // 4. Read the original index.html file - using var originalStream = originalIndexStreamFactory(); - using var originalStreamReader = new StreamReader(originalStream); - var originalIndexHtmlContents = originalStreamReader.ReadToEnd(); - // 5. Get the request-specific nonce generated by NetEscapades.AspNetCore.SecurityHeaders - var requestSpecificNonce = httpContextAccessor.HttpContext.GetNonce(); - // 6. Replace inline `