Files
DAS_2024_1/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/CreateContractCommandHandler.cs

77 lines
2.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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",
};
}
}
}
}