Пример #1
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;
        }
Пример #2
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;
        }
Пример #3
0
        public int UpdateOrder(List<CartViewModel> cartList, int orderId, int depositAmount,
            DateTime deliveryDate, int staffUserId, string orderNote)
        {

            Order previousOrder = db.Orders.FirstOrDefault(m => m.OrderId == orderId);

            if (previousOrder == null)
            {
                return 0;
            }

            int check = 0;

            foreach (OrderItem orderItem in previousOrder.OrderItems)
            {

                foreach (CartViewModel cartViewModel in cartList)
                {
                    if (cartViewModel.ProductId == orderItem.ProductId &&
                              cartViewModel.Quantity == orderItem.Quantity &&
                              cartViewModel.RealPrice == orderItem.RealPrice)
                    {
                        check++;
                    }
                }
            }

            if (previousOrder.OrderItems.Count == check && cartList.Count == check)
            {
                return 2;
            }

            OrderViewModel orderViewModel = MakeOrderViewModel(cartList, previousOrder.User.UserId, null);

            

            if (orderViewModel == null)
            {
                return 0;
            }
            DbContextTransaction contextTransaction = db.Database.BeginTransaction();
            // Add order
            Order order = new Order();
            order.CreateTime = previousOrder.CreateTime;
            order.OrderStatus = 1;
            order.PlanDeliveryTime = deliveryDate;
            order.DepositAmount = depositAmount;
            order.Amount = orderViewModel.Order.Amount;
            order.TaxAmount = orderViewModel.Order.TaxAmount;
            order.StaffApproveUserId = staffUserId;
            order.OrderNote = orderNote;
            // Get current identity of Order table
            order.OrderCode = previousOrder.OrderCode;

            //Add customer
            order.User = previousOrder.User;

            // Update prevoius order
            previousOrder.IsStaffEdit = true;
            order.PreviousOrderId = previousOrder.OrderId;
            order.IsStaffEdit = false;
            order.StaffEditTime = DateTime.Now;

            //Add OrderItem and OutputMaterial 
            #region Add OrderItem, OutputMaterial, ExportFrom, InputMaterial
            List<OrderItem> orderItemList = new List<OrderItem>();
            foreach (OrderItem orderItem in orderViewModel.Order.OrderItems)
            {
                TaxRate taxRate =
                    db.TaxRates.FirstOrDefault(
                        m =>
                            m.TaxTypeId == 1 && previousOrder.CreateTime <= m.EndDate &&
                            previousOrder.CreateTime >= m.BeginDate);
                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;
                            outputMaterial.ExportFroms.Add(exportFrom);
                        }
                    }
                    outputMaterialList.Add(outputMaterial);
                }
                orderItem.OutputMaterials = outputMaterialList;
                orderItemList.Add(orderItem);
            }
            order.OrderItems = orderItemList;
            #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 0;
                }
                productMaterial.CurrentQuantity -= materialViewModel.NeedQuantity;
                db.SaveChanges();
            }
            #endregion
            // Add order to db
            db.Orders.Add(order);
            db.SaveChanges();
            try
            {
                contextTransaction.Commit();
            }
            catch (Exception)
            {
                contextTransaction.Rollback();
                return 0;
            }
            finally
            {
                contextTransaction.Dispose();
            }



            return 1;
        }