Example #1
0
        /// <summary>
        /// Adds item to shopping cart and redirect to shopping cart page.
        /// </summary>
        protected void ButtonAddToCart_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
            {
                return;
            }

            // Retrieve product via Product Facade.
            var repository = new ProductRepository();

            ActionServiceReference.Product product = repository.GetProduct(ProductId);

            // Get product details and add information to cart.
            int    productId = product.ProductId;
            string name      = product.ProductName;
            double unitPrice = product.UnitPrice;

            int quantity;

            if (!int.TryParse(TextBoxQuantity.Text.Trim(), out quantity))
            {
                quantity = 1;
            }

            var cartRepository = new CartRepository();

            cartRepository.AddItem(productId, name, quantity, unitPrice);

            // Show shopping cart to user.
            Response.Redirect(UrlMaker.ToCart());
        }
Example #2
0
        public void InsertCartItemTest()
        {
            CartRepository.AddToCart(cart);
            var cartFromList = CartRepository.GetCartItemById(cart.Id);

            Assert.AreEqual(cart, cartFromList);
        }
Example #3
0
 public CartController(IRepository repository, AddToCartViewModel.Factory viewModelFactory, CartSerializer cartSerializer, CartRepository cartRepository)
 {
     this.repository       = repository;
     this.viewModelFactory = viewModelFactory;
     this.cartSerializer   = cartSerializer;
     this.cartRepository   = cartRepository;
 }
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                var cartInList = CartRepository.GetCartItemById(id);

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

                if (cartInList.Quantity > 1)
                {
                    cartInList.Quantity = --cartInList.Quantity;
                    CartRepository.Update(cartInList);
                }
                else
                {
                    CartRepository.RemoveCartItem(cartInList);
                }

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
        public void SetUp()
        {
            //Arrange
            _container  = new AutoMocker();
            _repository = _container.CreateInstance <CartRepository>();

            var cacheProvider = _container.GetMock <ICacheProvider>();

            cacheProvider
            .Setup(provider => provider.GetOrAddAsync(
                       It.IsNotNull <CacheKey>(),
                       It.IsNotNull <Func <Task <ProcessedCart> > >(),
                       It.IsAny <Func <ProcessedCart, Task> >(),
                       It.IsAny <CacheKey>()))
            .Returns <CacheKey, Func <Task <ProcessedCart> >, Func <ProcessedCart, Task>, CacheKey>(
                (key, func, arg3, arg4) => func())
            .Verifiable();

            var overtureClient = _container.GetMock <IOvertureClient>();
            var dummyCart      = new ProcessedCart();

            overtureClient
            .Setup(client => client.SendAsync(
                       It.IsNotNull <GetCartRequest>()))
            .ReturnsAsync(dummyCart)
            .Verifiable();
        }
Example #6
0
        public ActionResult DeleteCartItem(int cartItemId)
        {
            var    msgType = false;
            string msg;

            try
            {
                if (Application.LoggedRequestorId != null)
                {
                    var userId = (int)Application.LoggedRequestorId;
                    CartRepository.DeleteCartStuff(userId, cartItemId);

                    msgType = true;
                    msg     = Requestor.Req_Cart_MaterialDelete;
                }
                else
                {
                    msg = Common.ErrorMsgForSession;
                }
            }
            catch (Exception e)
            {
                msg = e.Message;
                Logger.LogError(e, "Error while deleting cart item from Requestor zone");
            }

            return(Json(new
            {
                success = msgType,
                message = msg
            }));
        }
        public virtual async Task <CompleteCheckoutViewModel> CompleteCheckoutAsync(CompleteCheckoutParam param)
        {
            if (param == null)
            {
                throw new ArgumentNullException(nameof(param), "param");
            }
            if (param.CultureInfo == null)
            {
                throw new ArgumentException(ArgumentNullMessageFormatter.FormatErrorMessage("CultureInfo"), nameof(param));
            }
            if (string.IsNullOrWhiteSpace(param.CartName))
            {
                throw new ArgumentException(ArgumentNullMessageFormatter.FormatErrorMessage("CartName"), nameof(param));
            }
            if (string.IsNullOrWhiteSpace(param.Scope))
            {
                throw new ArgumentException(ArgumentNullMessageFormatter.FormatErrorMessage("Scope"), nameof(param));
            }
            if (param.CustomerId == Guid.Empty)
            {
                throw new ArgumentException(ArgumentNullMessageFormatter.FormatErrorMessage("CustomerId"), nameof(param));
            }

            var order = await CartRepository.CompleteCheckoutAsync(param).ConfigureAwait(false);

            return(MapOrderToCompleteCheckoutViewModel(order, param.CultureInfo));
        }
Example #8
0
        public virtual async Task <CompleteCheckoutViewModel> CompleteCheckoutAsync(CompleteCheckoutParam param)
        {
            if (param == null)
            {
                throw new ArgumentNullException(nameof(param));
            }
            if (param.CultureInfo == null)
            {
                throw new ArgumentException(GetMessageOfNull(nameof(param.CultureInfo)), nameof(param));
            }
            if (string.IsNullOrWhiteSpace(param.CartName))
            {
                throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(param.CartName)), nameof(param));
            }
            if (string.IsNullOrWhiteSpace(param.Scope))
            {
                throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(param.Scope)), nameof(param));
            }
            if (param.CustomerId == Guid.Empty)
            {
                throw new ArgumentException(GetMessageOfEmpty(nameof(param.CustomerId)), nameof(param));
            }

            var order = await CartRepository.CompleteCheckoutAsync(param).ConfigureAwait(false);

            return(await MapOrderToCompleteCheckoutViewModel(order, param).ConfigureAwait(false));
        }
Example #9
0
        protected void UpdateCartBtn_Click(object sender, EventArgs e)
        {
            Products p = new Products();

            p = CartController.getProductByID(id);
            int quantity = Int32.Parse(NewQuantityBox.Text);


            int    stock    = p.Stock;
            String Notvalid = CartController.updateValidation(quantity, stock, p.ID);

            if (!Notvalid.Equals(""))
            {
                ErrorMsg.Text = Notvalid;
            }
            else if (quantity == 0)
            {
                //delete
                int userId = Convert.ToInt32(Session["userId"].ToString());
                CartRepository.deleteItem(userId, p.ID);
                Response.Redirect("ViewCart.aspx");
            }
            else
            {
                int userId = Convert.ToInt32(Session["userId"].ToString());
                CartRepository.updateCarts(userId, p.ID, quantity);
                Response.Redirect("ViewCart.aspx");
            }
        }
        public async Task GetAll_WhenCalled_ShouldEventually_FetchAllCartItems()
        {
            var data = new List <CartItem>();

            data.Add(new CartItem(Guid.NewGuid().ToString(), "some-name-1", 45.99m, "some-manufacturer", DateTime.UtcNow));
            var response = TryOptionAsync <List <CartItem> >(() => Task.Run(() => data));

            var documentDbClient = new Mock <IDocumentDbClient <CartItem> >();

            documentDbClient.Setup(mock => mock.GetDocumentsAsync(It.IsAny <int>(), It.IsAny <int>()))
            .Returns(response);

            var sut      = new CartRepository(documentDbClient.Object);
            var expected = Some(new PagedResult <CartItem>(
                                    data, 1, 1, 1
                                    ));

            await match <Exception, Option <PagedResult <CartItem> > >(sut.GetAll(0, 1),
                                                                       Right : result => Assert.Equal(expected, result),
                                                                       Left :  _ => Assert.False(true, "Shouldn't get here!")
                                                                       );

            documentDbClient.Verify(
                mock => mock.GetDocumentsAsync(
                    It.Is <int>(number => number == 0),
                    It.Is <int>(number => number == 1)
                    ),
                Times.Once
                );
        }
        public async Task GetAll_WhenCalled_AndExceptionOccurs_ShouldEventually_ReturnException()
        {
            var expected = new Exception("Unknown error occurred!");
            var response = TryOptionAsync <List <CartItem> >(() => throw expected);

            var documentDbClient = new Mock <IDocumentDbClient <CartItem> >();

            documentDbClient.Setup(mock => mock.GetDocumentsAsync(It.IsAny <int>(), It.IsAny <int>()))
            .Returns(response);

            var sut = new CartRepository(documentDbClient.Object);

            await match <Exception, Option <PagedResult <CartItem> > >(sut.GetAll(0, 1),
                                                                       Right :  _ => Assert.False(true, "Shouldn't get here!"),
                                                                       Left : ex => Assert.Equal(expected, ex)
                                                                       );

            documentDbClient.Verify(
                mock => mock.GetDocumentsAsync(
                    It.Is <int>(number => number == 0),
                    It.Is <int>(number => number == 1)
                    ),
                Times.Once
                );
        }
        public async Task Update_WhenCalled_AndExceptionOccurs_ShouldEventually_ReturnException()
        {
            var expectedId  = Guid.NewGuid().ToString();
            var updatedItem = new CartItem(expectedId, "some-name-1", 45.99m, "some-manufacturer", DateTime.UtcNow);
            var expected    = new Exception("Unknown error occurred!");
            var response    = TryOptionAsync <CartItem>(() => throw expected);

            var documentDbClient = new Mock <IDocumentDbClient <CartItem> >();

            documentDbClient.Setup(mock => mock.ReplaceDocumentAsync(It.IsAny <Func <CartItem, bool> >(), It.IsAny <CartItem>()))
            .Returns(response);
            var sut = new CartRepository(documentDbClient.Object);

            await match <Exception, Option <CartItem> >(sut.Update(updatedItem),
                                                        Right :  _ => Assert.False(true, "Shouldn't get here!"),
                                                        Left : ex => Assert.Equal(expected, ex)
                                                        );

            documentDbClient.Verify(
                mock => mock.ReplaceDocumentAsync(
                    It.IsAny <Func <CartItem, bool> >(),
                    It.Is <CartItem>(item => item.Equals(updatedItem))
                    ),
                Times.Once
                );
        }
        public void CartRepository_WithNoNullArguments_ShouldReturnDocumentDbClient()
        {
            var dbClientMock = new Mock <IDocumentDbClient <CartItem> >();
            var sut          = new CartRepository(dbClientMock.Object);

            Assert.NotNull(sut);
        }
Example #14
0
        public static void updateQtyForExistingItem(int userId, int itemId, int qty)
        {
            vCart currentCartItem = CartRepository.findProduct(userId, itemId);

            qty = currentCartItem.Quantity + qty;
            CartRepository.update(userId, itemId, qty);
        }
Example #15
0
 // 2. Show total shelter count
 public ActionResult TotalShelter()
 {
     return(Json(new
     {
         TotalProducts = CartRepository.GetTotalStuffCount(Application.LoggedRequestorId)
     }, JsonRequestBehavior.AllowGet));
 }
        public static bool Checkout(int userId)
        {
            List <Cart> carts = GetThisUserCart(userId);

            if (carts.Count == 0)
            {
                return(false);
            }
            else
            {
                TransactionHeader transactionHeader = TransactionHeaderFactory.Create(userId);

                if (TransactionHeaderRepository.InsertTransactionHeader(transactionHeader))
                {
                    int headerId = transactionHeader.Id;

                    for (int i = 0; i < carts.Count(); i++)
                    {
                        TransactionDetail transactionDetail = TransactionDetailFactory.Create(headerId, carts[i].ProductId, carts[i].Quantity);
                        TransactionDetailRepository.InsertTransactionDetail(transactionDetail);
                    }

                    for (int i = 0; i < carts.Count(); i++)
                    {
                        CartRepository.RemoveCart(carts[i]);
                    }

                    return(true);
                }

                return(false);
            }
        }
Example #17
0
        public ActionResult SaveCartStuffs()
        {
            var    msgType = false;
            string msg;

            try
            {
                if (Application.LoggedRequestorId != null)
                {
                    var userId = (int)Application.LoggedRequestorId;
                    CartRepository.SaveRequest(userId);

                    msgType = true;
                    msg     = Requestor.Req_Cart_MaterialSaved;
                }
                else
                {
                    msg = Common.ErrorMsgForSession;
                }
            }
            catch (Exception e)
            {
                msg = e.Message;
                BaseRepository.OimsDataContext.ClearChanges(); // Roll back all changes
                Logger.LogError(e, "Error while saving cart stuff from Requestor zone");
            }

            return(Json(new
            {
                success = msgType,
                message = msg
            }));
        }
Example #18
0
        public CartRepositoryTests()
        {
            container = new PointOfScaleContainer();

            cartRepository = new CartRepository(container);

            container.CartLines = new List <CartLine>
            {
                new CartLine {
                    Product = new Product {
                        Code = "A", RetailPrice = 1.25m, VolumePrice = 3m, VolumeQuantity = 3
                    }, Quantity = 1
                },
                new CartLine {
                    Product = new Product {
                        Code = "B", RetailPrice = 4.25m
                    }, Quantity = 2
                },
                new CartLine {
                    Product = new Product {
                        Code = "C", RetailPrice = 1m, VolumePrice = 5m, VolumeQuantity = 6
                    }, Quantity = 3
                },
                new CartLine {
                    Product = new Product {
                        Code = "D", RetailPrice = 0.75m
                    }, Quantity = 4
                }
            };
        }
Example #19
0
        protected void cartDetail_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int id = Int32.Parse(e.CommandArgument.ToString());

            CartRepository.deleteProductFromCartByCartId(id);
            Response.Redirect("CartPage.aspx");
        }
        /// <summary>
        /// Adds a coupon to the Cart.
        /// </summary>
        /// <param name="param"></param>
        /// <returns>The lightweight CartViewModel</returns>
        public virtual async Task <CartViewModel> AddCouponAsync(CouponParam param)
        {
            var cart = await CartRepository.AddCouponAsync(param).ConfigureAwait(false);

            await CartRepository.RemoveCouponsAsync(new RemoveCouponsParam
            {
                CartName    = param.CartName,
                CouponCodes = GetInvalidCouponsCode(cart.Coupons).ToList(),
                CustomerId  = param.CustomerId,
                Scope       = param.Scope
            }).ConfigureAwait(false);

            var vmParam = new CreateCartViewModelParam
            {
                Cart        = cart,
                CultureInfo = param.CultureInfo,
                IncludeInvalidCouponsMessages = true,
                BaseUrl = param.BaseUrl
            };

            var viewModel = await CreateCartViewModelAsync(vmParam).ConfigureAwait(false);

            AddSuccessMessageIfRequired(param, viewModel, param.CultureInfo);

            return(viewModel);
        }
        public ActionResult IncreaseQuantity(int productId)
        {
            try
            {
                var cartInList = CartRepository.GetCartItemByProductId(productId);

                if (cartInList != null)
                {
                    if (cartInList.StockControl.ProductAmount > cartInList.Quantity)
                    {
                        cartInList.Quantity = ++cartInList.Quantity;
                        CartRepository.Update(cartInList);
                    }
                    else
                    {
                        var cartItems = CartRepository.GetCartItems();
                        ModelState.AddModelError(string.Empty, "Nuk ka produkt te mjaftueshem ne stok!");
                        return(View("~/Views/Carts/Index.cshtml", cartItems));
                    }
                }

                return(RedirectToAction(nameof(Index), "Carts"));
            }
            catch
            {
                return(View());
            }
        }
 public ProductController()
 {
     context    = new ApplicationDbContext();
     products   = new ProductRepository(context);
     categories = new CategoryRepository(context);
     carts      = new CartRepository(context);
 }
Example #23
0
        protected virtual async Task <Payment> PreparePaymentSwitch(UpdatePaymentMethodParam param, Payment activePayment)
        {
            //TODO: Remove for now, but we should void (Bug with Moneris when payment is PendingVerification).
            await PaymentRepository.RemovePaymentAsync(new VoidOrRemovePaymentParam
            {
                CartName    = param.CartName,
                CultureInfo = param.CultureInfo,
                CustomerId  = param.CustomerId,
                PaymentId   = activePayment.Id,
                Scope       = param.Scope
            }).ConfigureAwait(false);

            var cart = await CartRepository.AddPaymentAsync(new AddPaymentParam
            {
                BillingAddress = activePayment.BillingAddress.Clone(),
                CartName       = param.CartName,
                CultureInfo    = param.CultureInfo,
                CustomerId     = param.CustomerId,
                Scope          = param.Scope
            });

            var newPayment = GetActivePayment(cart);

            return(newPayment);
        }
Example #24
0
        //TODO: Remove the InventoryLocationProvider and pass the FulfillmentLocationId by parameter
        public virtual async Task <ProcessedCart> SetFulfillmentLocationIfRequired(FixCartParam param)
        {
            var cart = param.Cart;

            if (!HasValidFulfillmentLocation(cart))
            {
                var fulfillmentLocation =
                    await InventoryLocationProvider.GetFulfillmentLocationAsync(new GetFulfillmentLocationParam
                {
                    Scope = cart.ScopeId
                }).ConfigureAwait(false);

                var shipment = cart.Shipments.FirstOrDefault() ?? new Shipment();

                cart = await CartRepository.UpdateShipmentAsync(new UpdateShipmentParam
                {
                    CartName                          = cart.Name,
                    CultureInfo                       = new CultureInfo(cart.CultureName),
                    FulfillmentLocationId             = fulfillmentLocation.Id,
                    CustomerId                        = cart.CustomerId,
                    FulfillmentMethodName             = shipment.FulfillmentMethod?.Name,
                    FulfillmentScheduleMode           = shipment.FulfillmentScheduleMode,
                    FulfillmentScheduledTimeBeginDate = shipment.FulfillmentScheduledTimeBeginDate,
                    FulfillmentScheduledTimeEndDate   = shipment.FulfillmentScheduledTimeEndDate,
                    PropertyBag                       = shipment.PropertyBag,
                    Id                 = shipment.Id,
                    ScopeId            = cart.ScopeId,
                    ShippingAddress    = shipment.Address,
                    ShippingProviderId = shipment.FulfillmentMethod == null ? Guid.Empty : shipment.FulfillmentMethod.ShippingProviderId
                }).ConfigureAwait(false);
            }

            return(cart);
        }
        public IActionResult Index()
        {
            CartRepository repositoryCart = new CartRepository();

            Console.WriteLine(repositoryCart.GetAll());
            return(View(repositoryCart.GetAll()));
        }
        public virtual async Task <LightRecurringOrderCartsViewModel> GetLightRecurringOrderCartListViewModelAsync(GetLightRecurringOrderCartListViewModelParam param)
        {
            if (!RecurringOrdersSettings.Enabled)
            {
                return(new LightRecurringOrderCartsViewModel());
            }

            var carts = await CartRepository.GetRecurringCartsAsync(new GetRecurringOrderCartsViewModelParam {
                Scope       = param.Scope,
                CultureInfo = param.CultureInfo,
                BaseUrl     = param.BaseUrl,
                CustomerId  = param.CustomerId
            }).ConfigureAwait(false);

            var tasks = carts.Select(pc => CreateLightCartViewModelAsync(new CreateLightRecurringOrderCartViewModelParam
            {
                Cart        = pc,
                CultureInfo = param.CultureInfo,
                BaseUrl     = param.BaseUrl,
            }));
            var viewModels = await Task.WhenAll(tasks);

            return(new LightRecurringOrderCartsViewModel
            {
                RecurringOrderCarts = viewModels.OrderBy(v => v.NextOccurence).ToList(),
            });
        }
        public void InitializeTest()
        {
            _cartRepository = new CartRepository();

            _cartRepository.Add(new CartItem(_products[0], 1));
            _cartRepository.Add(new CartItem(_products[1], 2));
        }
        public virtual async Task <CartViewModel> GetRecurringOrderCartViewModelAsync(GetRecurringOrderCartViewModelParam param)
        {
            var emptyVm = GetEmptyRecurringOrderCartViewModel();

            if (!RecurringOrdersSettings.Enabled)
            {
                return(emptyVm);
            }

            if (string.Equals(param.CartName, CartConfiguration.ShoppingCartName, StringComparison.OrdinalIgnoreCase))
            {
                return(emptyVm);
            }

            var cart = await CartRepository.GetCartAsync(new GetCartParam
            {
                CartName        = param.CartName,
                BaseUrl         = param.BaseUrl,
                CultureInfo     = param.CultureInfo,
                CustomerId      = param.CustomerId,
                ExecuteWorkflow = true,
                Scope           = param.Scope
            }).ConfigureAwait(false);

            var vm = await CreateCartViewModelAsync(new CreateRecurringOrderCartViewModelParam
            {
                Cart        = cart,
                CultureInfo = param.CultureInfo,
                IncludeInvalidCouponsMessages = false,
                BaseUrl = param.BaseUrl,
            });

            return(vm);
        }
Example #29
0
        /// <summary>
        /// Get the Shipping methods available for a shipment. Calls the GetCart to get the shipment Id.
        /// </summary>
        /// <param name="param"></param>
        /// <returns>The ShippingMethodsViewModel</returns>
        public async virtual Task <ShippingMethodsViewModel> GetRecurringCartShippingMethodsAsync(GetShippingMethodsParam param)
        {
            if (param == null)
            {
                throw new ArgumentNullException("param", "param is required");
            }
            if (string.IsNullOrWhiteSpace(param.CartName))
            {
                throw new ArgumentException("param.CartName is required", "param");
            }
            if (string.IsNullOrWhiteSpace(param.Scope))
            {
                throw new ArgumentException("param.Scope is required", "param");
            }
            if (param.CustomerId == Guid.Empty)
            {
                throw new ArgumentException("param.CustomerId is required", "param");
            }
            if (param.CultureInfo == null)
            {
                throw new ArgumentException("param.CultureInfo is required", "param");
            }
            //misleading method name, creates a cart if it does not exist, not just a "get" call
            await CartRepository.GetCartAsync(new GetCartParam
            {
                BaseUrl     = string.Empty,
                CartName    = param.CartName,
                CultureInfo = param.CultureInfo,
                CustomerId  = param.CustomerId,
                Scope       = param.Scope
            }).ConfigureAwait(false);

            return(await GetShippingMethodsAsync(param));
        }
Example #30
0
        public ProductController()
        {
            var context = new ApplicationDbContext();

            ProductRepository = new ProductRepository(context);
            CartRepository    = new CartRepository(context);
        }
Example #31
0
 public UnitOfWork(ProjectContext context)
 {
     _context = context;
     Products = new ProductRepository(_context);
     Categories = new CategoryRepository(_context);
     Users = new AuthRepository(_context);
     Carts = new CartRepository(_context);
     Orders = new OrderRepository(_context);
 }