public async Task <ActionResult <CustomerCart> > UpdateBasket(CustomerCart basket)
        {
            // var customerBasket = _mapper.Map<CustomerBasketDto, CustomerCart>(basket);
            var updatedBasket = await unitOfWork.Carts.UpdateAsync(basket);

            return(Ok(updatedBasket));
        }
        private async Task <CustomerCartProduct> GetCartProductValidated(Guid productId,
                                                                         CustomerCart customerCart,
                                                                         CustomerCartProduct customerCartProduct = null)
        {
            if (customerCartProduct != null && productId != customerCartProduct.Id)
            {
                AddErrorToList("Product id doesn't match.");
                return(null);
            }

            if (customerCart == null)
            {
                AddErrorToList("Customer cart not found.");
                return(null);
            }

            var itemCart = await _context.CustomerCartProducts
                           .FirstOrDefaultAsync(p => p.CustomerCartId == customerCart.Id && p.ProductId == productId);

            if (itemCart == null)
            {
                AddErrorToList("Product isn't in the cart.");
                return(null);
            }

            return(itemCart);
        }
Exemple #3
0
        public void Send(CustomerCart entity)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "checkout",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    string message = JsonConvert.SerializeObject(entity);
                    var    body    = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(exchange: "",
                                         routingKey: "checkout",
                                         basicProperties: null,
                                         body: body);
                    Console.WriteLine(" [x] Sent {0}", message);
                }
        }
Exemple #4
0
        private async Task <CartItem> GetCartItemValid(Guid produtctId, CustomerCart cart, CartItem item = null)
        {
            if (item != null && produtctId != item.ProductId)
            {
                AddProcessingError("O item não corresponde ao informado");
                return(null);
            }

            if (cart == null)
            {
                AddProcessingError("Carrinho não encontrado");
                return(null);
            }

            var itemCart = await _context.CartItens
                           .FirstOrDefaultAsync(c => c.CartId == cart.Id && c.ProductId == produtctId);

            if (itemCart == null || !cart.ExistingItemCart(itemCart))
            {
                AddProcessingError("O Item não está no carrinho");
                return(null);
            }

            return(itemCart);
        }
Exemple #5
0
        public async Task <IActionResult> PostCustomerCart([FromBody] CustomerCart customerCart)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.CustomerCart.Add(customerCart);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (CustomerCartExists(customerCart.CustomerCartId))
                {
                    return(new StatusCodeResult(StatusCodes.Status409Conflict));
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetCustomerCart", new { id = customerCart.CustomerCartId }, customerCart));
        }
Exemple #6
0
        public ICollection <CustomerCart> UpdateBookInCart(long CustomerID, long BookID, long Quantity)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    using (connection)
                    {
                        connection.Open();
                        SqlCommand cmd = new SqlCommand("UpdateBookInCart", connection)
                        {
                            CommandType = CommandType.StoredProcedure
                        };
                        cmd.Parameters.AddWithValue("CustomerID", CustomerID);
                        cmd.Parameters.AddWithValue("BookID", BookID);
                        cmd.Parameters.AddWithValue("Quantity", Quantity);
                        var returnParameter = cmd.Parameters.Add("@Result", SqlDbType.Int);
                        returnParameter.Direction = ParameterDirection.ReturnValue;
                        SqlDataReader rd     = cmd.ExecuteReader();
                        var           result = returnParameter.Value;
                        if (result != null && result.Equals(3))
                        {
                            throw new Exception("Book out of stock");
                        }
                        else if (result != null && result.Equals(2))
                        {
                            throw new Exception("Book don't exist");
                        }
                        ICollection <CustomerCart> cart = new List <CustomerCart>();
                        CustomerCart Book;
                        while (rd.Read())
                        {
                            Book = new CustomerCart();

                            Book.BookID = rd["BookID"] == DBNull.Value ? default : rd.GetInt64("BookID");

                                          Book.TotalCost = rd["TotalCost"] == DBNull.Value ? default : rd.GetInt32("TotalCost");

                                                           Book.BookPrice = rd["BookPrice"] == DBNull.Value ? default : rd.GetInt32("BookPrice");

                                                                            Book.CartID = rd["CartID"] == DBNull.Value ? default : rd.GetInt64("CartID");

                                                                                          Book.BookName = rd["BookName"] == DBNull.Value ? default : rd.GetString("BookName");

                                                                                                          Book.CustomerID = rd["CustomerID"] == DBNull.Value ? default : rd.GetInt64("CustomerID");

                                                                                                                            Book.Count = rd["BookCount"] == DBNull.Value ? default : rd.GetInt32("BookCount");

                                                                                                                                         Book.AuthorName = rd["AuthorName"] == DBNull.Value ? default : rd.GetString("AuthorName");
                                                                                                                                                           cart.Add(Book);
                        }
                        return(cart);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #7
0
        public async Task <IActionResult> PutCustomerCart([FromRoute] string id, [FromBody] CustomerCart customerCart)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != customerCart.CustomerCartId)
            {
                return(BadRequest());
            }

            _context.Entry(customerCart).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerCartExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemple #8
0
        public ActionResult Purchase(int itemList, double total)
        {
            CustomerOrderHistory coh = new CustomerOrderHistory();

            coh.LocId     = (int)HttpContext.Session.GetInt32("LocId");
            coh.CustId    = _customerBL.GetCustomerByEmail(HttpContext.Session.GetString("UserEmail")).Id;
            coh.OrderDate = DateTime.Now;
            coh.OrderId   = itemList;
            coh.Total     = total;
            _customerOrderHistoryBL.AddCustomerOrderHistory(coh);
            CustomerCart cart = new CustomerCart();

            /*cart.CustId = coh.CustId;
             * cart.LocId = coh.LocId;*/
            cart = _cartBL.GetCustomerCartByIds(coh.CustId, coh.LocId);
            cart.CurrentItemsId = _orderLineItemBL.Ident_Curr() + 1;
            _cartBL.UpdateCustomerCart(cart);
            CustomerOrderLineItem orderLineItem = new CustomerOrderLineItem();

            orderLineItem.OrderId   = cart.CurrentItemsId;
            orderLineItem.ProdId    = null;
            orderLineItem.Quantity  = 0;
            orderLineItem.ProdPrice = 0;
            _orderLineItemBL.AddCustomerOrderLineItem(orderLineItem);
            return(Redirect($"/InventoryLineItem?locId={HttpContext.Session.GetInt32("LocId")}"));
        }
Exemple #9
0
        public ActionResult DeleteItem(int id, string prodName)
        {
            try
            {
                InventoryLineItem iLI = _inventoryLineItemBL.GetInventoryLineItemById
                                            ((int)HttpContext.Session.GetInt32("LocId"), (int)_orderLineItemBL.GetCustomerOrderLineItemById(id, _productBL.GetProductByName(prodName).Id).ProdId);
                iLI.Quantity += _orderLineItemBL.GetCustomerOrderLineItemById(id, _productBL.GetProductByName(prodName).Id).Quantity;
                _inventoryLineItemBL.UpdateInventoryLineItem(iLI);
                _orderLineItemBL.DeleteCustomerOrderLineItem(_orderLineItemBL.GetCustomerOrderLineItemById(id, _productBL.GetProductByName(prodName).Id));

                //Log.Information($"Customer deleted-- Email: {email}");
                return(RedirectToAction("Cart"));
            }
            catch (Exception e)
            {
                /*Helper.WriteError(e, "Error");
                 * Helper.WriteFatal(e, "Fatal");
                 * Helper.WriteVerbose(e, "Verbose");*/

                CustomerCart cart = new CustomerCart();
                cart.CustId         = _customerBL.GetCustomerByEmail(HttpContext.Session.GetString("UserEmail")).Id;
                cart.LocId          = _locationBL.GetLocationById((int)HttpContext.Session.GetInt32("LocId")).Id;
                cart.CurrentItemsId = _orderLineItemBL.Ident_Curr() + 1;
                _cartBL.UpdateCustomerCart(cart);
                CustomerOrderLineItem orderLineItem = new CustomerOrderLineItem();
                orderLineItem.OrderId   = cart.CurrentItemsId;
                orderLineItem.ProdId    = null;
                orderLineItem.Quantity  = 0;
                orderLineItem.ProdPrice = 0;
                _orderLineItemBL.AddCustomerOrderLineItem(orderLineItem);
                return(Redirect($"/InventoryLineItem?locId={HttpContext.Session.GetInt32("LocId")}"));
            }
            //return View();
        }
        public async Task Delete_cart_and_when_get_cart_it_returns_null()
        {
            using var server = CreateServer();

            var redis = GetRedis(server);

            var repository = GetCartRepository(redis);

            var customerId = Guid.NewGuid().ToString();

            var customerCart = new CustomerCart
            {
                CustomerId = customerId,
                Items      = new List <CartItem>
                {
                    new CartItem
                    {
                        Price       = 200,
                        Quantity    = 5,
                        ProductId   = 1,
                        Id          = Guid.NewGuid(),
                        PictureUrl  = string.Empty,
                        ProductName = "Product Test 001"
                    }
                }
            };

            await repository.UpdateCart(customerCart);

            await repository.DeleteCart(customerId);

            var repositoryCart = await repository.GetCart(customerId);

            Assert.Null(repositoryCart);
        }
        public async Task Add_cart_and_get_cart_with_same_customerId_retrieves_the_same_cart()
        {
            using var server = CreateServer();

            var redis = GetRedis(server);

            var repository = GetCartRepository(redis);

            var customerId = Guid.NewGuid().ToString();

            var customerCart = new CustomerCart
            {
                CustomerId = customerId,
                Items      = new List <CartItem>
                {
                    new CartItem
                    {
                        Price       = 200,
                        Quantity    = 5,
                        ProductId   = 1,
                        Id          = Guid.NewGuid(),
                        PictureUrl  = string.Empty,
                        ProductName = "Product Test 001"
                    }
                }
            };

            await repository.UpdateCart(customerCart);

            var repositoryCart = await repository.GetCart(customerId);

            Assert.NotNull(repositoryCart);
            Assert.Equal(customerCart.CustomerId, repositoryCart.CustomerId);
            Assert.Equal(customerCart.Items.Count == 1, repositoryCart.Items.Count == 1);
        }
        public async Task <IHttpActionResult> PutCustomerCart(int id, CustomerCart customerCart)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != customerCart.Id)
            {
                return(BadRequest());
            }

            db.Entry(customerCart).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerCartExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemple #13
0
        public void UpdateCustomerCart(CustomerCart customerCart2BUpdated, CustomerCart updatedDetails)
        {
            customerCart2BUpdated.CustId         = updatedDetails.CustId;
            customerCart2BUpdated.LocId          = updatedDetails.LocId;
            customerCart2BUpdated.CurrentItemsId = updatedDetails.CurrentItemsId;

            _repo.UpdateCustomerCart(customerCart2BUpdated);
        }
        private void HandleNewCart(Guid customerId, CustomerCartProduct cartProduct)
        {
            var cart = new CustomerCart(customerId);

            cart.AddProduct(cartProduct);

            _context.CustomerCarts.Add(cart);
        }
        public void Checkout([FromBody] CustomerCart value)
        {
            var userId = value.BuyerId;
            var MsgBus = new CheckoutMsg();

            MsgBus.Send(value);
            _repository.DeleteCartAsync(userId);
        }
        public void UpdateCustomerCart(CustomerCart customerCart2BUpated)
        {
            Entity.CustomerCart oldCustomerCart = _context.CustomerCarts.Find(customerCart2BUpated.Id);
            _context.Entry(oldCustomerCart).CurrentValues.SetValues(_mapper.ParseCustomerCart(customerCart2BUpated));

            _context.SaveChanges();
            _context.ChangeTracker.Clear();
        }
Exemple #17
0
        private void HandleNewCart(CartItem item)
        {
            var cart = new CustomerCart(_user.GetUserId());

            cart.AddItem(item);

            ValidateCart(cart);
            _context.CustomersCart.Add(cart);
        }
Exemple #18
0
        public async Task <bool> UpdateAsync(CustomerCart entity)
        {
            using (var connection = this.GetOpenConnection())
            {
                var isSuucess = await connection.UpdateAsync(entity);

                return(isSuucess);
            }
        }
Exemple #19
0
        public void UpdateCustomerCart()
        {
            CustomerCart newCart = new CustomerCart();

            newCart = _customerCart;
            newCart.CurrentItemsId = (int)_customerOrderLineItem.OrderId;
            _customerCartBL.UpdateCustomerCart(_customerCart, newCart);
            _customerCart = _customerCartBL.GetCustomerCartByIds((int)_user.Id, (int)_location.Id);
        }
Exemple #20
0
 public CartCRVM cast2CartCRVM(CustomerCart cart)
 {
     return(new CartCRVM
     {
         CustId = cart.Id,
         LocId = cart.Id,
         CurrentItemsId = cart.CurrentItemsId
     });
 }
Exemple #21
0
        // Get  the customers shopping cart items.
        private List <CartItem> GetCustomerCartItems()
        {
            using (var db = new DataClasses1DataContext()) {
                // Get users shopping Cart.
                CustomerCart customerCart = db.CustomerCarts.Where(c => c.Customer == activeCustomer.Username).FirstOrDefault();
                // Get all items in this cart

                return(db.CartItems.Where(item => item.CustomerCart == customerCart.CustomerCartID).ToList());
            }
        }
Exemple #22
0
        private bool ValidateCart(CustomerCart cart)
        {
            if (cart.IsValid())
            {
                return(true);
            }

            cart.ValidationResult.Errors.ToList().ForEach(e => AddProcessingError(e.ErrorMessage));
            return(false);
        }
        public void FromEntity_Should_Return_An_EmptyObject_When_Given_An_EmptyEntity()
        {
            CustomerCart sut = new CustomerCart();

            // Act
            var mut = sut.FromEntity(null);

            //
            //mut.ShouldBe(new CartDto(), $"Should be given an empty [{nameof(CartDto)}]");
        }
Exemple #24
0
        public CustomerCart GetCustomerCartDetails()
        {
            CustomerCart newCart = new CustomerCart();

            newCart.CustId         = (int)_user.Id;
            newCart.LocId          = (int)_location.Id;
            newCart.CurrentItemsId = (int)_customerOrderLineItem.OrderId;
            _customerCart          = newCart;
            return(newCart);
        }
        public CustomerCart UpdateCustomerCart(CustomerCart customerCart2BUpated)
        {
            CustomerCart oldCustomerCart = _context.CustomerCarts.Find(customerCart2BUpated.Id);

            _context.Entry(oldCustomerCart).CurrentValues.SetValues(customerCart2BUpated);

            _context.SaveChanges();
            _context.ChangeTracker.Clear();
            return(customerCart2BUpated);
        }
Exemple #26
0
        public async Task <int> AddAsync(CustomerCart entity)
        {
            using (var connection = this.GetOpenConnection())
            {
                entity.date_created  = DateTime.UtcNow;
                entity.date_modified = DateTime.UtcNow;
                var result = await connection.InsertAsync(entity);

                return(result);
            }
        }
Exemple #27
0
        private static async ValueTask <Order> CreateCustomerOrderAsync(CustomerCart cart, IOrderRepository orderRepository)
        {
            var order = new Order()
            {
                SessionId   = Guid.NewGuid(),
                CreatedDate = DateTime.Now,
            };
            await orderRepository.SaveAsync(order);

            return(order);
        }
Exemple #28
0
        public async Task Delete_Cart_Should_Return_Bool()
        {
            var customerCart = new CustomerCart
            {
                Id = Guid.NewGuid()
            };

            var result = await Controller.DeleteCartByIdAsync(customerCart.Id);

            result.Should().Be(true);
        }
Exemple #29
0
        public async Task Given_Cart_Should_Be_Return_ItSelf()
        {
            var customerCart = new CustomerCart
            {
                Id = Guid.NewGuid()
            };

            var result = await Controller.UpdateCartAsync(customerCart);

            result.Should().Be(customerCart);
        }
Exemple #30
0
        public async Task <CustomerCart> UpdateCartAsync(CustomerCart cart)
        {
            var created = await _database.StringSetAsync(cart.Id, JsonSerializer.Serialize(cart), TimeSpan.FromDays(30));

            if (!created)
            {
                return(null);
            }

            return(await GetCartAsync(cart.Id));
        }