updating countries

This commit is contained in:
2024-08-20 21:34:56 +03:00
parent 19e792e670
commit a0d002b465
14 changed files with 119 additions and 10 deletions

View File

@@ -1,4 +1,5 @@
using ApplicationLayer.InfrastructureServicesInterfaces;
using ApplicationLayer.Services.Applicants.NeededServices;
using ApplicationLayer.Services.Locations.NeededServices;
using ApplicationLayer.Services.Locations.RequestHandlers.Exceptions;
using ApplicationLayer.Services.Locations.Requests;
@@ -7,7 +8,11 @@ using Domains.LocationDomain;
namespace ApplicationLayer.Services.Locations.RequestHandlers
{
/// <inheritdoc cref="ILocationRequestsHandler"/>
public class LocationRequestsHandler(ICountriesRepository countries, IUnitOfWork unitOfWork) : ILocationRequestsHandler
public class LocationRequestsHandler(
ICountriesRepository countries,
ICitiesRepository cities,
IApplicantsRepository applicants,
IUnitOfWork unitOfWork) : ILocationRequestsHandler
{
async Task<List<Country>> ILocationRequestsHandler.HandleGetRequestAsync(CancellationToken cancellationToken)
{
@@ -16,7 +21,7 @@ namespace ApplicationLayer.Services.Locations.RequestHandlers
async Task ILocationRequestsHandler.AddCountryAsync(AddCountryRequest request, CancellationToken cancellationToken)
{
if (await countries.FindByName(request.CountryName, cancellationToken) is not null)
if (await countries.FindByNameAsync(request.CountryName, cancellationToken) is not null)
{
throw new CountryAlreadyExists(request.CountryName);
}
@@ -38,5 +43,49 @@ namespace ApplicationLayer.Services.Locations.RequestHandlers
await unitOfWork.SaveAsync(cancellationToken);
}
async Task ILocationRequestsHandler.UpdateCountryAsync(UpdateCountryRequest request, CancellationToken cancellationToken)
{
if (await countries.FindByNameAsync(request.CountryName, cancellationToken) is not null)
{
throw new CountryAlreadyExists(request.CountryName);
}
var country = await countries.FindByIdAsync(request.Id, cancellationToken);
if (country is null)
{
throw new CountryNotFoundException(request.CountryName);
}
var existingCities = country.Cities;
var citiesToAdd = request.Cities.Except(existingCities.Select(c => c.Name)).ToList();
var citiesToRemove = existingCities.Where(c => !request.Cities.Contains(c.Name));
var applicantsList = await applicants.GetAllAsync(cancellationToken);
//todo mapper
foreach (var city in citiesToRemove)
{
if (applicantsList.All(a => a.CityOfBirth.Id != city.Id && a.PlaceOfWork.Address.City.Id != city.Id))
{
cities.Remove(city);
}
else
{
throw new CityCanNotBeDeletedException(city.Name);
}
}
foreach (var city in citiesToAdd)
{
await cities.AddAsync(new City { Name = city, Country = country }, cancellationToken);
}
country.Name = request.CountryName;
country.IsSchengen = request.IsSchengen;
await countries.UpdateAsync(country, cancellationToken);
await unitOfWork.SaveAsync(cancellationToken);
}
}
}