Exemple #1
0
        /// <summary>
        /// Deletes the specified order.
        /// </summary>
        /// <param name="orderId">The id of the order to delete.</param>
        /// <returns>Returns true if the delete has succeeded, otherwise false.</returns>
        public async Task <bool> DeleteOrder(int orderId)
        {
            Order order = await this.GetByIdAsync(orderId);

            _dbContext.Orders.Remove(order);
            await _dbContext.SaveChangesAsync();

            return(true);
        }
        public async Task <IActionResult> Delete_POST(int id)
        {
            Contact contact = await _dbContext.Contacts.FindAsync(id);

            _dbContext.Contacts.Remove(contact);
            await _dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Exemple #3
0
        /// <summary>
        /// Updates the profile info of the specified user.
        /// </summary>
        /// <param name="userId">The id of the user to update.</param>
        /// <param name="firstName">The first name of the user.</param>
        /// <param name="lastName">The last name of the user.</param>
        /// <param name="emailAddress">The email address of the user.</param>
        /// <param name="phoneNumber">The phone number of the user.</param>
        /// <returns>Returns true if the update has succeeded, otherwise false.</returns>
        public async Task <bool> UpdateUserProfile(int userId, string firstName, string lastName, string emailAddress, string phoneNumber)
        {
            if (string.IsNullOrEmpty(firstName))
            {
                throw new ArgumentNullException(nameof(firstName), $"{nameof(firstName)} cannot be null or empty.");
            }
            if (string.IsNullOrEmpty(lastName))
            {
                throw new ArgumentNullException(nameof(lastName), $"{nameof(lastName)} cannot be null or empty.");
            }
            if (string.IsNullOrEmpty(emailAddress))
            {
                throw new ArgumentNullException(nameof(emailAddress), $"{nameof(emailAddress)} cannot be null or empty.");
            }

            User user = await this.GetByIdAsync(userId);

            user.FirstName        = firstName;
            user.LastName         = lastName;
            user.EmailAddress     = emailAddress;
            user.PhoneNumber      = phoneNumber;
            user.DateLastModified = DateTime.Now;

            _dbContext.Users.Update(user);
            await _dbContext.SaveChangesAsync();

            _userCache.Set(user);
            return(true);
        }
        public async Task <IActionResult> Create(CreateVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            ProductType type = new ProductType()
            {
                Name = model.Name
            };

            _dbContext.ProductTypes.Add(type);
            await _dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Exemple #5
0
        public async Task <IActionResult> Remove_POST(int id)
        {
            NewsletterSubscriber subscriber = await _dbContext.NewsletterSubscribers.FindAsync(id);

            _dbContext.NewsletterSubscribers.Remove(subscriber);
            await _dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Exemple #6
0
        public async Task <IActionResult> Create(CreateVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            DeliveryMethod deliveryMethod = new DeliveryMethod()
            {
                Name        = model.Name,
                Description = model.Description,
                Price       = model.Price
            };

            _dbContext.DeliveryMethods.Add(deliveryMethod);
            await _dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> Create(CreateVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            Sale sale = new Sale()
            {
                Name         = model.Name,
                DiscountRate = model.DiscountRate,
                DateStart    = model.DateStart,
                DateEnd      = model.DateEnd
            };

            _dbContext.Sales.Add(sale);
            await _dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Exemple #8
0
        public async Task <IActionResult> Create(CreateVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            Branch branch = new Branch()
            {
                Name              = model.Name,
                Address           = model.Address,
                PhoneNumber       = model.PhoneNumber,
                OpeningHours      = model.OpeningHours,
                LocationLatitude  = model.LocationLatitude,
                LocationLongitude = model.LocationLongitude
            };

            _dbContext.Branches.Add(branch);
            await _dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Exemple #9
0
        public async Task <IActionResult> Create(CreateVM model)
        {
            if (!ModelState.IsValid)
            {
                ViewData["ProductCategories"] = new SelectList(_dbContext.ProductCategories, nameof(ProductCategory.Id), nameof(ProductCategory.Name), model.CategoryId);
                ViewData["ProductTypes"]      = new SelectList(_dbContext.ProductTypes, nameof(ProductType.Id), nameof(ProductType.Name), model.TypeId);
                ViewData["Sales"]             = new SelectList(_dbContext.Sales, nameof(Sale.Id), nameof(Sale.Name), model.SaleId);
                return(View(model));
            }

            // Saves the product image:
            string imagePath = await SaveImage(model.ImageFile);

            Product product = new Product()
            {
                Name        = model.Name,
                Description = model.Description,
                ImagePath   = imagePath,
                Price       = model.Price,
                IsAvailable = model.IsAvailable,
                CategoryId  = model.CategoryId,
                TypeId      = model.TypeId,
                SaleId      = model.SaleId
            };

            _dbContext.Products.Add(product);
            await _dbContext.SaveChangesAsync();

            // Checks if to tweet about this:
            if (model.Tweet && !string.IsNullOrEmpty(model.TweetText))
            {
                this.PostTweet(model.TweetText);
            }

            return(RedirectToAction(nameof(Index)));
        }
Exemple #10
0
        public async Task <IActionResult> Subscribe([FromBody] SubscribeVM model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Checks the email is not already subscribed:
            if (await _dbContext.NewsletterSubscribers.AnyAsync(s => s.EmailAddress.Equals(model.EmailAddress)) == false)
            {
                NewsletterSubscriber subscriber = new NewsletterSubscriber()
                {
                    EmailAddress = model.EmailAddress
                };
                _dbContext.NewsletterSubscribers.Add(subscriber);
                await _dbContext.SaveChangesAsync();
            }
            return(Json(new { Message = "Great! We will let you know about awesome jewelry!" }));
        }
        public async Task <IActionResult> Contact(ContactVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            Contact contact = new Contact()
            {
                Name         = $"{model.FirstName} {model.LastName}",
                EmailAddress = model.EmailAddress,
                Subject      = model.Subject,
                Body         = model.Body,
                Status       = ContactStatus.Pending
            };

            _dbContext.Contacts.Add(contact);
            await _dbContext.SaveChangesAsync();

            TempData["Success"] = true;
            return(RedirectToAction(nameof(Contact)));
        }
Exemple #12
0
        /// <summary>
        /// Sets (adds or updates) the specified product and quantity in the cart.
        /// </summary>
        /// <param name="productId">The id of the product to set.</param>
        /// <param name="quantity">The quantity to set.</param>
        public async Task SetProductAsync(int productId, int quantity)
        {
            if (quantity < 1)
            {
                throw new ArgumentException($"{nameof(quantity)} cannot be less than 1.", nameof(quantity));
            }

            // First, checks the product exists and valid in the database:
            if (!await _dbContext.Products.AnyAsync(p => p.Id == productId && p.IsAvailable))
            {
                return;
            }

            // Creates/Updates the cart:
            // Now, checks if it's the first item in the cart:
            if (this.IsEmpty())
            {
                // So creates a new cart:
                this.Cart          = new ClientCart();
                this.Cart.Products = new List <ClientCartProduct>();
                ClientCartProduct cartProduct = new ClientCartProduct()
                {
                    ClientCart = Cart,
                    ProductId  = productId,
                    Quantity   = quantity
                };
                this.Cart.Products.Add(cartProduct);
                _dbContext.ClientCarts.Add(this.Cart);
            }
            // Otherwise, it's not the first item:
            else
            {
                // Checks if the product already exists in the cart:
                ClientCartProduct cartProduct = this.Cart.Products.FirstOrDefault(p => p.ProductId == productId);
                if (cartProduct != null)
                {
                    // Updates the item:
                    cartProduct.Quantity = quantity;
                    _dbContext.ClientCartProducts.Update(cartProduct);
                }
                else
                {
                    // Adds the item:
                    cartProduct = new ClientCartProduct()
                    {
                        ClientCartId = this.Cart.Id,
                        ProductId    = productId,
                        Quantity     = quantity
                    };
                    _dbContext.ClientCartProducts.Add(cartProduct);
                }
            }

            // If the user is authenticated - connects the cart to him:
            User user = await _userIdentity.GetCurrentAsync();

            if (user != null && user.ClientCartId == null)
            {
                user.ClientCart = this.Cart;
                _dbContext.Users.Update(user);
            }

            await _dbContext.SaveChangesAsync();

            // Gets the cart back from the database:
            ClientCart clientCartBack = null;

            if (user != null)
            {
                clientCartBack    = Task.Run(() => GetAuthUserCartByDatabase()).Result;
                user.ClientCartId = clientCartBack.Id;
                _userCache.Set(user);
                this.CacheAuthUserCart(user.Id, clientCartBack);
            }
            else
            {
                clientCartBack = Task.Run(() => GetClientCartByDatabase(this.Cart.Id)).Result;
                this.CacheClientCart(clientCartBack);
            }

            // If user is anonymous - sets his cart id to the cookie:
            if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated == false)
            {
                this.SetUserCartIdToCookie(this.Cart.Id);
            }
        }
        /// <summary>
        /// Registers a new user by the specified user info parameters.
        /// </summary>
        /// <remarks>Handles: password encryption, cookie authentication, client's preferences (like currency and theme), and also user cache memory.</remarks>
        /// <param name="firstName">The first name of the user.</param>
        /// <param name="lastName">The last name of the user.</param>
        /// <param name="emailAddress">The email address of the user.</param>
        /// <param name="password">The password of the user.</param>
        /// <param name="subscribeNewsletter">Indicates whether to subscribe the user to the newsletter or not.</param>
        /// <returns>Returns the user info from the database.</returns>
        public async Task <User> RegisterAsync(string firstName, string lastName, string emailAddress, string password, bool subscribeNewsletter)
        {
            if (string.IsNullOrEmpty(firstName))
            {
                throw new ArgumentNullException(nameof(firstName), $"{nameof(firstName)} cannot be null or empty.");
            }
            if (string.IsNullOrEmpty(lastName))
            {
                throw new ArgumentNullException(nameof(lastName), $"{nameof(lastName)} cannot be null or empty.");
            }
            if (string.IsNullOrEmpty(emailAddress))
            {
                throw new ArgumentNullException(nameof(emailAddress), $"{nameof(emailAddress)} cannot be null or empty.");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password), $"{nameof(password)} cannot be null or empty.");
            }

            // Creates a user object by the specified user info parameters:
            string passwordSalt = EncryptionHelper.GenerateSalt();
            string passwordHash = EncryptionHelper.HashSHA256(password + passwordSalt);
            User   newUser      = new User()
            {
                FirstName    = firstName,
                LastName     = lastName,
                EmailAddress = emailAddress,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Currency     = _clientCurrency.Currency.Code,
                Theme        = _clientTheme.Theme.ID,
                Role         = UserRole.Customer
            };

            _dbContext.Users.Add(newUser);

            // Adds to newsletter subscription:
            if (subscribeNewsletter)
            {
                // Checks the email is not already subscribed:
                if (await _dbContext.NewsletterSubscribers.AnyAsync(s => s.EmailAddress.Equals(emailAddress)) == false)
                {
                    NewsletterSubscriber subscriber = new NewsletterSubscriber()
                    {
                        EmailAddress = emailAddress
                    };
                    _dbContext.NewsletterSubscribers.Add(subscriber);
                }
            }

            await _dbContext.SaveChangesAsync();

            User userFromDB = await _users.GetUserByEmailAsync(emailAddress);

            if (userFromDB == null)
            {
                throw new NullReferenceException($"Error getting the user info after insertion to the database, {nameof(userFromDB)} cannot be null.");
            }

            this.SetClientAuthentication(userFromDB, false);
            _userCache.Set(userFromDB);
            return(userFromDB);
        }
Exemple #14
0
        public async Task <IActionResult> Checkout(CheckoutVM model)
        {
            if (_clientCart.IsEmpty())
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                // Gets the authenticated user id:
                int?userId = await GetOrAuthenticateUser(model.SignMethod, model.LoginVM, model.RegisterVM);

                if (userId.HasValue)
                {
                    // Binds the order details:
                    Address billingAddress = new Address()
                    {
                        Street     = model.BillingDetails.Street,
                        PostalCode = model.BillingDetails.PostalCode,
                        City       = model.BillingDetails.City,
                        Country    = model.BillingDetails.Country
                    };
                    Address shippingAddress = (model.ShippingDetails == null ? null : new Address()
                    {
                        Street = model.ShippingDetails.Street,
                        PostalCode = model.ShippingDetails.PostalCode,
                        City = model.ShippingDetails.City,
                        Country = model.ShippingDetails.Country
                    });
                    Order order = new Order()
                    {
                        BillingName      = model.BillingDetails.Name,
                        BillingPhone     = model.BillingDetails.Phone,
                        BillingAddress   = billingAddress,
                        ShippingName     = (model.ShippingDetails.ShippingSameAsBilling ? model.BillingDetails.Name : model.ShippingDetails.Name),
                        ShippingPhone    = (model.ShippingDetails.ShippingSameAsBilling ? model.BillingDetails.Phone : model.ShippingDetails.Phone),
                        ShippingAddress  = (model.ShippingDetails.ShippingSameAsBilling ? billingAddress : shippingAddress),
                        DeliveryMethodId = model.DeliveryMethodId.Value,
                        UserId           = userId.Value,
                        OrderProducts    = new List <OrderVsProduct>(),
                        Note             = model.Note,
                        Status           = OrderStatus.PaymentProcessing
                    };
                    foreach (var cartProduct in _clientCart.Cart.Products)
                    {
                        OrderVsProduct orderProduct = new OrderVsProduct()
                        {
                            Order        = order,
                            ProductId    = cartProduct.ProductId,
                            Quantity     = cartProduct.Quantity,
                            UnitPrice    = cartProduct.Product.Price,
                            DiscountRate = (cartProduct.Product.IsOnSaleNow() ? cartProduct.Product.Sale.DiscountRate : null)
                        };
                        order.OrderProducts.Add(orderProduct);
                    }
                    _dbContext.Orders.Add(order);
                    await _dbContext.SaveChangesAsync();

                    // Clears the shopping cart:
                    await _clientCart.Clear();

                    // Here is a good place to charge the credit card... (but sadly we don't support it)

                    return(RedirectToAction(nameof(CheckoutConfirmed), new { orderId = order.Id }));
                }
            }

            ViewData["DeliveryMethods"] = await _dbContext.DeliveryMethods.OrderBy(dm => dm.Price).ToListAsync();

            return(View(model));
        }