示例#1
0
 public void InitializeCart(string userId)
 {
     _cartRepository.Add(new Cart()
     {
         UserId = userId
     });
 }
示例#2
0
        public async Task <ActionResult <CartModel> > PostCart(CartModel cart)
        {
            _cartRepository.Add(cart);
            await _cartRepository.SaveChangesAsync();

            return(CreatedAtAction("GetCart", new { id = cart.Id }, cart));
        }
示例#3
0
        public IActionResult DetailsPost(int id, DetailsVM detailsVM)
        {
            List <ShoppingCart> shoppingCartList = new List <ShoppingCart>();

            if (HttpContext.Session.Get <IEnumerable <ShoppingCart> >(WC.SessionCart) != null &&
                HttpContext.Session.Get <IEnumerable <ShoppingCart> >(WC.SessionCart).Count() > 0)
            {
                //if there are products in the session and user is not logged in
                shoppingCartList = HttpContext.Session.Get <List <ShoppingCart> >(WC.SessionCart);
            }
            shoppingCartList.Add(new ShoppingCart {
                ProductId = id, Qty = detailsVM.Product.TempQty
            });
            HttpContext.Session.Set(WC.SessionCart, shoppingCartList);

            if (User.IsInRole(WC.CustomerRole))
            {
                var claimsIdentity = (ClaimsIdentity)User.Identity;
                var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
                _cartRepo.Add(new Cart {
                    ProductId = id, Qty = detailsVM.Product.TempQty, ApplicationUserId = claim.Value
                });
                _cartRepo.Save();
            }
            TempData[WC.Success] = "Item add to cart successfully";
            return(RedirectToAction(nameof(Index)));
        }
示例#4
0
        public override void Add(User entity)
        {
            using (var dbContextTransaction = dataContext.Database.BeginTransaction())
            {
                try
                {
                    if (entity.Address != null)
                    {
                        addressRepository.Add(entity.Address);
                        addressRepository.Save();
                    }
                    base.Add(entity);
                    base.Save();

                    Cart cart = new Cart();
                    cart.CustomerID = entity.UserID;
                    cartRepository.Add(cart);
                    cartRepository.Save();

                    WishList wishList = new WishList();
                    wishList.CustomerID = entity.UserID;
                    wishListRepository.Add(wishList);
                    wishListRepository.Save();

                    dbContextTransaction.Commit();
                }
                catch (Exception e)
                {
                    dbContextTransaction.Rollback();
                }
            }
        }
示例#5
0
        /// <summary>
        /// Consumes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public async Task Consume(ConsumeContext <AddtoCartRequest> context)
        {
            try
            {
                var productData = productService.FilterWithQuery(Query.Matches("Id", new MongoDB.Bson.BsonRegularExpression("/^" + context.Message.ProductId.ToString() + "$/i"))).FirstOrDefault();
                if (productData != null)
                {
                    var isexistQuery = Query.And(Query.Matches("ProductId", new MongoDB.Bson.BsonRegularExpression("/^" + context.Message.ProductId.ToString() + "$/i")), Query.Matches("CustomerId", new MongoDB.Bson.BsonRegularExpression("/^" + context.Message.CustomerId.ToString() + "$/i")));
                    var itemDetails  = cartService.FilterWithQuery(isexistQuery).Count();
                    if (itemDetails == 0)
                    {
                        var cartId = Guid.NewGuid();
                        cartService.Insert(new Cart()
                        {
                            Category    = productData.Category,
                            CustomerId  = context.Message.CustomerId,
                            Description = productData.Description,
                            Id          = cartId,
                            Name        = productData.Name,
                            Price       = productData.Price,
                            ProductId   = productData.Id,
                            Qty         = 1
                        });
                        eventStoreRepository.Add(new ES.Domain.Cart(cartId, productData.Name, productData.Category, productData.Description, Convert.ToDecimal(productData.Price), Convert.ToInt32(productData.Qty), productData.Id, context.Message.CustomerId, "Added"));
                    }
                    else
                    {
                        var cartItem = cartService.FilterWithQuery(isexistQuery).FirstOrDefault();
                        if (cartItem != null)
                        {
                            cartItem.Qty += 1;
                            cartService.Update(isexistQuery, cartItem);
                            eventStoreRepository.Save(new ES.Domain.Cart(cartItem.Id, productData.Name, productData.Category, productData.Description, Convert.ToDecimal(productData.Price), Convert.ToInt32(productData.Qty), productData.Id, context.Message.CustomerId, "Added"));
                        }
                    }

                    await context.RespondAsync(new AddtoCartResponse
                    {
                        Success = true,
                        Message = "ok"
                    });
                }

                await context.RespondAsync(new AddtoCartResponse
                {
                    Success = false,
                    Message = "Product Not Found",
                });
            }
            catch (Exception exc)
            {
                await context.RespondAsync(new AddtoCartResponse
                {
                    Success = false,
                    Message = "Failed" + Environment.NewLine + exc.Message
                });

                throw;
            }
        }
示例#6
0
        public void AddToCart(Album album)
        {
            // Get the matching cart and album instances
            var cartItem = _carts.Get().SingleOrDefault(
                c => c.CartId == ShoppingCartId &&
                c.AlbumId == album.AlbumId);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new Cart
                {
                    AlbumId     = album.AlbumId,
                    CartId      = ShoppingCartId,
                    Count       = 1,
                    DateCreated = DateTime.Now
                };
                _carts.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart,
                // then add one to the quantity
                cartItem.Count++;
            }
            // Save changes
            _unitOfWork.SaveChanges();
        }
示例#7
0
        public IActionResult Index()
        {
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            List <ShoppingCart> shoppingCartList = new List <ShoppingCart>();

            if (HttpContext.Session.Get <IEnumerable <ShoppingCart> >(WC.SessionCart) != null &&
                HttpContext.Session.Get <IEnumerable <ShoppingCart> >(WC.SessionCart).Count() > 0)
            {
                //session exsits
                shoppingCartList = HttpContext.Session.Get <List <ShoppingCart> >(WC.SessionCart);
            }

            IEnumerable <Cart> carts = _cartRepo.GetAll(u => u.ApplicationUserId == claim.Value);

            foreach (var cartDB in carts)
            {
                if (!shoppingCartList.Exists(x => x.ProductId == cartDB.ProductId))
                {
                    shoppingCartList.Add(new ShoppingCart {
                        ProductId = cartDB.ProductId, Qty = cartDB.Qty
                    });
                }
            }
            HttpContext.Session.Set(WC.SessionCart, shoppingCartList);


            List <int> prodInCart = shoppingCartList.Select(i => i.ProductId).ToList();
            // List<int> prodInCartSave = shoppingCartList.Select(i => i.ProductId).ToList();

            IEnumerable <Product> prodListTemp = _prodRepo.GetAll(u => prodInCart.Contains(u.Id));
            IList <Product>       prodList     = new List <Product>();

            foreach (var cartObj in shoppingCartList)
            {
                //sending to db
                Cart cart = new Cart
                {
                    ApplicationUserId = claim.Value,
                    Qty       = cartObj.Qty,
                    ProductId = cartObj.ProductId
                };
                var obj = _cartRepo.FirstOrDefault(u => u.ApplicationUserId == claim.Value && u.ProductId == cart.ProductId);
                if (obj == null)
                {
                    _cartRepo.Add(cart);
                }

                //sending to cartView
                Product prodTemp = prodListTemp.FirstOrDefault(u => u.Id == cartObj.ProductId);
                prodTemp.TempQty = cartObj.Qty;
                prodList.Add(prodTemp);
            }
            _cartRepo.Save();



            return(View(prodList));
        }
示例#8
0
        public void AddToCart(ICoffee orderedCofee)
        {
            var isAvailable = cartRepository.IsCartItemAvailable(shoppingCartId, orderedCofee.Id);

            ICart cartItem;

            if (!isAvailable)
            {
                cartItem                   = cartFactory.CreateCart();
                cartItem.CoffeeId          = orderedCofee.Id;
                cartItem.CoffeeDescription = orderedCofee.FullDescription;
                cartItem.CoffeeCost        = orderedCofee.Cost();
                cartItem.ShoppingCartId    = this.shoppingCartId;
                cartItem.Count             = 1;

                cartRepository.Add(cartItem);
            }
            else
            {
                // Pls refactor
                cartItem = cartRepository.GetCartItemByCoffeeId(shoppingCartId, orderedCofee.Id);

                cartItem.Count++;

                cartRepository.Update(cartItem);
            }
        }
        /// <summary>
        /// Adds the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        public void Add(AddProudctToCartViewModel model)
        {
            var customer = _customerRepository.FindById(model.CustomerId);

            if (customer == null)
            {
                _eventDispatcher.RaiseEvent(new DomainNotification(MessageType, string.Format("Customer was not found with this Id: {0}", model.CustomerId)));
                return;
            }

            var product = _productRepository.FindById(model.ProductId);

            if (product == null)
            {
                _eventDispatcher.RaiseEvent(new DomainNotification(MessageType, string.Format("Product was not found with this Id: {0}", model.ProductId)));
                return;
            }

            var cart = _cartRepository.FindSingleBySpec(new CustomerCartSpec(model.CustomerId));

            if (cart == null)
            {
                cart = Cart.Create(customer);
                _cartRepository.Add(cart);
            }

            cart.Add(CartProduct.Create(customer, cart, product, model.Quantity));
        }
示例#10
0
        public ActionResult GetCart()
        {
            User user;
            Cart cart;

            if (Session["user"] != null)
            {
                user = (User)Session["user"];
                var curUser = userRepository.GetById(user.UserID);
                if (curUser.Carts.Count > 0)
                {
                    cart = curUser.Carts.ToList()[0];
                }
                else
                {
                    cart = new Cart {
                        CustomerID = curUser.UserID
                    };
                    cartRepository.Add(cart);
                    cartRepository.Save();
                }
                var cartDto = Mapper.Map <CartDTO>(cart);
                cartDto.NumberOfItems = cartDto.CartDetails.Count;
                if (cartDto.CartDetails.Count > 0)
                {
                    decimal totalPrice = 0;
                    decimal totalTax   = 0;

                    foreach (var cartDetail in cartDto.CartDetails)
                    {
                        totalPrice += (cartDetail.UnitPrice * cartDetail.Quantity);
                        ProductDetail p = productDetailRepository.GetById(cartDetail.ProductDetailID);
                        if (p.Product.TaxRate != null)
                        {
                            totalTax += (cartDetail.UnitPrice * (decimal)p.Product.TaxRate / 100 * cartDetail.Quantity);
                        }
                    }
                    cartDto.TotalPrice         = totalPrice;
                    cartDto.TotalTax           = totalTax;
                    cartDto.TotalPriceAfterTax = totalPrice + totalTax;
                }
                Session["cartID"] = cartDto.CartID;
                return(Json(cartDto, JsonRequestBehavior.AllowGet));
            }

            return(Json(false, JsonRequestBehavior.AllowGet));
        }
示例#11
0
        protected override Task Handle(CreateCartCommand request, CancellationToken cancellationToken)
        {
            var cart = new Cart(request.ID);

            repository.Add(cart);

            return(Task.CompletedTask);
        }
        public int CreateCart()
        {
            var cart = new Cart();

            _cartRepository.Add(cart);
            _unitOfWork.Commit();
            return(cart.CartId);
        }
示例#13
0
 public CartItem Add(CartItem cartItem)
 {
     return(ExecuteFaultHandledOperation(() => {
         ValidationAuthorization(((IAccountOwnedEntity)cartItem).OwnerAccountId); // GetOwnerAccountId(cartItem)
         ICartRepository cartRepository =
             _dataRepositoryFactory.GetDataRepository <ICartRepository>();
         CartItem newCartItem = cartRepository.Add(cartItem);
         return newCartItem;
     }));
 }
示例#14
0
        private void SaveItem(CartItem item, int customerId)
        {
            OrderedItem orderedItem = new OrderedItem()
            {
                CustomerId = customerId,
                ProductId  = item.Product.ProductId,
                Qty        = item.Qty
            };

            cartRepository.Add(orderedItem);
        }
 public IActionResult Post(Cart cart)
 {
     _log4net.Info(" Adding item to cart");
     using (var scope = new TransactionScope())
     {
         _cartRepository.Add(cart);
         scope.Complete();
         _log4net.Info("Item Added");
         return(Ok());
     }
 }
示例#16
0
        private Customer CreateNewCustomer(string name)
        {
            using (_unitOfWork.BeginTransaction())
            {
                var customer = new Customer(Guid.NewGuid(), name);
                _customerRepository.Add(customer);
                _currentUser.CustomerId = customer.Id;
                var cart = _cartRepository.Add(new Cart(Guid.NewGuid(), customer.Id));
                _currentCart.Id = cart.Id;

                return(customer);
            }
        }
示例#17
0
        public async Task <Cart> GetByUser(string userId)
        {
            var cart = _cartRepository.GetByUserId(userId);

            if (cart != null)
            {
                return(cart);
            }

            var newCart = await _cartRepository.Add(new Cart { UserId = userId, Active = true });

            return(newCart);
        }
示例#18
0
        public async Task <ActionResult> CreateCart([FromBody] CartDTO cart)
        {
            var cartRepo = _mapper.Map <ShoppingCart>(cart);

            _repo.Add(cartRepo);

            if (await _repo.SaveAll())
            {
                return(Ok(cartRepo));
            }

            return(BadRequest("Adding cart error"));
        }
示例#19
0
 public bool Add(Cart cart)
 {
     try
     {
         _cartRepository.Add(cart);
         _unitOfWork.Commit();
         return(true);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
        public void AddToCart(long cartId, long productId)
        {
            var cart = cartRepository.GetById(cartId);

            if (cart == null)
            {
                cart = new Cart(new List <CartItem>());
                cartRepository.Add(cart);
            }
            var product = productRepository.GetById(productId);

            cart.AddCartItem(product);
            cartRepository.Update(cart);
            cartRepository.Commit();
        }
示例#21
0
        public async Task <string> CreateCartItem(CartItemDto cart)
        {
            var c = new CartItem
            {
                EquipmentId = cart.EquipmentId,
                UserId      = cart.UserId,
                DateCreated = DateTime.Now,
                NoOfDays    = cart.NoOfDays
            };

            _cartRepository.Add(c);
            await _uow.CompleteAsync();

            return(c.CartItemId.ToString());
        }
示例#22
0
        public void Add_GivenValidData_ReturnsTrue()
        {
            //Arrange
            const string guid      = "967d56bd-3899-4097-8548-e42a6968dea0";
            const int    productId = 1;

            A.CallTo(() => _productsRepository.Get(productId)).Returns(new ProductModel());
            A.CallTo(() => _cartRepository.Get(guid, productId)).Returns(null);
            A.CallTo(() => _cartRepository.Add(guid, productId)).Returns(true);

            //Act
            var result = _cartService.Add(guid, productId);

            //Assert
            Assert.That(result, Is.True);
        }
示例#23
0
        public async Task AddOrUpdate(Cart cart)
        {
            var cartItemEntity = await _cartRepository.GetBy(cart.SessionId, cart.StyleId);

            if (cartItemEntity != null)
            {
                cartItemEntity.Count += cart.Quantity;
                await _cartRepository.Update(cartItemEntity);
            }
            else
            {
                var entity = _mapper.Map <Entities.Cart>(cart);
                entity.DateCreated = DateTime.Now;
                entity.Count       = cart.Quantity == 0 ? 1 : cart.Quantity;
                await _cartRepository.Add(entity);
            }
        }
示例#24
0
        public CreateCartResponse CreateCart(CreateCartRequest request)
        {
            var response = new CreateCartResponse();

            var cart = new Cart();

            AddAlbumsToCart(request.AlbumsToAdd, cart);

            ThrowExceptionIfCartIsInvalid(cart);

            _cartRepository.Add(cart);

            _uow.Commit();

            response.Cart = cart.ConvertToCartView();

            return(response);
        }
示例#25
0
        public void addToCart(String userId, Guid gameId)
        {
            Guid userIdGuid = Guid.Empty;

            if (!Guid.TryParse(userId, out userIdGuid))
            {
                throw new Exception("Invalid Guid Format");
            }
            var user = userRepository.GetUserById(userIdGuid);
            var game = gameRepository.GetGamebyId(gameId);

            cartRepository.Add(new ShoppingCart()
            {
                Id       = Guid.NewGuid(),
                UserId   = user.Id,
                Quantity = 1,
                GameId   = game.Id
            });
        }
示例#26
0
        public void CreateCart(string customerEmail)
        {
            // Get customer
            var customer = userRepository.Get(item => item.Email == customerEmail);

            // Add new cart
            var newCart = new Cart {
                TotalCost = 0
            };

            cartRepository.Add(newCart);
            Save();

            // Add CustomerCart
            customerCartRepository.Add(new CustomerCart {
                CartId = newCart.Id, CustomerId = customer.Id
            });
            Save();
        }
示例#27
0
        public IActionResult AddToCart(int id, string returnUrl = null)
        {
            var product = _productRepository.GetById(id);

            if (product == null)
            {
                return(NotFound());
            }

            if (!Int32.TryParse(_userManager.GetUserId(User), out int userId))
            {
                return(BadRequest("User is incorrect."));
            }

            var cartItems       = _cartRepository.GetAll().Where(n => n.UserId == userId).ToList();
            var currentCartItem = cartItems?.FirstOrDefault(n => n.ProductId == product.Id);

            if (currentCartItem != null)
            {
                var updateCartItem = new CartItem
                {
                    Id        = currentCartItem.Id,
                    ProductId = currentCartItem.ProductId,
                    UserId    = currentCartItem.UserId,
                    Amount    = currentCartItem.Amount + 1
                };
                _cartRepository.Update(updateCartItem);
                _cartRepository.Commit();
                return(Redirect(returnUrl));
            }

            var cartItem = new CartItem
            {
                ProductId = id,
                UserId    = userId,
                Amount    = 1
            };

            _cartRepository.Add(cartItem);
            _cartRepository.Commit();
            return(Redirect(returnUrl));
        }
        public override AbstractOperationResult <Cart> Handle(CartCreateCommand command)
        {
            if (!command.IsValid())
            {
                NotifyValidationErrors(command);
                return(new FailureOperationResult <Cart>("error creating cart"));
            }

            if (_cartRepository.ExistsByCustomerId(command.customerId))
            {
                return(new FailureOperationResult <Cart>("cart already exists for the specified customer"));
            }

            if (!_productRepository.ExistsBySku(command.item.sku))
            {
                return(new FailureOperationResult <Cart>("product with specified sku does not exists"));
            }

            var product = _productRepository.GetBySku(command.item.sku).Result;
            var item    = new CartItem(product);

            // TODO: alterar para bater no worker e fazer o calculo correto
            item.price = command.item.quantity * product.price.amount;

            var entity = new Cart(command.id)
            {
                customerId = command.customerId,
                status     = "PENDING",
                item       = command.item,
                items      = new List <CartItem>()
                {
                    item
                }
            };

            _cartRepository.Add(entity).Wait();

            var py = _cartRepository.GetAll().Result;
            var px = _cartRepository.GetByCustomerId(entity.customerId).Result;

            return(new SuccessOperationResult <Cart>("cart created", entity));
        }
示例#29
0
        public async Task AddOrUpdate(string sessionId, int styleId, int quantity)
        {
            var cartItem = await _cartRepository.GetBy(sessionId, styleId);

            if (cartItem != null)
            {
                cartItem.Count += quantity;
                await _cartRepository.Update(cartItem);
            }
            else
            {
                await _cartRepository.Add(new Cart
                {
                    CartId      = sessionId,
                    StyleId     = styleId,
                    Count       = quantity,
                    DateCreated = DateTime.UtcNow
                });
            }
        }
示例#30
0
        public void AddToCart(int productId)
        {
            var cartItem = GetCartItem(CartId, productId);

            if (cartItem == null)
            {
                cartItem = new Cart
                {
                    CartId      = CartId,
                    ProductId   = productId,
                    Quantity    = 1,
                    DateCreated = DateTime.Now
                };
                _cartRepository.Add(cartItem);
            }
            else
            {
                cartItem.Quantity++;
            }
        }