115 lines
3.6 KiB
C#
115 lines
3.6 KiB
C#
using AutobusApi.Application.Common.Exceptions;
|
|
using AutobusApi.Application.Common.Interfaces;
|
|
using AutobusApi.Domain.Entities;
|
|
using AutobusApi.Domain.Enums;
|
|
using MediatR;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace AutobusApi.Application.Employees.Commands.UpdateEmployee;
|
|
|
|
public class UpdateEmployeeCommandHandler : IRequestHandler<UpdateEmployeeCommand>
|
|
{
|
|
private readonly IApplicationDbContext _dbContext;
|
|
|
|
public UpdateEmployeeCommandHandler(IApplicationDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public async Task Handle(
|
|
UpdateEmployeeCommand request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var employee = await _dbContext.Employees
|
|
.Include(e => e.Documents)
|
|
.SingleAsync(e => e.Id == request.Id, cancellationToken);
|
|
|
|
if (employee == null)
|
|
{
|
|
throw new NotFoundException();
|
|
}
|
|
|
|
employee.FirstName = request.FirstName;
|
|
employee.LastName = request.LastName;
|
|
employee.Patronymic = request.Patronymic;
|
|
employee.Sex = Enum.Parse<Sex>(request.Sex);
|
|
employee.BirthDate = request.BirthDate;
|
|
|
|
var compaper = new EmployeeDocumentEqualityComparer();
|
|
|
|
var routeAddressesToBeRemoved = employee.Documents
|
|
.ExceptBy(request.Documents.Select(
|
|
d => new EmployeeDocument
|
|
{
|
|
Id = d.Id ?? 0,
|
|
Information = d.Information,
|
|
Type = Enum.Parse<EmployeeDocumentType>(d.Type)
|
|
}),
|
|
d => new EmployeeDocument
|
|
{
|
|
Id = d.Id,
|
|
Information = d.Information,
|
|
Type = d.Type
|
|
},
|
|
compaper
|
|
).ToList();
|
|
|
|
var remainingEmployeeDocumentes = employee.Documents
|
|
.ExceptBy(routeAddressesToBeRemoved.Select(
|
|
dtbr => new EmployeeDocument
|
|
{
|
|
Id = dtbr.Id,
|
|
Information = dtbr.Information,
|
|
Type = dtbr.Type
|
|
}),
|
|
d => new EmployeeDocument
|
|
{
|
|
Id = d.Id,
|
|
Information = d.Information,
|
|
Type = d.Type
|
|
},
|
|
compaper
|
|
).ToList();
|
|
|
|
var newEmployeeDocumentes = remainingEmployeeDocumentes
|
|
.UnionBy(request.Documents.Select(
|
|
d => new EmployeeDocument
|
|
{
|
|
Id = d.Id ?? 0,
|
|
Information = d.Information,
|
|
Type = Enum.Parse<EmployeeDocumentType>(d.Type)
|
|
}),
|
|
rd => new EmployeeDocument
|
|
{
|
|
Id = rd.Id,
|
|
Information = rd.Information,
|
|
Type = rd.Type
|
|
},
|
|
compaper
|
|
).ToList();
|
|
|
|
employee.Documents = newEmployeeDocumentes.ToList();
|
|
|
|
await _dbContext.SaveChangesAsync(cancellationToken);
|
|
}
|
|
|
|
private class EmployeeDocumentEqualityComparer : IEqualityComparer<EmployeeDocument>
|
|
{
|
|
public bool Equals(EmployeeDocument? x, EmployeeDocument? y)
|
|
{
|
|
return
|
|
x?.Id == y?.Id &&
|
|
x?.Type == y?.Type &&
|
|
x?.Information == y?.Information;
|
|
}
|
|
|
|
public int GetHashCode(EmployeeDocument obj)
|
|
{
|
|
return
|
|
obj.Id.GetHashCode() +
|
|
obj.Information.GetHashCode() +
|
|
obj.Type.GetHashCode();
|
|
}
|
|
}
|
|
}
|