Api/Netina.Core/EntityServices/OrderBagHandlers/SubmitDiscountActionCommand...

45 lines
2.1 KiB
C#

namespace Netina.Core.EntityServices.OrderBagHandlers;
public class SubmitDiscountActionCommandHandler : IRequestHandler<SubmitDiscountActionCommand, OrderSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
public SubmitDiscountActionCommandHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator)
{
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
}
public async Task<OrderSDto> Handle(SubmitDiscountActionCommand request, CancellationToken cancellationToken)
{
var order = await _repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
if (order == null)
throw new AppException("Order not found", ApiResultStatusCode.NotFound);
if (request.DiscountCode != null)
{
var discount = await _repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);
if (discount == null || discount.IsExpired())
throw new AppException("تخفیف منقضی شده است یا وجود ندارد", ApiResultStatusCode.NotFound);
var isFirstUserOfDiscount = await _mediator.Send(new CheckUserDiscountFirstUseCommand(request.DiscountCode), cancellationToken);
if (!isFirstUserOfDiscount)
throw new BaseApiException(ApiResultStatusCode.BadRequest, "شما یک بار از این کد تخفیف استفاده نموده اید و قابلیت استفاده مجدد ندارید");
order.SetDiscount(request.DiscountCode);
}
else
order.RemoveDiscount();
_repositoryWrapper.SetRepository<Order>().Update(order);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
var calculateOrder = await _mediator.Send(new CalculateOrderCommand(order.Id), cancellationToken);
return calculateOrder.AdaptToSDto();
}
}