namespace NetinaShop.Core.EntityServices.OrderHandlers; public class CalculateOrderCommandHandler : IRequestHandler { private readonly IRepositoryWrapper _repositoryWrapper; private readonly IMediator _mediator; private readonly ShopSettings _shopSettings; public CalculateOrderCommandHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator,IOptionsSnapshot snapshot) { _repositoryWrapper = repositoryWrapper; _mediator = mediator; _shopSettings = snapshot.Value; } public async Task Handle(CalculateOrderCommand request, CancellationToken cancellationToken) { var order = await _mediator.Send(new GetOrderQuery(request.OrderId), cancellationToken); if (order.OrderStatus != OrderStatus.OrderBag) throw new AppException("Order is not in bag status and cant be calculate", ApiResultStatusCode.BadRequest); var totalProductPrice = order.OrderProducts.Sum(op => op.ProductCost); var totalPackingPrice = order.OrderProducts.Sum(op => op.PackingCost); var servicePrice = _shopSettings.ServiceIsPercent ? (totalProductPrice / 100) * _shopSettings.ServiceFee : _shopSettings.ServiceFee; var deliveryPrice = order.OrderDeliveries.Sum(op => op.DeliveryCost); double discountPrice = 0; if (!order.DiscountCode.IsNullOrEmpty()) { discountPrice = await _mediator.Send(new CalculateDiscountCommand(order.DiscountCode, order),cancellationToken); } var taxesPrice = (((totalProductPrice - discountPrice) + totalPackingPrice + servicePrice) / 100) * _shopSettings.TaxesFee; order.SetTotalPrice(totalProductPrice, totalPackingPrice, servicePrice, deliveryPrice, discountPrice, taxesPrice); _repositoryWrapper.SetRepository().Update(order); await _repositoryWrapper.SaveChangesAsync(cancellationToken); return order; } }