forked from Alexey/DAS_2024_1
77 lines
2.6 KiB
C#
77 lines
2.6 KiB
C#
using AutoMapper;
|
||
using DSaC_second.Database;
|
||
using DSaC_second.Database.Models;
|
||
using DSaC_second.Logic.Handlers.Queries;
|
||
using DSaC_second.Models.DTOs;
|
||
using DSaC_second.Models.Internal;
|
||
using DSaC_second.Models.Internal.Queries;
|
||
using DSaC_second.Models.Internal.Сommands;
|
||
using MediatR;
|
||
|
||
namespace DSaC_second.Logic.Handlers.Commands
|
||
{
|
||
public class CreateContractCommandHandler : IRequestHandler<CreateContractCommand, ResponseModel<ContractFullDto>>
|
||
{
|
||
private readonly ILogger _logger;
|
||
private readonly DsacContext _context;
|
||
private readonly IMapper _mapper;
|
||
private readonly IMediator _mediator;
|
||
|
||
public CreateContractCommandHandler(ILogger<CreateContractCommandHandler> logger, DsacContext context, IMapper mapper, IMediator mediator)
|
||
{
|
||
_logger = logger;
|
||
_context = context;
|
||
_mapper = mapper;
|
||
_mediator = mediator;
|
||
}
|
||
|
||
public async Task<ResponseModel<ContractFullDto>> Handle(CreateContractCommand request, CancellationToken cancellationToken)
|
||
{
|
||
try
|
||
{
|
||
var counterparty = await _mediator.Send(new GetConunterpartyQuery()
|
||
{
|
||
Id = request.Model.CounterpartyId,
|
||
}, cancellationToken: cancellationToken);
|
||
|
||
if (counterparty.IsError)
|
||
return new()
|
||
{
|
||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||
ErrorText = counterparty.ErrorText,
|
||
};
|
||
if (counterparty.Value == null)
|
||
return new()
|
||
{
|
||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||
ErrorText = "Cpty with this id not found",
|
||
};
|
||
|
||
var model = _mapper.Map<Contract>(request.Model);
|
||
|
||
var outModel = await _context.Contracts.AddAsync(model, cancellationToken: cancellationToken);
|
||
|
||
await _context.SaveChangesAsync(cancellationToken);
|
||
|
||
var res = _mapper.Map<ContractFullDto>(model);
|
||
res.Counterparty = counterparty.Value!;
|
||
|
||
return new()
|
||
{
|
||
Value = res,
|
||
};
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "Error on creating record");
|
||
|
||
return new()
|
||
{
|
||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||
ErrorText = "Cannot create contract",
|
||
};
|
||
}
|
||
}
|
||
}
|
||
}
|