public ActionResult CheckoutWithNewCustomer(FormCollection form) { try { // Check autherization User staffUser = Session["User"] as User; if (staffUser == null || Session["UserRole"] == null || (int)Session["UserRole"] != 2) { Session["Cart"] = null; return RedirectToAction("Index", "Home"); } List<CartViewModel> inputCartList = Session["Cart"] as List<CartViewModel>; string customerNameString = form["customerName"]; string customerEmailString = form["customerEmail"]; string customerAddressString = form["customerAddress"]; string customerPhoneNumberString = form["customerPhoneNumber"]; string customerTaxCodeString = form["customerTaxCode"]; string usernameString = form["username"]; if ( !(customerNameString.IsEmpty() || customerAddressString.IsEmpty() || customerPhoneNumberString.IsEmpty() || customerTaxCodeString.IsEmpty() || customerEmailString.IsEmpty() || usernameString.IsEmpty())) { CustomerViewModel customer = new CustomerViewModel(); customer.CustomerName = customerNameString; customer.CustomerAddress = customerAddressString; customer.CustomerPhoneNumber = customerPhoneNumberString; customer.CustomerTaxCode = customerTaxCodeString; customer.Username = usernameString; customer.CustomerEmail = customerEmailString; Session["CustomerId"] = 0; Session["NewCustomer"] = customer; OrderBusiness orderBusiness = new OrderBusiness(); OrderViewModel order = orderBusiness.MakeOrderViewModel(inputCartList, null, customer); ViewBag.TreeView = "order"; ViewBag.TreeViewMenu = "addOrder"; return View("CheckoutWithCustomer", order); } return RedirectToAction("AddCustomerToOrder"); } catch (Exception) { return RedirectToAction("ManageError", "Error"); } }
public int ApproveOrder(FormCollection form) { try { //Check autherization User staffUser = Session["User"] as User; if (staffUser == null || Session["UserRole"] == null || (int)Session["UserRole"] != 2) { return -7; } else { String customerName = form["customerName"]; if (customerName == null) { int orderId = Convert.ToInt32(form["orderId"]); int deposit = Convert.ToInt32(form["deposit"].Replace(".", "")); string deliveryDateString = form["deliveryDate"]; DateTime deliveryDate = DateTime.ParseExact(deliveryDateString, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); OrderBusiness orderBusiness = new OrderBusiness(); return orderBusiness.ApproveOrder(orderId, deposit, deliveryDate, staffUser.UserId, null); } else { string orderIdString = form["orderId"]; string username = form["username"]; string email = form["customerEmail"]; string customerAddress = form["customerAddress"]; string customerPhoneNumber = form["customerPhoneNumber"]; string customerTaxCode = form["customerTaxCode"]; if (!(customerName.IsEmpty() || orderIdString.IsEmpty() || username.IsEmpty() || email.IsEmpty() || customerAddress.IsEmpty() || customerPhoneNumber.IsEmpty() || customerTaxCode.IsEmpty())) { OrderBusiness orderBusiness = new OrderBusiness(); int check = orderBusiness.CheckCustomerField(email, customerAddress, customerPhoneNumber, customerTaxCode, username); if (check != 0) { return check; } int orderId = Convert.ToInt32(orderIdString); int deposit = Convert.ToInt32(form["deposit"].Replace(".", "")); CustomerViewModel customer = new CustomerViewModel { Username = username, CustomerEmail = email, CustomerAddress = customerAddress, CustomerPhoneNumber = customerPhoneNumber, CustomerName = customerName, CustomerTaxCode = customerTaxCode }; DateTime deliveryDate = DateTime.ParseExact(form["deliveryDate"], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture); int rs = orderBusiness.ApproveOrder(orderId, deposit, deliveryDate, staffUser.UserId, customer); return rs; } return 0; } } } catch (Exception) { return 0; } }
/// <summary> /// Make OrderViewModel /// </summary> /// <param name="cartList">List of product</param> /// <param name="customerId">The ID of the customer in DB</param> /// <param name="customerInput">The new customer info</param> /// <returns></returns> public OrderViewModel MakeOrderViewModel(List<CartViewModel> cartList, int? customerId, CustomerViewModel customerInput) { OrderViewModel result = new OrderViewModel(); // Create new order Order order = new Order(); if (customerId != null && customerInput == null) { order.CustomerUserId = customerId; //Add info for OrderView //Customer info Customer customer = db.Customers.FirstOrDefault(m => m.UserId == customerId && m.IsActive); if (customer != null) { result.OrderPersonName = customer.User.Fullname; result.OrderPersonAddress = customer.CustomerAddress; result.OrderPersonPhoneNumber = customer.CustomerPhoneNumber; result.OrderPersonTaxCode = customer.TaxCode; result.IsGuest = false; result.IsLoyal = customer.IsLoyal; } } else if (customerId == null && customerInput != null) { order.CustomerUserId = 0; //Add new customer info for OrderView //Customer info result.OrderPersonName = customerInput.CustomerName; result.OrderPersonAddress = customerInput.CustomerAddress; result.OrderPersonPhoneNumber = customerInput.CustomerPhoneNumber; result.OrderPersonTaxCode = customerInput.CustomerTaxCode; result.IsGuest = true; result.IsLoyal = false; } // Temp var for total amount int totalAmount = 0; // Taemp var for total quantity int totalQuantity = 0; // Creat OrderItemViewModel List and MaterialViewModelList List<OrderItem> orderItemList = new List<OrderItem>(); List<MaterialViewModel> materialViewModelList = new List<MaterialViewModel>(); foreach (CartViewModel cartViewModel in cartList) { if (cartViewModel.Quantity != 0) { //Create OrderItem and add to list OrderItem orderItem = new OrderItem(); Product product = db.Products.FirstOrDefault(m => m.ProductId == cartViewModel.ProductId); orderItem.Product = product; orderItem.Quantity = cartViewModel.Quantity; orderItem.RealPrice = cartViewModel.RealPrice; orderItem.Amount = cartViewModel.Quantity * cartViewModel.RealPrice; orderItemList.Add(orderItem); totalAmount += cartViewModel.Quantity * cartViewModel.RealPrice; totalQuantity += cartViewModel.Quantity; //Create MaterialViewModel and add to list // Get Product in DB if (product != null) { foreach (Recipe recipe in product.Recipes) { if (materialViewModelList.Count == 0) { MaterialViewModel materialViewModel = new MaterialViewModel(); // Get each product material and multiply with quantity materialViewModel.ProductMaterialId = recipe.ProductMaterialId; materialViewModel.ProductMaterialName = recipe.ProductMaterial.ProductMaterialName; materialViewModel.NeedQuantity = (int)Math.Floor(recipe.RecipeQuantity * cartViewModel.Quantity); materialViewModel.StorageQuantity = recipe.ProductMaterial.CurrentQuantity; // Add into MaterialViewModelList materialViewModelList.Add(materialViewModel); } else { bool check = true; foreach (MaterialViewModel materialViewModel in materialViewModelList) { if (materialViewModel.ProductMaterialId == recipe.ProductMaterialId) { materialViewModel.NeedQuantity += (int)Math.Floor(recipe.RecipeQuantity * cartViewModel.Quantity); check = false; } } if (check) { MaterialViewModel materialViewModel = new MaterialViewModel(); // Get each product material and multiply with quantity materialViewModel.ProductMaterialId = recipe.ProductMaterialId; materialViewModel.ProductMaterialName = recipe.ProductMaterial.ProductMaterialName; materialViewModel.NeedQuantity = (int)Math.Floor(recipe.RecipeQuantity * cartViewModel.Quantity); materialViewModel.StorageQuantity = recipe.ProductMaterial.CurrentQuantity; // Add into MaterialViewModelList materialViewModelList.Add(materialViewModel); } } } } } } // Complete attribute in order //Check enough material for order result.IsEnoughMaterial = true; foreach (MaterialViewModel materialViewModel in materialViewModelList) { if (materialViewModel.NeedQuantity > materialViewModel.StorageQuantity) { materialViewModel.IsEnough = false; result.IsEnoughMaterial = false; } else { materialViewModel.IsEnough = true; } } int discountAmount = 0; DiscountByQuantity discountByQuantity = db.DiscountByQuantities.FirstOrDefault( m => m.QuantityFrom <= totalQuantity && m.QuantityTo >= totalQuantity); if (discountByQuantity != null) { discountAmount = totalAmount * discountByQuantity.DiscountValue / 100; } int totalTax = 0; TaxRate taxRate = db.TaxRates.FirstOrDefault( m => m.TaxType.Abbreviation.Equals("GTGT") && m.BeginDate <= DateTime.Now && m.EndDate >= DateTime.Now); if (taxRate != null) { totalTax = (totalAmount - discountAmount) * taxRate.TaxRateValue / 100; } order.Amount = totalAmount; order.DiscountAmount = discountAmount; order.TaxAmount = totalTax; order.OrderItems = orderItemList; result.Order = order; result.MaterialList = materialViewModelList; // Calculate the Material cost List<InputMaterialViewModel> inputMaterialList = GetInputMaterialList(materialViewModelList); result.MaterialCost = GetMaterialCost(inputMaterialList); return result; }
/// <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; }
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; }