Api/NetinaShop.Core/EntityServices/OrderBagHandlers/AddToOrderBagCommandHandler.cs

43 lines
1.8 KiB
C#

namespace NetinaShop.Core.EntityServices.OrderBagHandlers;
public class AddToOrderBagCommandHandler : IRequestHandler<AddToOrderBagCommand,bool>
{
private readonly IMediator _mediator;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public AddToOrderBagCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_mediator = mediator;
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(AddToOrderBagCommand request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
throw new AppException("User id notfound", ApiResultStatusCode.BadRequest);
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
throw new AppException("User id wrong", ApiResultStatusCode.BadRequest);
var product = await _repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);
if (product == null)
throw new AppException("Product not found ",ApiResultStatusCode.NotFound);
if (!product.IsEnable)
throw new AppException("Product is not enable", ApiResultStatusCode.BadRequest);
var orderBag = await _mediator.Send(new GetUserOrderBagQuery(), cancellationToken);
orderBag.AddToOrderBag(product, request.Count);
_repositoryWrapper.SetRepository<Order>().Update(orderBag);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);
return true;
}
}