public IEnumerable <CartItemDetailsServiceModel> CartItemsDetails(CartServiceModel cart) { var items = cart? .AllItems() .ToDictionary(i => i.Id, i => i.Quantity); if (items == null) { return(null); } return(this.db .Shoes .Where(s => items.ContainsKey(s.Id)) .Select(s => new CartItemDetailsServiceModel { Id = s.Id, Name = s.Name, Price = s.Price, Quantity = items[s.Id] }) .ToList()); }
protected async Task <bool> AddOrderProduct(CartServiceModel cart, List <ProductDTO> products, CartDTO cartDTO) { List <int> productIds = cart.CartProducts.Select(x => x.ProductId).ToList(); for (int i = 0; i < productIds.Count; i++) { var productId = productIds[i]; var product = products.FirstOrDefault(x => x.Id == productId && x.IsAvailable); var cartQuantity = cart.CartProducts.Single(x => x.ProductId == productId).Quantity; if (!IsValidProduct(product, cartQuantity, productId, i)) { continue; } product.AvailableCount -= cartQuantity; if (product.AvailableCount == 0) { product.IsAvailable = false; } var cartProductInCart = DoesCartHaveProduct(cartDTO, productId); if (cartProductInCart != null) { cartProductInCart.Quantity += cartQuantity; await _unitOfWork.CartProductRepository.UpdateAsync(cartProductInCart); } else { await _unitOfWork.CartProductRepository.InsertAsync(new CartProductDTO { CartId = cartDTO.Id, ProductId = productId, Quantity = cartQuantity }); } } return(_validationDictionary.IsValid); }
public async Task <bool> InsertOrderAsync(CartServiceModel cart) { try { await _unitOfWork.BeginTransactionAsync(); var products = await _unitOfWork.ProductRepository.GetAllAsyncWithTracking(); var users = await _unitOfWork.UserRepository.GetAllAsyncWithNoTracking(); var user = users.FirstOrDefault(x => x.Id == cart.UserId); if (user == null) { _validationDictionary.AddError("UserId", "შეყვანილი იუზერი არ არსებობს!"); return(false); } var doesUserHaveCart = DoesUserHaveActiveCart(user.Id); CartDTO newCart; if (doesUserHaveCart == null) { newCart = new CartDTO { UserId = cart.UserId, }; await _unitOfWork.CartRepository.InsertAsync(newCart); } else { newCart = doesUserHaveCart; } if (!await AddOrderProduct(cart, products.ToList(), newCart)) { await _unitOfWork.RollbackAsync(); return(false); } await _unitOfWork.SaveChangesAsync(); if (doesUserHaveCart == null) { var jobId = BackgroundJob.Schedule(() => DeleteCart(newCart.Id), TimeSpan.FromMinutes(_config.GetValue <int>("CartOptions:CartExpireTimeInMinute"))); newCart.JobId = jobId; await _unitOfWork.SaveChangesAsync(); } await _unitOfWork.CommitAsync(); return(true); } catch (Exception) { await _unitOfWork.RollbackAsync(); throw; } }