protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool authorize = false;

            try
            {
                int userId = int.Parse(Convert.ToString(httpContext.Session["UserId"]));
                if (userId != 0)
                {
                    using (var context = new FreshChoiceEntities())
                    {
                        var userRole = (from u in context.Users
                                        join r in context.Roles on u.RoleId equals r.RoleId
                                        where u.UserId == userId
                                        select new
                        {
                            r.RoleName
                        }).FirstOrDefault();
                        foreach (var role in allowedroles)
                        {
                            if (role == userRole.RoleName)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }
            catch {}

            return(authorize);
        }
Example #2
0
        public List <OrderCartItem> GetOrderCartItems()
        {
            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                List <CartItem> cartItems = GetCartItems();

                if (cartItems != null)
                {
                    List <OrderCartItem> orderCartItems = new List <OrderCartItem>();
                    foreach (var item in cartItems)
                    {
                        OrderCartItem orderCartItem     = new OrderCartItem();
                        Item          selectedItem      = db.Items.Where(w => w.ItemId == item.ItemId).FirstOrDefault();
                        Image         selectedItemImage = db.Images.Where(w => w.ItemId == item.ItemId).FirstOrDefault();
                        orderCartItem.ItemId          = item.ItemId;
                        orderCartItem.Quantity        = item.CartItemQnt;
                        orderCartItem.ItemName        = selectedItem.ItemName;
                        orderCartItem.ItemPrice       = selectedItem.ItemPrice;
                        orderCartItem.ItemDescription = selectedItem.ItemDescription;
                        if (selectedItemImage != null)
                        {
                            orderCartItem.ItemImageUrl = selectedItemImage.ImageUrl;
                        }
                        orderCartItems.Add(orderCartItem);
                    }
                    return(orderCartItems);
                }
            }
            return(null);
        }
Example #3
0
        public ActionResult SaveBrand(int?CategoryId, string BrandName, int?BrandId)
        {
            bool result = false;

            if ((BrandId == null && CategoryId == null) || BrandName.Length < 1)
            {
                return(Json(result));
            }
            try
            {
                using (FreshChoiceEntities db = new FreshChoiceEntities())
                {
                    Brand brand = new Brand();
                    if (BrandId == null)
                    {
                        brand.CategoryId = (int)CategoryId;
                        brand.BrandName  = BrandName;
                        db.Brands.Add(brand);
                    }
                    else
                    {
                        brand           = db.Brands.Where(w => w.BrandId == BrandId).FirstOrDefault();
                        brand.BrandName = BrandName;
                    }

                    db.SaveChanges();
                    result = true;
                }
            }
            catch (Exception) { }
            return(Json(result));
        }
Example #4
0
        public ActionResult EditItem(int?Id)
        {
            EditItemViewModel viewModel = new EditItemViewModel();

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                if (Id == null)
                {
                    viewModel.Item = new Item();
                }
                else
                {
                    viewModel.Item = db.Items.Where(w => w.ItemId == (int)Id).FirstOrDefault();
                }
                viewModel.Categories = db.Categories.ToList();
                viewModel.Brands     = db.Brands.ToList();

                viewModel.Images = db.Images.Where(w => w.ItemId == viewModel.Item.ItemId).ToList();

                var catJson = viewModel.Categories
                              .Select(s => new { s.CategoryName, s.CategoryId })
                              .ToList();
                var brandJson = viewModel.Brands
                                .Select(s => new { s.BrandName, s.CategoryId, s.BrandId })
                                .ToList();

                viewModel.CategoriesJson = JsonConvert.SerializeObject(catJson);
                viewModel.BrandsJson     = JsonConvert.SerializeObject(brandJson);
            }
            return(View(viewModel));
        }
Example #5
0
        public ActionResult SaveCategory(int CategoryId, string CategoryName)
        {
            bool result = false;

            try
            {
                using (FreshChoiceEntities db = new FreshChoiceEntities())
                {
                    Category category = new Category();
                    if (CategoryId == 0)
                    {
                        category.CategoryName = CategoryName;
                        db.Categories.Add(category);
                    }
                    else
                    {
                        category = db.Categories.Where(w => w.CategoryId == CategoryId).FirstOrDefault();
                        category.CategoryName = CategoryName;
                    }

                    db.SaveChanges();
                    result = true;
                }
            }
            catch (Exception) { }
            return(Json(result));
        }
Example #6
0
 public bool IsEmailExist(string emailID)
 {
     using (FreshChoiceEntities dc = new FreshChoiceEntities())
     {
         var v = dc.Users.Where(a => a.UserEmail == emailID).FirstOrDefault();
         return(v != null);
     }
 }
Example #7
0
        public bool CancelOrder(int OrderId)
        {
            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                Order order = db.Orders.Where(w => w.OrderId == OrderId).FirstOrDefault();
                if (order != null)
                {
                    // delete order
                    Cart cart = db.Carts.Where(w => w.CartId == order.CartId).FirstOrDefault();
                    // add amount to user wallet
                    Wallet wallet = db.Wallets.Where(w => w.UserId == currentUserId).FirstOrDefault();
                    if (wallet == null)
                    {
                        // create wallet
                        wallet = new Wallet();
                        wallet.WalletDescription = currentUserId + "_wallet";
                        wallet.WalletTotal       = 0;
                        wallet.UserId            = currentUserId;
                        db.Wallets.Add(wallet);
                        db.SaveChanges();
                    }
                    // create transaction
                    Transaction transaction = new Transaction();
                    transaction.TransactionDate        = DateTime.Now;
                    transaction.TransactionDescription = "cancel_order_" + order.OrderId;
                    transaction.TransactionAmount      = order.OrderAmount;
                    transaction.WalletId = wallet.WalletId;
                    db.Transactions.Add(transaction);
                    wallet.WalletTotal += order.OrderAmount;
                    db.SaveChanges();

                    db.Orders.Remove(order);
                    db.SaveChanges();

                    // add items to list again
                    if (cart != null)
                    {
                        var items = db.CartItems
                                    .Where(w => w.CartId == cart.CartId)
                                    .Join(
                            db.Items,
                            ci => ci.ItemId,
                            i => i.ItemId,
                            (ci, i) => new { Item = i, CartItem = ci })
                                    .ToList();
                        // update available quantity
                        foreach (var item in items)
                        {
                            Item item1 = db.Items.Where(w => w.ItemId == item.Item.ItemId).FirstOrDefault();
                            item1.ItemAvailableQnt += item.CartItem.CartItemQnt;
                            db.SaveChanges();
                        }
                    }
                    return(true);
                }
            }
            return(false);
        }
Example #8
0
        public List <OrderCartItem> AddItemToCart(int ItemId, int Quantity = 1)
        {
            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                Item item = db.Items.Where(w => w.ItemId == ItemId).FirstOrDefault();
                if (item != null && item.ItemAvailableQnt >= Quantity)
                {
                    bool isNewCart = false;
                    if (currentCart == null)
                    {
                        currentCart = new Cart();
                        currentCart.CartIsActive = true;
                        currentCart.UserId       = currentUserId;
                        db.Carts.Add(currentCart);
                        db.SaveChanges();
                        isNewCart = true;
                    }

                    CartItem cartItem = null;
                    if (!isNewCart)
                    {
                        // check this item is already exist in cart
                        cartItem = db.CartItems
                                   .Where(w => w.CartId == currentCart.CartId && w.ItemId == ItemId)
                                   .FirstOrDefault();
                    }
                    if (cartItem != null)
                    {
                        cartItem.CartItemQnt       += Quantity;
                        cartItem.CartItemTotalPrice = cartItem.CartItemQnt * item.ItemPrice;
                    }
                    else
                    {
                        // New
                        cartItem                    = new CartItem();
                        cartItem.ItemId             = ItemId;
                        cartItem.CartId             = currentCart.CartId;
                        cartItem.CartItemTotalPrice = item.ItemPrice * Quantity;
                        cartItem.CartItemQnt       += Quantity;
                        db.CartItems.Add(cartItem);
                    }
                    db.SaveChanges();
                    item.ItemAvailableQnt -= Quantity;
                    db.SaveChanges();
                }
                else
                {
                    return(null);
                }

                // add it to cart

                // return new cart items
                return(GetOrderCartItems());
            }
        }
Example #9
0
        public ActionResult Items()
        {
            List <Item> items = new List <Item>();

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                items = db.Items.Where(w => w.ItemIsDeleted == null || w.ItemIsDeleted != true).ToList();
            }
            return(View(items));
        }
Example #10
0
        public JsonResult GetCategories()
        {
            List <Category> categories;

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                categories = db.Categories.ToList();
            }
            return(Json(new { categories = categories, JsonRequestBehavior.AllowGet }));
        }
Example #11
0
        public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user)
        {
            bool   Status  = false;
            string message = "";

            //
            // Model Validation
            if (true)
            {
                #region //Email is already Exist
                var isExist = IsEmailExist(user.UserEmail);
                if (isExist)
                {
                    ModelState.AddModelError("EmailExist", "Email already exist");
                    return(View(user));
                }
                #endregion

                #region Generate Activation Code
                user.ActivationCode = Guid.NewGuid();
                #endregion

                #region  Password Hashing
                user.UserName        = user.FirstName + " " + user.LastName;
                user.UserContact     = user.UserContact;
                user.RoleId          = 1;
                user.UserPassword    = Crypto.Hash(user.UserPassword);
                user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword); //
                #endregion
                user.IsEmailVerified = false;

                #region Save to Database
                using (FreshChoiceEntities dc = new FreshChoiceEntities())
                {
                    dc.Users.Add(user);
                    dc.SaveChanges();

                    //Send Email to User
                    SendVerificationLinkEmail(user.UserEmail, user.ActivationCode.ToString());
                    message = "Registration successfully done. Account activation link " +
                              " has been sent to your email id:" + user.UserEmail;
                    Status = true;
                }
                #endregion
            }
            else
            {
                message = "Invalid Request";
            }

            ViewBag.Message = message;
            ViewBag.Status  = Status;
            return(Redirect("/"));
        }
Example #12
0
        public ActionResult ManageCategories()
        {
            ManageCategoriesViewModel viewModel = new ManageCategoriesViewModel();

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                viewModel.Categories = db.Categories.ToList();
                viewModel.Brands     = db.Brands.ToList();
            }
            return(View(viewModel));
        }
Example #13
0
        public ActionResult Products(int CategoryId = 0, String q = null, int BrandId = 0)
        {
            int userId = int.Parse(Convert.ToString(Session["UserId"]));
            List <OrderCartItem> cartItems = CartHelper.GetInstance(userId).GetOrderCartItems();
            IndexViewModel       viewModel = new IndexViewModel();

            if (cartItems != null && cartItems.Count > 0)
            {
                viewModel.InCartCount = cartItems.Count;
            }
            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                List <Item> items = items = db.Items.ToList();
                if (CategoryId != 0)
                {
                    items = items.Where(w => w.Brand.CategoryId == CategoryId).ToList();
                }
                if (q != null)
                {
                    items = items.Where(w => w.ItemName.ToLower().StartsWith(q.ToLower())).ToList();
                }
                if (BrandId != 0)
                {
                    items = items.Where(w => w.Brand.BrandId == BrandId).ToList();
                }
                viewModel.Items = new List <IndexItem>();
                foreach (var item in items)
                {
                    IndexItem orderItem = new IndexItem();
                    orderItem.ItemName        = item.ItemName;
                    orderItem.ItemDescription = item.ItemDescription;
                    orderItem.ItemId          = item.ItemId;
                    orderItem.ItemPrice       = item.ItemPrice;
                    orderItem.ItemBrand       = item.Brand.BrandName;
                    orderItem.ItemCategory    = item.Brand.Category.CategoryName;
                    orderItem.ItemImageUrl    = item.Images.First().ImageUrl;
                    orderItem.Quantity        = item.ItemAvailableQnt;

                    // Checking whether the item is in cart or not
                    if (cartItems != null && cartItems.Count > 0)
                    {
                        var existing = cartItems.Where(w => w.ItemId == orderItem.ItemId).FirstOrDefault();
                        if (existing != null)
                        {
                            orderItem.InCartCount = existing.Quantity;
                        }
                    }

                    viewModel.Items.Add(orderItem);
                }
            }
            return(View(viewModel));
        }
Example #14
0
        public ActionResult Login(UserLogin login, string ReturnUrl = "/")
        {
            string message = "";

            using (FreshChoiceEntities dc = new FreshChoiceEntities())
            {
                var v = dc.Users.Where(a => a.UserEmail == login.UserEmail).FirstOrDefault();
                if (v != null)
                {
                    if (!v.IsEmailVerified)
                    {
                        ViewBag.Message = "Please verify your email first";
                        return(View());
                    }

                    if (string.Compare(Crypto.Hash(login.UserPassword), v.UserPassword) == 0)
                    {
                        int    timeout   = login.RememberMe ? 525600 : 20; // 525600 min = 1 year
                        var    ticket    = new FormsAuthenticationTicket(login.UserEmail, login.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);

                        Session["UserId"]   = v.UserId;
                        Session["UserName"] = v.UserName;
                        Session["UserRole"] = v.Role.RoleName;

                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    else
                    {
                        message = "Invalid credential provided";
                    }
                }
                else
                {
                    message = "Invalid credential provided";
                }
            }
            ViewBag.Message = message;
            return(View());
        }
Example #15
0
        public static CartHelper GetInstance(int UserId)
        {
            if (_instance == null)
            {
                _instance = new CartHelper(UserId);
            }

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                currentCart = db.Carts.Where(w => w.UserId == UserId && w.CartIsActive).FirstOrDefault();
            }

            return(_instance);
        }
Example #16
0
 public List <CartItem> GetCartItems()
 {
     using (FreshChoiceEntities db = new FreshChoiceEntities())
     {
         if (currentCart == null)
         {
             return(null);
         }
         else
         {
             return(db.CartItems.Where(w => w.CartId == currentCart.CartId).ToList());
         }
     }
 }
Example #17
0
 public bool DeleteCart()
 {
     if (currentCart == null)
     {
         return(false);
     }
     using (FreshChoiceEntities db = new FreshChoiceEntities()) {
         Cart cart = db.Carts.Where(w => w.CartId == currentCart.CartId).FirstOrDefault();
         cart.CartIsActive = false;
         db.SaveChanges();
         currentCart = null;
         return(true);
     }
 }
Example #18
0
        public List <OrderCartItem> RemoveItemFromCart(int ItemId, int Quantity = 1)
        {
            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                Item item = db.Items.Where(w => w.ItemId == ItemId).FirstOrDefault();
                if (item != null)
                {
                    if (currentCart == null)
                    {
                        return(null);
                    }

                    CartItem cartItem = db.CartItems
                                        .Where(w => w.CartId == currentCart.CartId && w.ItemId == ItemId)
                                        .FirstOrDefault();
                    if (cartItem != null)
                    {
                        if ((cartItem.CartItemQnt - Quantity) > 0)
                        {
                            // Normal reduce
                            cartItem.CartItemQnt       -= Quantity;
                            cartItem.CartItemTotalPrice = cartItem.CartItemQnt * item.ItemPrice;
                        }
                        else if ((cartItem.CartItemQnt - Quantity) == 0)
                        {
                            // Remove item from cart
                            db.CartItems.Remove(cartItem);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        return(null);
                    }
                    db.SaveChanges();
                    item.ItemAvailableQnt += Quantity;
                    db.SaveChanges();
                }
                else
                {
                    return(null);
                }

                // return new cart items
                return(GetOrderCartItems());
            }
        }
Example #19
0
        public ActionResult UpdateOrderStatus(int Id, int StatusOrder, DateTime NextDeadline)
        {
            try
            {
                using (FreshChoiceEntities db = new FreshChoiceEntities())
                {
                    Order order = db.Orders.Where(w => w.OrderId == Id).FirstOrDefault();
                    if (order != null)
                    {
                        if (StatusOrder == OrderProcessingStatus.COMPLETED)
                        {
                            // assign delivery person
                            var user = db.Users
                                       .Join(
                                db.Roles,
                                u => u.RoleId,
                                r => r.RoleId,
                                (u, r) => new { User = u, Role = r })
                                       .Where(w => w.Role.RoleId == RoleTypes.DELIVERY)
                                       .FirstOrDefault();
                            if (user != null)
                            {
                                Delivery delivery = db.Deliveries
                                                    .Where(w => w.DeliveryId == order.DeliveryId)
                                                    .FirstOrDefault();
                                delivery.UserId = user.User.UserId;
                                db.SaveChanges();
                            }
                            else
                            {
                                return(Json(false));
                            }
                        }

                        order.OrderStatusId = db
                                              .OrderStatus.Where(w => w.OrderStatusOrder == StatusOrder)
                                              .Select(s => s.OrderStatusId).FirstOrDefault();
                        order.OrderNextDeadline = NextDeadline;
                        order.OrderUpdatedDate  = DateTime.Now;
                        db.SaveChanges();

                        return(Json(true));
                    }
                }
            }
            catch (Exception)
            {
            }
            return(Json(false));
        }
Example #20
0
        public ActionResult Index()
        {
            DashBoardViewModel viewModel = new DashBoardViewModel();

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                var items = db.Orders
                            .Join(
                    db.Carts,
                    o => o.CartId,
                    c => c.CartId,
                    (o, c) => new { Order = o, Cart = c })
                            .Join(
                    db.CartItems,
                    oc => oc.Cart.CartId,
                    ci => ci.CartId,
                    (oc, ci) => new { OrderCart = oc, CartItem = ci }
                    )
                            .Join(
                    db.Items,
                    occi => occi.CartItem.ItemId,
                    i => i.ItemId,
                    (occi, i) => new { Item = i, CartItem = occi.CartItem }
                    ).ToList();
                viewModel.CategorySalesItems = new List <CategorySalesItem>();
                viewModel.TotalSales         = 0;
                foreach (var item in items)
                {
                    CategorySalesItem categorySalesItem = new CategorySalesItem();
                    categorySalesItem.CategoryName    = item.Item.Brand.Category.CategoryName;
                    categorySalesItem.TotalSalesValue = item.CartItem.CartItemTotalPrice;
                    viewModel.TotalSales += categorySalesItem.TotalSalesValue;
                    viewModel.CategorySalesItems.Add(categorySalesItem);
                }

                var cats = viewModel.CategorySalesItems.Select(s => s.CategoryName).Distinct().ToList();
                viewModel.DataJson = new List <double>();
                foreach (var cat in cats)
                {
                    double total    = 0;
                    var    catItems = viewModel.CategorySalesItems.Where(w => w.CategoryName == cat).ToList();
                    foreach (var i in catItems)
                    {
                        total += i.TotalSalesValue;
                    }
                    viewModel.DataJson.Add(total);
                }
            }
            return(View(viewModel));
        }
Example #21
0
        public ActionResult Address(int Id = 0)
        {
            if (Id == 0)
            {
                return(View(new Address()));
            }
            Address address = new Address();

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                address = db.Addresses.Where(w => w.AddressId == Id).FirstOrDefault();
            }
            return(View(address));
        }
Example #22
0
        public double GetDeliveryInKilometers()
        {
            double distance = 0;

            // calculate distance based on lat & lng
            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                Address address = db.Addresses.Where(w => w.UserId == currentUserId).FirstOrDefault();
                if (address != null)
                {
                    var userCoordinate = new GeoCoordinate(address.AddressLatitude, address.AddressLongitude);
                    var shopCoordinate = new GeoCoordinate(StoreLocation.STORE_LATITUDE, StoreLocation.STORE_LONGITUDE);

                    distance = userCoordinate.GetDistanceTo(shopCoordinate) / 1000;
                }
            }
            return(distance);
        }
Example #23
0
        public ActionResult MyOrders()
        {
            int userId = int.Parse(Convert.ToString(Session["UserId"]));
            MyProfileViewModel viewModel = new MyProfileViewModel();

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                viewModel.User   = db.Users.Where(w => w.UserId == userId).FirstOrDefault();
                viewModel.Wallet = db.Wallets.Where(w => w.UserId == userId).FirstOrDefault();
                if (viewModel.Wallet != null)
                {
                    viewModel.Transactions = db.Transactions.Where(w => w.WalletId == viewModel.Wallet.WalletId).ToList();
                }
                viewModel.Orders  = CartHelper.GetInstance(userId).GetAllOrderItems();
                viewModel.Address = db.Addresses.Where(w => w.UserId == userId).FirstOrDefault();
                viewModel.Orders  = viewModel.Orders.OrderByDescending(o => o.LastUpdate).ToList();
            }
            return(View(viewModel));
        }
Example #24
0
        public ActionResult Index()
        {
            int userId = int.Parse(Convert.ToString(Session["UserId"]));
            List <OrderCartItem> cartItems = CartHelper.GetInstance(userId).GetOrderCartItems();
            IndexViewModel       viewModel = new IndexViewModel();

            if (cartItems != null && cartItems.Count > 0)
            {
                viewModel.InCartCount = cartItems.Count;
            }
            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                var items = db.Items.ToList();
                viewModel.Items = new List <IndexItem>();
                foreach (var item in items)
                {
                    IndexItem orderItem = new IndexItem();
                    orderItem.ItemName        = item.ItemName;
                    orderItem.ItemDescription = item.ItemDescription;
                    orderItem.ItemId          = item.ItemId;
                    orderItem.ItemPrice       = item.ItemPrice;
                    orderItem.ItemBrand       = item.Brand.BrandName;
                    orderItem.ItemCategory    = item.Brand.Category.CategoryName;
                    orderItem.ItemImageUrl    = item.Images.First().ImageUrl;
                    orderItem.Quantity        = item.ItemAvailableQnt;

                    if (cartItems != null && cartItems.Count > 0)
                    {
                        var existing = cartItems.Where(w => w.ItemId == orderItem.ItemId).FirstOrDefault();
                        if (existing != null)
                        {
                            orderItem.InCartCount = existing.Quantity;
                        }
                    }

                    viewModel.Items.Add(orderItem);
                }
            }
            return(View(viewModel));
        }
Example #25
0
        public ActionResult DeleteItem(int Id)
        {
            bool result = false;

            try
            {
                using (FreshChoiceEntities db = new FreshChoiceEntities())
                {
                    Item item = db.Items.Where(w => w.ItemId == Id).FirstOrDefault();
                    if (item != null)
                    {
                        item.ItemIsDeleted = true;
                        db.SaveChanges();
                        result = true;
                    }
                }
            }
            catch (Exception)
            {
            }
            return(Json(result));
        }
Example #26
0
        public ActionResult VerifyAccount(string id)
        {
            bool Status = false;

            using (FreshChoiceEntities dc = new FreshChoiceEntities())
            {
                dc.Configuration.ValidateOnSaveEnabled = false; // This line I have added here to avoid
                                                                // Confirm password does not match issue on save changes
                var v = dc.Users.Where(a => a.ActivationCode == new Guid(id)).FirstOrDefault();
                if (v != null)
                {
                    v.IsEmailVerified = true;
                    dc.SaveChanges();
                    Status = true;
                }
                else
                {
                    ViewBag.Message = "Invalid Request";
                }
            }
            ViewBag.Status = Status;
            return(View());
        }
Example #27
0
        public ActionResult Address(Address address)
        {
            int userId = int.Parse(Convert.ToString(Session["UserId"]));

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                Address newAddress = new Address();
                if (address.AddressId != 0)
                {
                    newAddress = db.Addresses.Where(w => w.AddressId == address.AddressId).FirstOrDefault();
                }
                newAddress.UserId             = userId;
                newAddress.AddressName        = address.AddressName;
                newAddress.AddressDescription = address.AddressDescription;
                newAddress.AddressLatitude    = address.AddressLatitude;
                newAddress.AddressLongitude   = address.AddressLongitude;
                if (address.AddressId == 0)
                {
                    db.Addresses.Add(newAddress);
                }
                db.SaveChanges();
            }
            return(Redirect("/Cart"));
        }
Example #28
0
        public ActionResult SaveItem(EditItemViewModel viewModel)
        {
            bool result = false;

            try
            {
                using (FreshChoiceEntities db = new FreshChoiceEntities())
                {
                    //  Get all files from Request object
                    HttpFileCollectionBase files  = Request.Files;
                    List <Image>           images = new List <Image>();

                    // create Item
                    Item item = new Item();
                    if (viewModel.ItemId != 0)
                    {
                        item = db.Items.Where(w => w.ItemId == viewModel.ItemId).FirstOrDefault();
                    }

                    item.ItemName         = viewModel.ItemName;
                    item.ItemDescription  = viewModel.ItemDescription;
                    item.ItemAvailableQnt = viewModel.ItemAvailableQnt;
                    if (viewModel.ItemId == 0)
                    {
                        item.ItemQnt = viewModel.ItemAvailableQnt;
                    }
                    else
                    {
                        item.ItemQnt = (item.ItemQnt + (viewModel.ItemAvailableQnt - item.ItemAvailableQnt));
                    }
                    item.ItemPrice     = viewModel.ItemPrice;
                    item.ItemIsDeleted = false;
                    item.BrandId       = viewModel.ItemBrandId;
                    if (viewModel.ItemId == 0)
                    {
                        db.Items.Add(item);
                    }
                    db.SaveChanges();

                    int imageCount = db.Images.Where(w => w.ItemId == item.ItemId).Count();
                    if (Request.Files.Count > 0)
                    {
                        for (int i = 0; i < files.Count; i++)
                        {
                            HttpPostedFileBase file = files[i];
                            string             fname;

                            // Checking for Internet Explorer
                            if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                            {
                                string[] testfiles = file.FileName.Split(new char[] { '\\' });
                                fname = testfiles[testfiles.Length - 1];
                            }
                            else
                            {
                                fname = file.FileName;
                            }

                            string[] find      = fname.Split('.');
                            string   extention = find[find.Length - 1];
                            fname = item.ItemName + "_" + (i + imageCount) + "." + extention;

                            // Get the complete folder path and store the file inside it.
                            var finalName = Path.Combine(Server.MapPath("~/Uploads/"), fname);
                            file.SaveAs(finalName);

                            // Create image
                            Image image = new Image();
                            image.ImageDescription = "";
                            image.ImageUrl         = "/Uploads/" + fname;
                            image.ItemId           = item.ItemId;
                            db.Images.Add(image);
                            db.SaveChanges();
                        }
                    }
                    result = true;
                }
            }
            catch (Exception)
            {
            }

            return(Json(result));
        }
Example #29
0
        public Order PlaceOrder(string DeliveryType, bool UseWalletCash = false)
        {
            if (currentCart == null)
            {
                return(null);
            }
            List <CartItem> cartItems = GetCartItems();

            if (cartItems == null || cartItems.Count == 0)
            {
                return(null);
            }
            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                if (DeliveryType == DeliveryTypes.HOME_DELIVERY)
                {
                    Address address = db.Addresses.Where(w => w.UserId == currentUserId).FirstOrDefault();
                    if (address == null)
                    {
                        return(null);
                    }
                }
                // Set order status and delivery status
                OrderStatu orderStatus = db.OrderStatus.Where(w => w.OrderStatusOrder == OrderProcessingStatus.PLACED).FirstOrDefault();
                Delivery   delivery    = new Delivery();
                delivery.DeliveryType = DeliveryType;
                db.Deliveries.Add(delivery);
                db.SaveChanges();

                // create new order
                Order order = new Order();
                order.OrderDescription    = "New Order";
                order.OrderBillNo         = GenerateBillNo(DeliveryType);
                order.OrderConfirmationNo = GenerateConfirmationNo(DeliveryType);
                order.OrderUpdatedDate    = DateTime.Now;
                order.OrderNextDeadline   = DateTime.Now.AddHours(ORDER_PLACED_DEADLINE);
                order.DeliveryId          = delivery.DeliveryId;
                order.OrderStatusId       = orderStatus.OrderStatusId;
                order.CartId = currentCart.CartId;

                // calculate cart amount
                double total = 0;
                foreach (var cartItem in cartItems)
                {
                    total += cartItem.CartItemTotalPrice;
                }
                // calculate & Add delivery Fees
                double deliveryFee = 0;
                if (DeliveryType == DeliveryTypes.HOME_DELIVERY)
                {
                    Address address = db.Addresses.Where(w => w.UserId == currentUserId).FirstOrDefault();
                    if (address != null)
                    {
                        var userCoordinate = new GeoCoordinate(address.AddressLatitude, address.AddressLongitude);
                        var shopCoordinate = new GeoCoordinate(StoreLocation.STORE_LATITUDE, StoreLocation.STORE_LONGITUDE);

                        var distanceInKM = userCoordinate.GetDistanceTo(shopCoordinate) / 1000;
                        deliveryFee          = distanceInKM * 50;
                        delivery.DeliveryFee = deliveryFee;
                        db.SaveChanges();
                    }
                }

                order.OrderAmount = total + deliveryFee;
                order.UserId      = currentUserId;

                // if using wallet cash
                if (UseWalletCash)
                {
                    // add amount to user wallet
                    Wallet wallet = db.Wallets.Where(w => w.UserId == currentUserId).FirstOrDefault();

                    if (wallet == null || wallet.WalletTotal < order.OrderAmount)
                    {
                        return(null);
                    }

                    // create transaction
                    Transaction transaction = new Transaction();
                    transaction.TransactionDate        = DateTime.Now;
                    transaction.TransactionDescription = "cancel_order_" + order.OrderId;
                    transaction.TransactionAmount      = 0 - order.OrderAmount;
                    transaction.WalletId = wallet.WalletId;
                    db.Transactions.Add(transaction);
                    wallet.WalletTotal -= order.OrderAmount;
                    db.SaveChanges();
                }

                db.Orders.Add(order);
                db.SaveChanges();
                DeleteCart();
                return(order);
            }
        }
Example #30
0
        public List <AllOrderItem> GetAllOrderItems()
        {
            List <AllOrderItem> orders = new List <AllOrderItem>();

            using (FreshChoiceEntities db = new FreshChoiceEntities())
            {
                var newOrders = db.Orders
                                .Join(
                    db.OrderStatus,
                    o => o.OrderStatusId,
                    os => os.OrderStatusId,
                    (o, os) => new { order = o, orderStatus = os }
                    )
                                .Join(
                    db.Carts,
                    ows => ows.order.CartId,
                    c => c.CartId,
                    (ows, c) => new { order = ows.order, orderStatus = ows.orderStatus, cart = c }
                    )
                                .Where(w => w.order.UserId == currentUserId)
                                .OrderByDescending(o => o.order.OrderUpdatedDate)
                                .ToList();

                foreach (var order in newOrders)
                {
                    AllOrderItem orderItem = new AllOrderItem();
                    orderItem.OrderId        = order.order.OrderId;
                    orderItem.BillNo         = order.order.OrderBillNo;
                    orderItem.ConfirmationNo = order.order.OrderConfirmationNo;
                    orderItem.LastUpdate     = order.order.OrderUpdatedDate;
                    orderItem.NextDeadline   = order.order.OrderNextDeadline;
                    orderItem.OrderStatus    = order.orderStatus.OrderStatusDescription;
                    orderItem.OrderStatusId  = order.orderStatus.OrderStatusId;
                    orderItem.OrderAmount    = order.order.OrderAmount;

                    var items = db.CartItems
                                .Where(w => w.CartId == order.order.Cart.CartId)
                                .Join(db.Items,
                                      ci => ci.ItemId,
                                      i => i.ItemId,
                                      (ci, i) => new { cartItem = ci, item = i })
                                .ToList();

                    orderItem.Items = new List <OrderCartItem>();
                    foreach (var item in items)
                    {
                        OrderCartItem cartItem = new OrderCartItem();
                        cartItem.ItemId    = item.item.ItemId;
                        cartItem.Quantity  = item.cartItem.CartItemQnt;
                        cartItem.ItemName  = item.item.ItemName;
                        cartItem.ItemPrice = item.item.ItemPrice;

                        var image = db.Images.Where(w => w.ItemId == item.item.ItemId).FirstOrDefault();
                        if (image != null)
                        {
                            cartItem.ItemImageUrl = image.ImageUrl;
                        }
                        orderItem.Items.Add(cartItem);
                    }

                    orders.Add(orderItem);
                }
            }
            return(orders);
        }