Example #1
0
        public async Task <IActionResult> Index(string part = "All", string brand = "All", string car = "All", string search = null, int page = 1)
        {
            ViewData["allBrands"] = await _common.GetAllBrandNamesAsync();

            ViewData["allCars"] = await _common.GetAllCarsAsync();

            ViewData["search"] = search;
            ViewData["Page"]   = page;
            var products = await GetProductsAsync(part, brand, car, search, page);

            await Task.Run(() =>
            {
                foreach (var product in products.Where(x => x.OnSale == true))
                {
                    if (product.SaleExpiration <= DateTime.UtcNow)
                    {
                        product.OnSale = false;
                        _context.Products.Update(product);
                        _context.SaveChangesAsync();
                    }
                }
            });

            return(View(products));
        }
Example #2
0
        private async Task CreateRoles(CodeRedContext context, IServiceProvider serviceProvider)
        {
            var RoleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();
            var UserManager = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();

            IList <IdentityRole> roles = new List <IdentityRole>();

            foreach (var role in Enum.GetValues(typeof(UserRoles)))
            {
                roles.Add(new IdentityRole {
                    Name = role.ToString(), NormalizedName = role.ToString().Normalize()
                });
            }

            foreach (var role in roles)
            {
                var exists = await RoleManager.RoleExistsAsync(role.Name);

                if (!exists)
                {
                    context.Roles.Add(role);
                }
            }
            await context.SaveChangesAsync();
        }
Example #3
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, EmailConfirmed = true
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        await _userManager.AddToRoleAsync(user, "Default");

                        if (user.NormalizedEmail == "*****@*****.**")
                        {
                            await _userManager.AddToRoleAsync(user, "Admin");
                        }
                        await _context.SaveChangesAsync();

                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
        public async Task <IActionResult> Index(ManageMessageId?message = null)
        {
            ViewData["StatusMessage"] =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
       : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
       : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
       : message == ManageMessageId.Error ? "An error has occurred."
       : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
       : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
       : "";

            var user = await GetCurrentUserAsync();

            if (user == null)
            {
                return(View("Error"));
            }
            var model = new IndexViewModel
            {
                HasPassword       = await _userManager.HasPasswordAsync(user),
                PhoneNumber       = await _userManager.GetPhoneNumberAsync(user),
                TwoFactor         = await _userManager.GetTwoFactorEnabledAsync(user),
                Logins            = await _userManager.GetLoginsAsync(user),
                BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user),
                UserReferral      = await _context.UserReferral.FirstOrDefaultAsync(x => x.UserId == user.Id)
            };

            if (model.UserReferral == null)
            {
                var userRef = new UserReferral
                {
                    UserId       = user.Id,
                    ReferralCode = $"{user.Email.Split('@')[0]}"
                };
                _context.UserReferral.Add(userRef);

                var refPromo = await _context.Promos.FirstOrDefaultAsync(x => x.Code == userRef.ReferralCode);

                if (refPromo == null)
                {
                    _context.Promos.Add(new PromoModel
                    {
                        Code = userRef.ReferralCode,
                        DiscountPercentage = 5,
                        Enabled            = true
                    });
                }

                await _context.SaveChangesAsync();

                model.UserReferral = userRef;
            }


            ViewData["ReferralUrl"]      = $"http://{HttpContext.Request.Host}/Home/Referral/{model.UserReferral.ReferralCode}";
            ViewData["ReferralEarnings"] = Math.Round(model.UserReferral.Earnings, 2);
            return(View(model));
        }
        public async Task <IActionResult> Checkout(string id)
        {
            var session        = HttpContext.Session.GetString(sessionKey);
            var url            = "https://www.paypal.com/us/cgi-bin/webscr";
            var paypalBusiness = _settings.PaypalBusiness;

            if (session != null)
            {
                int productCount = 1;
                var cart         = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <ShoppingCartViewModel>(session));

                if (cart.PromoModel != null)
                {
                    cart.PromoModel.TimesUsed++;
                    await _context.SaveChangesAsync();
                }

                var builder = new StringBuilder();
                builder.Append(url);
                builder.Append($"?cmd=_cart&upload=1&business={UrlEncoder.Default.Encode(paypalBusiness)}");
                builder.Append($"&lc=US&no_note=0&currency_code=USD");
                if (cart.PromoModel != null)
                {
                    builder.Append($"&custom=PromoCode:{cart.PromoModel.Code}");
                }

                var     totalValue = 0m;
                decimal taxRate    = Math.Round((decimal)9 / 100, 2);
                foreach (var product in cart.Products)
                {
                    totalValue += product.SalePrice;
                    builder.Append($"&item_name_{productCount}={UrlEncoder.Default.Encode($"{product.Brand.Name} - {product.Name}: #{product.PartNumber}")}");
                    builder.Append($"&item_number_{productCount}={UrlEncoder.Default.Encode(product.PartNumber)}");
                    builder.Append($"&amount_{productCount}={UrlEncoder.Default.Encode(product.SalePrice.ToString())}");
                    builder.Append($"&shipping_{productCount}={UrlEncoder.Default.Encode(product.Shipping.ToString())}");

                    productCount++;
                }
                decimal originalTotal = totalValue;

                if (!string.IsNullOrEmpty(id))
                {
                    var amount = decimal.Parse(id);

                    var user = await _userManager.GetUserAsync(HttpContext.User);

                    if (user != null)
                    {
                        var userRef = await _context.UserReferral.FirstOrDefaultAsync(x => x.UserId == user.Id);

                        amount = (amount > userRef.Earnings) ? userRef.Earnings : amount;
                        amount = (amount > originalTotal) ? (originalTotal - 0.01m) : amount;
                        TempData["RefAmount"] = amount.ToString();

                        builder.Append($"&discount_amount_cart={amount.ToString()}");
                    }
                }
                decimal tax = Math.Round((totalValue * taxRate), 2);
                builder.Append($"&tax_cart={UrlEncoder.Default.Encode(tax.ToString())}");


                builder.Append($"&return={UrlEncoder.Default.Encode($"https://{HttpContext.Request.Host.Value}/Home/ThankYou")}");
                builder.Append($"&cancel_return={UrlEncoder.Default.Encode($"https://{HttpContext.Request.Host.Value}/ShoppingCart")}");

                TempData["ThankYouValidation"] = true;
                return(Redirect(builder.ToString()));
            }
            return(RedirectToAction("Index"));
        }
Example #6
0
        public async Task <IActionResult> ThankYou(int?id)
        {
            var session = HttpContext.Session.GetString("ShoppingCart");
            var user    = await _userManager.GetUserAsync(HttpContext.User);

            // Makes sure that it's a legit Home/ThankYou redirect
            // Only triggered when manually navigated to Home/ThankYou
            if (TempData["ThankYouValidation"] == null || (id == null && session == null))
            {
                return(RedirectToAction("Index"));
            }

            decimal refAmount = 0m;

            // Checks if the user used store credit
            if (TempData["RefAmount"] != null && !string.IsNullOrEmpty(TempData["RefAmount"].ToString()))
            {
                refAmount = decimal.Parse(TempData["RefAmount"].ToString());
                if (refAmount > 0)
                {
                    var userRef = await _context.UserReferral.FirstOrDefaultAsync(x => x.UserId == user.Id);

                    if (userRef != null && userRef.Enabled)
                    {
                        userRef.Earnings -= refAmount;
                        _context.UserReferral.Update(userRef);
                        await _context.SaveChangesAsync();

                        TempData["Message"] = $"{refAmount.ToString("C2")} has been successfully applied on your purchase.";
                    }
                }
            }
            else // if no store credit used, then checks if there's an acctive referral account
            {
                if (HttpContext.Request.Cookies["Referral"] != null)
                {
                    var referralCookie = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <UserReferral>(HttpContext.Request.Cookies["Referral"]));

                    if (user != null)
                    {
                        if (referralCookie != null && user.Id != referralCookie.UserId)
                        {
                            const decimal referralPercent = 10;
                            const decimal referralDecimal = (referralPercent / 100);
                            if (id != null)
                            {
                                var product = await _context.Products.Include(x => x.Brand).FirstOrDefaultAsync(x => x.PartId == id);

                                referralCookie.Earnings += Math.Round(product.Price * referralDecimal, 2);
                            }
                            else if (session != null)
                            {
                                var cart = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <ShoppingCartViewModel>(session));

                                decimal cartValue = 0;
                                foreach (var item in cart.Products)
                                {
                                    cartValue += item.Price;
                                }
                                HttpContext.Session.Remove("ShoppingCart");

                                referralCookie.Earnings += Math.Round(cartValue * referralDecimal, 2);
                            }

                            _context.Update(referralCookie);
                            await _context.SaveChangesAsync();
                        }
                    }
                }
            }

            if (user != null)
            {
                var message = "<h2>Thank you for your order!</h2><p>Your order has been successfully placed. You'll recieve shipping information once it's made avaliable. If you have any questions please contact our Code Red Performance support team: <a href='mailto:[email protected]'>[email protected]</a></p>";
                await _emailSender.SendEmailAsync(user.NormalizedEmail, "Order Confirmation", "Order Confirmation", message);
            }

            return(View());
        }
Example #7
0
        public async Task <IActionResult> ToggleReferral(string id)
        {
            var userRef = await _context.UserReferral.FirstOrDefaultAsync(x => x.UserId == id);

            if (userRef != null)
            {
                userRef.Enabled = !userRef.Enabled;

                var promo = await _context.Promos.FirstOrDefaultAsync(x => x.Code == userRef.ReferralCode);

                if (promo != null)
                {
                    promo.Enabled = userRef.Enabled;
                    _context.Promos.Update(promo);
                }

                _context.UserReferral.Update(userRef);
                await _context.SaveChangesAsync();
            }

            return(RedirectToAction("ManageUsers"));
        }