namespace Netina.Core.EntityServices.OrderBagHandlers; public class SubmitDiscountActionCommandHandler : IRequestHandler { private readonly IRepositoryWrapper _repositoryWrapper; private readonly IMediator _mediator; public SubmitDiscountActionCommandHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator) { _repositoryWrapper = repositoryWrapper; _mediator = mediator; } public async Task Handle(SubmitDiscountActionCommand request, CancellationToken cancellationToken) { var order = await _repositoryWrapper.SetRepository() .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() .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().Update(order); await _repositoryWrapper.SaveChangesAsync(cancellationToken); var calculateOrder = await _mediator.Send(new CalculateOrderCommand(order.Id), cancellationToken); return calculateOrder.AdaptToSDto(); } }