Ejemplo n.º 1
0
 public int ChangePassword(FormCollection f)
 {
     try
     {
         AccountBusiness ab = new AccountBusiness();
         int cusUserId = Convert.ToInt32(Session["UserId"]);
         string sOldPass = f["txtOldPass"];
         string sNewPass = f["txtNewPass"];
         string sNewPassConfirm = f["txtNewPassConfirm"];
         if (!ab.checkPass(cusUserId, sOldPass))
         {
             return -1;
         }
         if (sOldPass == sNewPass)
         {
             return -2;
         }
         if (sNewPass != sNewPassConfirm)
         {
             return -3;
         }
         ab.ChangePassword(cusUserId, sNewPass);
         return 1;
     }
     catch
     {
         return -4;
     }
 }
Ejemplo n.º 2
0
        protected void Page_Load()
        {
            AccountBusiness ab = new AccountBusiness();
            if (Context.Session != null)
            {
                if (Session.IsNewSession)
                {

                }
            }
        }
Ejemplo n.º 3
0
 public int CreateNewPassword(FormCollection f)
 {
     try
     {
         AccountBusiness ab = new AccountBusiness();
         int userId = Convert.ToInt32(f["userId"]);
         string newPassword = f["txtPass"];
         ab.ChangePassword(userId, newPassword);
         return 1;
     }
     catch
     {
         return -1;
     }
 }
Ejemplo n.º 4
0
        public ActionResult CreateNewPassword(string strUserId, DateTime timeSend)
        {
            try
            {
                DateTime activeTimeCheck = DateTime.Now;
                AccountBusiness ab = new AccountBusiness();
                int userId = 0;
                string salt = strUserId.Substring(strUserId.Length - 88);
                List<User> lstUser = db.Users.ToList();
                foreach (var item in lstUser)
                {
                    if (ab.CreateIdHash(item.UserId, salt) == strUserId)
                    {
                        userId = item.UserId;
                    }
                }
                double check = (activeTimeCheck - timeSend).TotalMinutes;
                if (check > 1440)
                {
                    ViewBag.outOfTime = "";
                }

                if (userId != 0)
                {
                    ViewBag.userId = userId;
                    return View();
                }
                else
                {
                    return RedirectToAction("Index", "Error");
                }
            }
            catch
            {
                return RedirectToAction("Index", "Error");
            }
        }
Ejemplo n.º 5
0
 public int EditInformation(FormCollection f)
 {
     try
     {
         AccountBusiness ab = new AccountBusiness();
         int userId = Convert.ToInt32(Session["UserId"]);
         string sName = f["customerName"];
         string sEmail = f["customerEmail"];
         if ((int)Session["UserRole"] == 1)
         {
             if (ab.checkEmailExisted(userId, sEmail))
             {
                 return -1;
             }
             ab.ChangeInformation(userId, sName, sEmail, null,null,null);
         }
         if ((int)Session["UserRole"] == 2)
         {
             if (ab.checkEmailExisted(userId, sEmail))
             {
                 return -1;
             }
             string sAddress = f["customerAddress"];
             string sPhone = f["customerPhoneNumber"];
             if (ab.checkPhoneExisted(userId, sPhone))
             {
                 return -2;
             }
             ab.ChangeInformation(userId, sName, sEmail, sAddress, null, sPhone);
         }
         return 1;
     }
     catch
     {
         return -3;
     }
 }
Ejemplo n.º 6
0
 //For customer after enter information
 public int LoginOrderProduct(FormCollection f)
 {
     try
     {
         AccountBusiness ab = new AccountBusiness();
         CustomerOrderBusiness cob = new CustomerOrderBusiness();
         if (Session["Cart"] == null)
         {
             return -4;
         }
         List<CustomerCartViewModel> cart = GetCart();
         string orderTime = DateTime.Now.ToString("yyyyMMdd");
         int amount = Convert.ToInt32(Session["Amount"]);
         int taxAmount = Convert.ToInt32(Session["TaxAmount"]);
         int discount = Convert.ToInt32(Session["DiscountAmount"]);
         string sAccount = f.Get("txtAccount").ToString();
         string sPassword = f.Get("txtPassword").ToString();
         User endUser = ab.checkLogin(sAccount, sPassword);
         if (endUser != null)
         {
             int checkRole = endUser.RoleId;
             if (checkRole != 3)
             {
                 TempData["Notify"] = "Tài khoản không hợp lệ";
                 return -2;
             }
             Session["User"] = endUser;
             Session["UserId"] = endUser.UserId;
             Session["CusUserId"] = endUser.Customers.ElementAt(0).CustomerId;
             TempData["userName"] = endUser.Username.ToString();
             Session["Phonenumber"] = endUser.Customers.ElementAt(0).CustomerPhoneNumber.ToString();
         }
         else
         {
             TempData["Notify"] = "Sai tài khoản hoặc mật khẩu";
             return -3;
         }
         int cusUserId = Convert.ToInt32(Session["UserId"]);
         DateTime planDeliveryDate = DateTime.ParseExact(Session["DeliveryDate"].ToString(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
         string Note = Session["Note"].ToString();
         cob.OrderProduct(orderTime, planDeliveryDate, amount, taxAmount, discount, cusUserId, cart, Note);
         TempData["orderCode"] = cob.GetOrderCode();
         Session["Cart"] = null;
         Session["Amount"] = null;
         Session["TaxAmount"] = null;
         Session["DiscountAmount"] = null;
         Session["Note"] = null;
         return 1;
     }
     catch
     {
         return -5;
     }
 }
Ejemplo n.º 7
0
        public int AddStaff(FormCollection f)
        {
            try
            {
                AccountBusiness ab = new AccountBusiness();
                User staffUser = Session["User"] as User;
                if (staffUser == null || Session["UserRole"] == null || (int)Session["UserRole"] != 1)
                {
                    return -7;
                }
                else
                {
                    String staffName = f["txtStaffName"];
                    String staffUserAccount = f["txtStaffUserAccount"];
                    String staffPhoneNumber = f["txtStaffPhoneNumber"];
                    String staffEmail = f["txtStaffEmail"];
                    String staffAddress = f["txtStaffAddress"];
                    Staff staff = new Staff();
                    User user = new User();

                    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                    var stringChars = new char[6];
                    var random = new Random();
                    for (int i = 0; i < stringChars.Length; i++)
                    {
                        stringChars[i] = chars[random.Next(chars.Length)];
                    }
                    var finalString = new String(stringChars);

                    try
                    {
                        user.Fullname = staffName;
                        user.Username = staffUserAccount;
                        user.Email = staffEmail;
                        user.RoleId = 3;
                        user.Password = ab.CreateStaffPassword(finalString);
                        staff.StaffPhoneNumber = staffPhoneNumber;
                        staff.StaffAddress = staffAddress;
                        staff.IsActive = true;

                        staff.User = user;

                        string password = "******";
                        string from = "*****@*****.**";
                        string to = staffEmail;

                        MailMessage mail = new MailMessage();
                        mail.IsBodyHtml = true;
                        mail.To.Add(to);
                        mail.From = new MailAddress(from);
                        mail.Subject = string.Format("{0}{1}", "Tạo tài khoản cho nhân viên ", staffName);
                        mail.Body += "<html lang='vi'>";
                        mail.Body += "<head>";
                        mail.Body += "<meta charset='utf-8'>";
                        mail.Body += "</head>";
                        mail.Body += "<body>";
                        mail.Body += "<div> Bạn vừa được tạo tài khoản tại Tiệm Bánh Dâu Tây</div>";
                        mail.Body += string.Format("{0}{1}", "Tên tài khoản: ", staffUserAccount);
                        mail.Body += "<div></div>";
                        mail.Body += string.Format("{0}{1}", "Mật khẩu: ", finalString);
                        mail.Body += "</body>";
                        mail.Body += "</html>";
                        var mailBody = mail.Body;
                        var htmlBody = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
                        mail.AlternateViews.Add(htmlBody);

                        mail.Priority = MailPriority.High;
                        SmtpClient smtp = new SmtpClient();
                        smtp.UseDefaultCredentials = false;
                        smtp.Credentials = new System.Net.NetworkCredential(from, password);
                        smtp.Port = 587;
                        smtp.Host = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        smtp.Send(mail);

                    }
                    catch (Exception)
                    {
                        return 0;

                    }

                    bool result = StaffBusiness.AddStaff(staff);
                    if (result)
                    {
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }
                }
            }
            catch (Exception)
            {
                return 0;
            }
        }
Ejemplo n.º 8
0
 // GET: Manage
 public ActionResult Index(int userId)
 {
     try
     {
         if (Session["User"] == null || Session["UserRole"] == null)
         {
             return RedirectToAction("Index", "Home");
         }
         if ((int)Session["UserId"] != userId)
         {
             return RedirectToAction("Index", "StoreInfor");
         }
         AccountBusiness ab = new AccountBusiness();
         var user = ab.GetUser(userId);
         return View(user);
     }
     catch
     {
         return RedirectToAction("ManageError", "Error");
     }
 }
Ejemplo n.º 9
0
 public ActionResult Index()
 {
     try
     {
         if (Session["User"] == null || Session["UserRole"] == null)
         {
             return RedirectToAction("Index", "Home");
         }
         ViewBag.TreeView = "storeInfor";
         ViewBag.TreeViewMenu = "storeInforList";
         AccountBusiness ab = new AccountBusiness();
         StoreInfo storeInfo = db.StoreInfoes.SingleOrDefault();
         List<Product> lstNewProduct = db.Products.OrderByDescending(n => n.ProductId).Take(4).ToList();
         ViewBag.lstProduct = lstNewProduct;
         List<Order> lstOrder = db.Orders.Where(n => n.OrderStatus == 0).ToList();
         ViewBag.orderWaiting = lstOrder.Count;
         List<Customer> lstCustomer = db.Customers.ToList();
         ViewBag.customer = lstCustomer.Count;
         List<ProductMaterial> lstLowQuantity = ab.StaffOffLowQuantityNoty();
         ViewBag.lowQuantity = lstLowQuantity.Count;
         return View(storeInfo);
     }
     catch
     {
         return RedirectToAction("ManageError", "Error");
     }
 }
Ejemplo n.º 10
0
        public int ApproveOrder(int orderId, int deposit, DateTime deliveryTime, int staffUserId, CustomerViewModel newCustomer)
        {
            OrderViewModel orderViewModel = GetOrderViewModel(orderId);
            if (orderViewModel.Order.CustomerEditingFlag)
            {
                return -1;
            }
            if (orderViewModel == null)
            {
                return -2;
            }
            if (orderViewModel.Order.OrderStatus != 0)
            {
                return -3;
            }
            if (!orderViewModel.IsEnoughMaterial)
            {
                return -4;
            }
            DbContextTransaction contextTransaction = db.Database.BeginTransaction();
            DateTime now = DateTime.Now;
            #region Update OutputMaterial; ExportFrom and InputMaterial
            foreach (OrderItem orderItem in orderViewModel.Order.OrderItems)
            {
                List<MaterialViewModel> materialListForOrderItem =
                    GetMaterialListForOrderItem(orderItem.Product.ProductId, orderItem.Quantity);
                foreach (MaterialViewModel materialViewModel in materialListForOrderItem)
                {
                    OutputMaterial outputMaterial = new OutputMaterial();
                    outputMaterial.ExportQuantity = materialViewModel.NeedQuantity;
                    outputMaterial.ProductMaterialId = materialViewModel.ProductMaterialId;
                    outputMaterial.ExportTime = now;
                    outputMaterial.OrderItemId = orderItem.OrderItemId;
                    //Get list of InputMaterial available order by ExpireDate descending
                    List<InputMaterial> tempList = db.InputMaterials.Where(
                        m => m.ProductMaterialId == materialViewModel.ProductMaterialId && m.IsActive && m.RemainQuantity > 0).OrderByDescending(m => m.InputMaterialExpiryDate).ToList();
                    //Compare each input material with material ViewModel and merge each material of orderItem to input material
                    foreach (InputMaterial inputMaterial in tempList)
                    {
                        if (materialViewModel.NeedQuantity > 0)
                        {
                            ExportFrom exportFrom = new ExportFrom();
                            if (inputMaterial.RemainQuantity >= materialViewModel.NeedQuantity)
                            {
                                exportFrom.ExportFromQuantity = materialViewModel.NeedQuantity;
                                inputMaterial.RemainQuantity -= materialViewModel.NeedQuantity;
                                materialViewModel.NeedQuantity = 0;

                            }
                            else
                            {
                                materialViewModel.NeedQuantity -= inputMaterial.RemainQuantity;
                                exportFrom.ExportFromQuantity = inputMaterial.RemainQuantity;
                                inputMaterial.RemainQuantity = 0;
                            }
                            InputBill inputBill = inputMaterial.InputBill;
                            // Get info for ExportFrom
                            exportFrom.InputBill = inputBill;
                            // Add input bill to output material
                            outputMaterial.ExportFroms.Add(exportFrom);
                        }
                    }
                    if (materialViewModel.NeedQuantity > 0)
                    {
                        contextTransaction.Rollback();
                        return -6;
                    }
                    db.OutputMaterials.Add(outputMaterial);
                    db.SaveChanges();
                }
            }
            #endregion
            #region Update ProductMaterial

            foreach (MaterialViewModel materialViewModel in orderViewModel.MaterialList)
            {
                //Update currentQuantity of product material
                ProductMaterial productMaterial =
                    db.ProductMaterials.FirstOrDefault(m => m.ProductMaterialId == materialViewModel.ProductMaterialId);
                if (productMaterial == null)
                {
                    contextTransaction.Rollback();
                    return 0;
                }
                productMaterial.CurrentQuantity -= materialViewModel.NeedQuantity;
                if (productMaterial.CurrentQuantity < 0)
                {
                    contextTransaction.Rollback();
                    return -6;
                }
                db.SaveChanges();
            }
            #endregion
            #region UpdateOrder

            Order order = db.Orders.FirstOrDefault(m => m.OrderId == orderViewModel.Order.OrderId);
            if (order == null)
            {
                contextTransaction.Rollback();
                return -2;
            }
            order.OrderStatus = 2;
            order.PlanDeliveryTime = deliveryTime;
            order.ApproveTime = now;
            order.DepositAmount = deposit;
            order.StaffApproveUserId = staffUserId;

            if (newCustomer != null)
            {
                Customer customer = new Customer
                {
                    CustomerAddress = newCustomer.CustomerAddress,
                    CustomerPhoneNumber = newCustomer.CustomerPhoneNumber,
                    TaxCode = newCustomer.CustomerTaxCode,
                    IsActive = true,
                    IsLoyal = false
                };
                List<Customer> customers = new List<Customer> { customer };
                AccountBusiness accountBusiness = new AccountBusiness();
                // Generate random password
                string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                var stringChars = new char[6];
                var random = new Random();
                for (int i = 0; i < stringChars.Length; i++)
                {
                    stringChars[i] = chars[random.Next(chars.Length)];
                }
                string password = new String(stringChars);

                User user = new User
                {
                    Fullname = newCustomer.CustomerName,
                    Email = newCustomer.CustomerEmail,
                    Username = newCustomer.Username,

                    Password = accountBusiness.CreatePassword(password)
                };

                Role role = db.Roles.FirstOrDefault(m => m.Name.Equals("Customer"));
                user.Role = role;
                user.Customers = customers;

                order.User = user;

                // Remove Guest Info
                GuestInfo guestInfo = order.GuestInfo;
                if (guestInfo != null)
                {
                    order.GuestInfo = null;
                    db.GuestInfoes.Remove(guestInfo);
                }

                // Send Email
                string passwordStore = "Tiembanhdautay";
                string from = "*****@*****.**";
                string to = user.Email;

                MailMessage mail = new MailMessage();
                mail.IsBodyHtml = true;
                mail.To.Add(to);
                mail.From = new MailAddress(from);
                mail.Subject = string.Format("{0}{1}", "Tạo tài khoản cho khách hàng ", user.Fullname);
                mail.Body += "<html lang='vi'>";
                mail.Body += "<head>";
                mail.Body += "<meta charset='utf-8'>";
                mail.Body += "</head>";
                mail.Body += "<body>";
                mail.Body += "<div> Bạn vừa được tạo tài khoản tại Tiệm Bánh Dâu Tây</div>";
                mail.Body += string.Format("{0}{1}", "Tên tài khoản: ", user.Username);
                mail.Body += "<div></div>";
                mail.Body += string.Format("{0}{1}", "Mật khẩu: ", password);
                mail.Body += "</body>";
                mail.Body += "</html>";
                var mailBody = mail.Body;
                var htmlBody = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
                mail.AlternateViews.Add(htmlBody);

                mail.Priority = MailPriority.High;
                SmtpClient smtp = new SmtpClient();
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(from, passwordStore);
                smtp.Port = 587;
                smtp.Host = "smtp.gmail.com";
                smtp.EnableSsl = true;
                try
                {
                    smtp.Send(mail);
                }
                catch (Exception e)
                {
                    contextTransaction.Rollback();
                    return -5;
                }
            }

            try
            {
                db.SaveChanges();
            }
            catch (Exception)
            {
                return 0;
            }

            #endregion

            try
            {
                contextTransaction.Commit();
            }
            catch (Exception)
            {
                contextTransaction.Rollback();
                return 0;
            }
            finally
            {
                contextTransaction.Dispose();
            }


            return 1;
        }
Ejemplo n.º 11
0
        public int GetPassword(FormCollection f)
        {
            try
            {
                AccountBusiness ab = new AccountBusiness();
                string username = f["txtUsername"].ToString();
                List<User> lstUser = db.Users.ToList();
                for (int i = 0; i < lstUser.Count; i++)
                {
                    if (lstUser[i].Username == username)
                    {
                        try
                        {
                            string password = "******";
                            string from = "*****@*****.**";
                            string to = lstUser[i].Email;

                            MailMessage mail = new MailMessage();
                            mail.IsBodyHtml = true;
                            mail.To.Add(to);
                            mail.From = new MailAddress(from);
                            mail.Subject = string.Format("{0}{1}", "Tạo mật khẩu mới cho khách hàng ", lstUser[i].Fullname);
                            mail.Body += "<html lang='vi'>";
                            mail.Body += "<head>";
                            mail.Body += "<meta charset='utf-8'>";
                            mail.Body += "</head>";
                            mail.Body += "<body>";
                            mail.Body += "<div> Quý khách vừa gởi yêu cầu tạo mật khẩu mới bằng Email này ?</div>";
                            mail.Body += "<div> Nếu phải, vui lòng bấm vào 'Tạo mới mật khẩu' bên dưới, đường dẫn chỉ có hiệu lực trong vòng 24 tiếng kể từ khi quý khách nhận được email này</div>";
                            //string link = Url.Encode(string.Format("{0}{1}", Request.Url.Authority, Url.Action("CreateNewPassword", "Account", new { userId = lstUser[i].UserId, timeSend = DateTime.Now })));
                            //mail.Body += string.Format("<a href='{0}{1}'>Tạo mới mật khẩu</a>", "http://", link);
                            mail.Body += string.Format("<a href='{0}{1}{2}'>Tạo mới mật khẩu</a>", "http://", Request.Url.Authority, Url.Action("CreateNewPassword", "Account", new { strUserId = ab.EncodeUserId(lstUser[i].UserId), timeSend = DateTime.Now }));
                            mail.Body += "</body>";
                            mail.Body += "</html>";
                            var mailBody = mail.Body;
                            var htmlBody = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
                            mail.AlternateViews.Add(htmlBody);

                            mail.Priority = MailPriority.High;
                            SmtpClient smtp = new SmtpClient();
                            smtp.UseDefaultCredentials = false;
                            smtp.Credentials = new System.Net.NetworkCredential(from, password);
                            smtp.Port = 587;
                            smtp.Host = "smtp.gmail.com";
                            smtp.EnableSsl = true;
                            smtp.Send(mail);
                            return 1;
                        }
                        catch
                        {
                            return -2;
                        }
                    }
                }
                return -1;
            }
            catch (Exception)
            {
                return -1;
            }
        }
Ejemplo n.º 12
0
        public ActionResult ConfigIndex()
        {
            try
            {
                if (Session["User"] == null || Session["UserRole"] == null)
                {
                    return RedirectToAction("Index", "Home");
                }
                if ((int)Session["UserRole"] == 2)
                {
                    return RedirectToAction("Index");
                }
                ViewBag.TreeView = "storeInfor";
                ViewBag.TreeViewMenu = "configStoreInfor";
                AccountBusiness ab = new AccountBusiness();
                List<Product> lstNewProduct = db.Products.OrderBy(n => n.ProductId).Take(4).ToList();
                ViewBag.lstProduct = lstNewProduct;
                List<Order> lstOrder = db.Orders.Where(n => n.OrderStatus == 0).ToList();
                ViewBag.orderWaiting = lstOrder.Count;
                List<Customer> lstCustomer = db.Customers.ToList();
                ViewBag.customer = lstCustomer.Count;
                List<ProductMaterial> lstLowQuantity = ab.StaffOffLowQuantityNoty();
                ViewBag.lowQuantity = lstLowQuantity.Count;

                Policy policy = db.Policies.SingleOrDefault(n => n.PolicyId == 1);
                ViewBag.minQuantity = policy;
                Policy policy2 = db.Policies.SingleOrDefault(n => n.PolicyId == 2);
                ViewBag.maxPrice = policy2;
                List<DiscountByQuantity> discountByQuantity = db.DiscountByQuantities.ToList();
                ViewBag.discountByQuantity = discountByQuantity;
                var quantityFrom = db.DiscountByQuantities.Select(n => n.QuantityFrom).ToList();
                var quantityTo = db.DiscountByQuantities.Select(n => n.QuantityTo).ToList();
                var discountRate = db.DiscountByQuantities.Select(n => n.DiscountValue).ToList();
                ViewBag.QuantityFrom = quantityFrom;
                ViewBag.quantityTo = quantityTo;
                ViewBag.DiscountValue = discountRate;
                List<Category> category = db.Categories.Where(n => n.CategoryName != "Bánh").ToList();
                ViewBag.category = category;
                return View();
            }
            catch
            {
                return RedirectToAction("ManageError", "Error");
            }
        }
Ejemplo n.º 13
0
 public ActionResult Logout()
 {
     try
     {
         AccountBusiness ab = new AccountBusiness();
         if (Session["CusUserId"] != null)
         {
             MvcApplication.changeStatusNotifer.Dispose();
             ab.SetLogoutTime((int)Session["UserId"]);
         }
         if (Session["UserRole"] != null)
         {
             if ((int)Session["UserRole"] == 2)
             {
                 ab.SetLogoutTime((int)Session["UserId"]);
             }
         }
         Session["User"] = null;
         Session["BeEdited"] = null;
         Session.Clear();
         return RedirectToAction("Index", "Home");
     }
     catch
     {
         return RedirectToAction("Index", "Error");
     }
 }
Ejemplo n.º 14
0
        public int Login(FormCollection f, string strURL)
        {
            AccountBusiness ab = new AccountBusiness();
            try
            {
                string sAccount = f.Get("txtAccount");
                string sPassword = f.Get("txtPassword");
                User endUser = ab.checkLogin(sAccount, sPassword);
                if (endUser == null)
                {
                    return -1;
                }
                if (!endUser.IsConfirmed)
                {
                    ab.ConfirmAccount(endUser.UserId);
                }
                if (endUser.RoleId == 3)
                {
                    if (!endUser.Customers.ElementAt(0).IsActive)
                    {
                        return -2;
                    }
                    Session["User"] = endUser;
                    Session["UserId"] = endUser.UserId;
                    Session["CusUserId"] = endUser.Customers.ElementAt(0).CustomerId;
                    Session["Phonenumber"] = endUser.Customers.ElementAt(0).CustomerPhoneNumber;

                    //Check customer off notifier
                    List<Order> lstNewOrderNoty = ab.CustomerOffNewOrderNoty((int)Session["UserId"]);
                    List<Order> lstEditedOrderNoty = ab.CustomerOffEditedOrderNoty((int)Session["UserId"]);
                    List<Order> lstConfirmOrderNoty = ab.CustomerOffConfirmOrderNoty((int)Session["UserId"]);
                    if (lstNewOrderNoty != null)
                    {
                        Session["CusNewOrderCountPartial"] = Session["CusNotificateCount"] = lstNewOrderNoty.Count;
                        if (lstEditedOrderNoty != null)
                        {
                            Session["CusEditOrderCountPartial"] = lstEditedOrderNoty.Count;
                            Session["CusNotificateCount"] = lstNewOrderNoty.Count + lstEditedOrderNoty.Count;
                            if (lstConfirmOrderNoty != null)
                            {
                                Session["CusConfirmOrderCountPartial"] = lstConfirmOrderNoty.Count;
                                Session["CusNotificateCount"] = lstNewOrderNoty.Count + lstEditedOrderNoty.Count + lstConfirmOrderNoty.Count;
                            }
                        }
                        else
                        {
                            if (lstConfirmOrderNoty != null)
                            {
                                Session["CusConfirmOrderCountPartial"] = lstConfirmOrderNoty.Count;
                                Session["CusNotificateCount"] = lstNewOrderNoty.Count + lstConfirmOrderNoty.Count;
                            }
                        }
                    }
                    else
                    {
                        if (lstEditedOrderNoty != null)
                        {
                            Session["CusEditOrderCountPartial"] = Session["CusNotificateCount"] = lstEditedOrderNoty.Count;
                            if (lstConfirmOrderNoty != null)
                            {
                                Session["CusConfirmOrderCountPartial"] = lstConfirmOrderNoty.Count;
                                Session["CusNotificateCount"] = lstEditedOrderNoty.Count + lstConfirmOrderNoty.Count;
                            }
                        }
                        else
                        {
                            if (lstConfirmOrderNoty != null)
                            {
                                Session["CusConfirmOrderCountPartial"] = Session["CusNotificateCount"] = lstConfirmOrderNoty.Count;
                            }
                        }
                    }

                    //Open connection with this Customer
                    string dependencyCheckSql = string.Format("{0}{1}", "SELECT OrderStatus FROM dbo.[Orders] WHERE CustomerUserId=", endUser.UserId);
                    Session["CheckToNotify"] = endUser.UserId;
                    MvcApplication.changeStatusNotifer.Start("BMAChangeDB", dependencyCheckSql);
                    MvcApplication.changeStatusNotifer.Change += this.OnChange3;
                    return 1;
                }
                else
                {
                    if (endUser.RoleId == 2)
                    {
                        if (!endUser.Staffs.ElementAt(0).IsActive)
                        {
                            return -2;
                        }

                        MvcApplication.notifier.Dispose();
                        MvcApplication.notifier.Start("BMAChangeDB", "SELECT OrderId FROM dbo.[Orders]");
                        MvcApplication.notifier.Change += this.OnChange;

                        MvcApplication.lowQuantityNotifer.Dispose();
                        MvcApplication.lowQuantityNotifer.Start("BMAChangeDB", "SELECT ProductMaterialId,CurrentQuantity,StandardQuantity FROM dbo.[ProductMaterial] WHERE (CurrentQuantity < StandardQuantity AND IsActive = 'True')");
                        MvcApplication.lowQuantityNotifer.Change += this.OnChange2;

                        //Check staff off notifier
                        List<Order> lstNewOrderNoty = ab.StaffOffNewOrderNoty();
                        List<Order> lstConfirmOrderNoty = ab.StaffOffConfirmOrderNoty();
                        List<Order> lstCancelOrderNoty = ab.StaffOffCancelOrderNoty();
                        List<ProductMaterial> lstLowQuantityNoty = ab.StaffOffLowQuantityNoty();

                        if (lstNewOrderNoty != null)
                        {
                            Session["NewOrderCountPartial"] = Session["NotificateCount"] = lstNewOrderNoty.Count;
                            if (lstConfirmOrderNoty != null)
                            {
                                Session["ConfirmOrderCountPartial"] = lstConfirmOrderNoty.Count;
                                Session["NotificateCount"] = lstConfirmOrderNoty.Count + lstNewOrderNoty.Count;
                                if (lstCancelOrderNoty != null)
                                {
                                    Session["CancelOrderCountPartial"] = lstCancelOrderNoty.Count;
                                    Session["NotificateCount"] = lstCancelOrderNoty.Count + lstConfirmOrderNoty.Count + lstNewOrderNoty.Count;
                                    if (lstLowQuantityNoty != null)
                                    {
                                        Session["LowMaterialCountPartial"] = lstLowQuantityNoty.Count;
                                        Session["NotificateCount"] = lstLowQuantityNoty.Count + lstCancelOrderNoty.Count + lstConfirmOrderNoty.Count + lstNewOrderNoty.Count;
                                    }
                                }
                                else
                                {
                                    if (lstLowQuantityNoty != null)
                                    {
                                        Session["LowMaterialCountPartial"] = lstLowQuantityNoty.Count;
                                        Session["NotificateCount"] = lstLowQuantityNoty.Count + lstConfirmOrderNoty.Count + lstNewOrderNoty.Count;
                                    }
                                }
                            }
                            else
                            {
                                if (lstCancelOrderNoty != null)
                                {
                                    Session["CancelOrderCountPartial"] = lstCancelOrderNoty.Count;
                                    Session["NotificateCount"] = lstCancelOrderNoty.Count + lstNewOrderNoty.Count;
                                    if (lstLowQuantityNoty != null)
                                    {
                                        Session["LowMaterialCountPartial"] = lstLowQuantityNoty.Count;
                                        Session["NotificateCount"] = lstLowQuantityNoty.Count + lstCancelOrderNoty.Count + lstNewOrderNoty.Count;
                                    }
                                }
                                else
                                {
                                    if (lstLowQuantityNoty != null)
                                    {
                                        Session["LowMaterialCountPartial"] = lstLowQuantityNoty.Count;
                                        Session["NotificateCount"] = lstLowQuantityNoty.Count + lstNewOrderNoty.Count;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (lstConfirmOrderNoty != null)
                            {
                                Session["ConfirmOrderCountPartial"] = Session["NotificateCount"] = lstConfirmOrderNoty.Count;
                                if (lstCancelOrderNoty != null)
                                {
                                    Session["CancelOrderCountPartial"] = lstCancelOrderNoty.Count;
                                    Session["NotificateCount"] = lstCancelOrderNoty.Count + lstConfirmOrderNoty.Count;
                                    if (lstLowQuantityNoty != null)
                                    {
                                        Session["LowMaterialCountPartial"] = lstLowQuantityNoty.Count;
                                        Session["NotificateCount"] = lstLowQuantityNoty.Count + lstCancelOrderNoty.Count + lstConfirmOrderNoty.Count;
                                    }
                                }
                                else
                                {
                                    if (lstLowQuantityNoty != null)
                                    {
                                        Session["LowMaterialCountPartial"] = lstLowQuantityNoty.Count;
                                        Session["NotificateCount"] = lstLowQuantityNoty.Count + lstConfirmOrderNoty.Count;
                                    }
                                }
                            }
                            else
                            {
                                if (lstCancelOrderNoty != null)
                                {
                                    Session["CancelOrderCountPartial"] = Session["NotificateCount"] = lstCancelOrderNoty.Count;
                                    if (lstLowQuantityNoty != null)
                                    {
                                        Session["LowMaterialCountPartial"] = lstLowQuantityNoty.Count;
                                        Session["NotificateCount"] = lstLowQuantityNoty.Count + lstCancelOrderNoty.Count;
                                    }
                                }
                                else
                                {
                                    if (lstLowQuantityNoty != null)
                                    {
                                        Session["LowMaterialCountPartial"] = Session["NotificateCount"] = lstLowQuantityNoty.Count;
                                    }
                                }
                            }
                        }

                    }
                    Session["User"] = endUser;
                    Session["UserId"] = endUser.UserId;
                    Session["UserRole"] = endUser.Role.RoleId;
                    return 2;
                }
            }
            catch
            {
                return -1;
            }
        }
Ejemplo n.º 15
0
 public int ChangePasswordConfirm(FormCollection f)
 {
     try
     {
         AccountBusiness ab = new AccountBusiness();
         int cusUserId = Convert.ToInt32(Session["UserId"]);
         string sOldPass = f["txtOldPass"];
         string sNewPass = f["txtNewPass"];
         string sNewPassConfirm = f["txtNewPassConfirm"];
         if (!ab.checkPass(cusUserId, sOldPass))
         {
             TempData["checkOldPass"] = "******";
             return -1;
         }
         if (sOldPass == sNewPass)
         {
             TempData["checkUnchange"] = "Mật khẩu mới và mật khẩu cũ giống nhau! Vui lòng thử lại.";
             return -2;
         }
         if (sNewPass != sNewPassConfirm)
         {
             TempData["checkConfirmPass"] = "******";
             return -3;
         }
         ab.ChangePassword(cusUserId, sNewPass);
         return 1;
     }
     catch
     {
         return -4;
     }
 }
Ejemplo n.º 16
0
 public ActionResult ChangePassword(int UserId)
 {
     try
     {
         AccountBusiness ab = new AccountBusiness();
         if (Session["User"] == null || ((int)Session["UserId"] != UserId))
         {
             return RedirectToAction("Index", "Home");
         }
         var user = ab.GetUser(UserId);
         return View(user);
     }
     catch
     {
         return RedirectToAction("Index", "Error");
     }
 }
Ejemplo n.º 17
0
 public int ChangeInformationConfirm(FormCollection f)
 {
     try
     {
         AccountBusiness ab = new AccountBusiness();
         int cusUserId = Convert.ToInt32(Session["UserId"]);
         string sName = f["txtName"];
         string sAddress = f["txtAdress"];
         string sEmail = f["txtEmail"];
         string sTaxCode = f["txtTaxCode"];
         string sPhone = f["txtPhone"];
         if (ab.checkEmailExisted(cusUserId, sEmail))
         {
             return -1;
         }
         if (ab.checkPhoneExisted(cusUserId, sPhone))
         {
             return -2;
         }
         if (ab.checkTaxCodeExisted(cusUserId, sTaxCode))
         {
             return -3;
         }
         ab.ChangeInformation(cusUserId, sName, sEmail, sAddress, sTaxCode, sPhone);
         return 1;
     }
     catch
     {
         return -4;
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Add new order
        /// </summary>
        /// <param name="cartList">List of product</param>
        /// <param name="customerUserId">If add for customer in DB, the ID of user of customer</param>
        /// <param name="inputCustomer">If add for new customer</param>
        /// <param name="staffUserId">Adding statff user id</param>
        /// <param name="deposit">Deposit</param>
        /// <param name="deliveryDate">Delivery Date</param>
        /// <returns></returns>
        public bool AddOrder(List<CartViewModel> cartList, int? customerUserId, CustomerViewModel inputCustomer, int staffUserId, int deposit, DateTime deliveryDate, string orderNote)
        {
            OrderViewModel orderViewModel = MakeOrderViewModel(cartList, customerUserId, null);
            if (orderViewModel == null)
            {
                return false;
            }
            DbContextTransaction contextTransaction = db.Database.BeginTransaction();
            // Add order
            Order order = new Order();
            order = orderViewModel.Order;
            DateTime now = DateTime.Now;
            order.ApproveTime = now;
            order.CreateTime = now;
            order.OrderStatus = 2;
            order.PlanDeliveryTime = deliveryDate;
            order.DepositAmount = deposit;
            order.StaffApproveUserId = staffUserId;
            order.OrderNote = orderNote;

            // Get current identity of Order table
            var currentOrderId = db.Database.SqlQuery<decimal>("SELECT IDENT_CURRENT('Orders')").FirstOrDefault();
            String orderCode = "O" + now.ToString("yyyyMMdd") + (((currentOrderId + 1) % 10000)).ToString(new string('0', 4));
            order.OrderCode = orderCode;

            // Customer
            // Exist User
            if (customerUserId != null && inputCustomer == null)
            {
                order.CustomerUserId = customerUserId;
            }
            // New User
            else if (customerUserId == null && inputCustomer != null)
            {
                //Add customer
                User checkUser = db.Users.FirstOrDefault(m => m.Username == inputCustomer.Username ||
                    m.Email == inputCustomer.CustomerEmail);
                Customer checkCustomer =
                    db.Customers.FirstOrDefault(
                        m =>
                            m.CustomerAddress == inputCustomer.CustomerAddress ||
                            m.CustomerPhoneNumber == inputCustomer.CustomerPhoneNumber ||
                            m.TaxCode == inputCustomer.CustomerTaxCode);
                if (checkUser == null && checkCustomer == null)
                {
                    AccountBusiness accountBusiness = new AccountBusiness();

                    // Create user
                    Role role = db.Roles.FirstOrDefault(m => m.Name.Equals("Customer"));
                    // Generate password

                    string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                    var stringChars = new char[6];
                    var random = new Random();
                    for (int i = 0; i < stringChars.Length; i++)
                    {
                        stringChars[i] = chars[random.Next(chars.Length)];
                    }
                    string password = new String(stringChars);


                    User user = new User
                    {
                        Username = inputCustomer.Username,
                        Email = inputCustomer.CustomerEmail,
                        Password = accountBusiness.CreatePassword(password),
                        Role = role,
                        Fullname = inputCustomer.CustomerName

                    };


                    // Creat customer
                    Customer customer = new Customer
                    {
                        CustomerAddress = inputCustomer.CustomerAddress,
                        CustomerPhoneNumber = inputCustomer.CustomerPhoneNumber,
                        TaxCode = inputCustomer.CustomerTaxCode,
                        IsActive = true
                    };

                    user.Customers.Add(customer);
                    order.User = user;

                    string passwordStore = "Tiembanhdautay";
                    string from = "*****@*****.**";
                    string to = user.Email;

                    MailMessage mail = new MailMessage();
                    mail.IsBodyHtml = true;
                    mail.To.Add(to);
                    mail.From = new MailAddress(from);
                    mail.Subject = string.Format("{0}{1}", "Tạo tài khoản cho khách hàng ", user.Fullname);
                    mail.Body += "<html lang='vi'>";
                    mail.Body += "<head>";
                    mail.Body += "<meta charset='utf-8'>";
                    mail.Body += "</head>";
                    mail.Body += "<body>";
                    mail.Body += "<div> Bạn vừa được tạo tài khoản tại Tiệm Bánh Dâu Tây</div>";
                    mail.Body += string.Format("{0}{1}", "Tên tài khoản: ", user.Username);
                    mail.Body += "<div></div>";
                    mail.Body += string.Format("{0}{1}", "Mật khẩu: ", password);
                    mail.Body += "</body>";
                    mail.Body += "</html>";
                    var mailBody = mail.Body;
                    var htmlBody = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
                    mail.AlternateViews.Add(htmlBody);

                    mail.Priority = MailPriority.High;
                    SmtpClient smtp = new SmtpClient();
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new System.Net.NetworkCredential(from, passwordStore);
                    smtp.Port = 587;
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;

                    try
                    {
                        smtp.Send(mail);
                    }
                    catch (Exception e)
                    {
                        return false;
                    }

                }

            }

            #region Add OrderItem, OutputMaterial, ExportFrom, InputMaterial
            foreach (OrderItem orderItem in orderViewModel.Order.OrderItems)
            {
                List<OutputMaterial> outputMaterialList = new List<OutputMaterial>();
                List<MaterialViewModel> materialListForOrderItem = GetMaterialListForOrderItem(orderItem.Product.ProductId,
                    orderItem.Quantity);
                foreach (MaterialViewModel materialViewModel in materialListForOrderItem)
                {
                    OutputMaterial outputMaterial = new OutputMaterial();
                    outputMaterial.ExportQuantity = materialViewModel.NeedQuantity;
                    outputMaterial.ProductMaterialId = materialViewModel.ProductMaterialId;
                    //Get list of InputMaterial available order by expire date descending
                    List<InputMaterial> tempList = db.InputMaterials.Where(
                        m => m.ProductMaterialId == materialViewModel.ProductMaterialId && m.IsActive && m.RemainQuantity > 0).OrderByDescending(m => m.InputMaterialExpiryDate).ToList();
                    //Compare each input material with material ViewModel and merge each material of orderItem to input material
                    foreach (InputMaterial inputMaterial in tempList)
                    {
                        if (materialViewModel.NeedQuantity > 0)
                        {
                            ExportFrom exportFrom = new ExportFrom();
                            if (inputMaterial.RemainQuantity >= materialViewModel.NeedQuantity)
                            {
                                exportFrom.ExportFromQuantity = materialViewModel.NeedQuantity;
                                inputMaterial.RemainQuantity -= materialViewModel.NeedQuantity;
                                materialViewModel.NeedQuantity = 0;
                            }
                            else
                            {
                                materialViewModel.NeedQuantity -= inputMaterial.RemainQuantity;
                                exportFrom.ExportFromQuantity = inputMaterial.RemainQuantity;
                                inputMaterial.RemainQuantity = 0;
                            }
                            InputBill inputBill = inputMaterial.InputBill;
                            // Get info for ExportFrom
                            exportFrom.InputBill = inputBill;
                            // Add input bill to output material
                            outputMaterial.ExportFroms.Add(exportFrom);
                        }
                    }
                    outputMaterialList.Add(outputMaterial);
                }
                orderItem.OutputMaterials = outputMaterialList;
            }
            #endregion




            #region Update ProductMaterial

            foreach (MaterialViewModel materialViewModel in orderViewModel.MaterialList)
            {
                //Update currentQuantity of product material
                ProductMaterial productMaterial =
                    db.ProductMaterials.FirstOrDefault(m => m.ProductMaterialId == materialViewModel.ProductMaterialId);
                if (productMaterial == null)
                {
                    return false;
                }
                productMaterial.CurrentQuantity -= materialViewModel.NeedQuantity;
                db.SaveChanges();
            }
            #endregion
            // Add order to db
            db.Orders.Add(order);
            db.SaveChanges();
            try
            {
                contextTransaction.Commit();
            }
            catch (Exception)
            {
                contextTransaction.Rollback();
            }
            finally
            {
                contextTransaction.Dispose();
            }



            return true;
        }