/// <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; }
/// <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; }
public bool IsEnoughMaterialForOrder(Order order) { List<MaterialViewModel> materialViewModelList = new List<MaterialViewModel>(); foreach (OrderItem orderItem in order.OrderItems) { // Get material list for each order item List<MaterialViewModel> materialListForOrderItem = GetMaterialListForOrderItem(orderItem.Product.ProductId, orderItem.Quantity); // Check each material in materialListForOrderItem, if NeedQuantity > Storage Quantity, return false // else if materialViewModelList does not have any member, add into it // else check each member in materialViewModel depends on ProductMaterialId, if NeedQuantity + this.NeedQuantity > Storage Quantity, return false // else plus into NeedQuantity // else add this materialListForOrderItem into materialViewModelList foreach (MaterialViewModel materialForOrderItemViewModel in materialListForOrderItem) { if (materialForOrderItemViewModel.NeedQuantity > materialForOrderItemViewModel.StorageQuantity) { return false; } if (materialViewModelList.Count == 0) { materialViewModelList.Add(materialForOrderItemViewModel); } else { bool check = true; foreach (MaterialViewModel materialViewModel in materialViewModelList) { if (materialViewModel.ProductMaterialId == materialForOrderItemViewModel.ProductMaterialId) { check = false; if ((materialViewModel.NeedQuantity + materialForOrderItemViewModel.NeedQuantity) > materialViewModel.StorageQuantity) { return false; } else { materialViewModel.NeedQuantity += materialForOrderItemViewModel.NeedQuantity; } } } if (check) { materialViewModelList.Add(materialForOrderItemViewModel); } } } } return true; }
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; }
public bool OrderProduct(string orderTime, DateTime planDeliveryDate, int Amount, int taxAmount, int discount, int cusUserId, List<CustomerCartViewModel> cart, string Note) { DbContextTransaction contextTransaction = db.Database.BeginTransaction(); Order order = new Order(); order.OrderCode = orderTime; order.CreateTime = DateTime.Now; order.PlanDeliveryTime = planDeliveryDate; order.DepositAmount = 0; order.IsStaffEdit = false; order.CustomerEditingFlag = false; order.OrderStatus = 0; order.Amount = Amount; order.TaxAmount = taxAmount; order.DiscountAmount = discount; order.CustomerUserId = cusUserId; order.OrderNote = Note; db.Orders.Add(order); db.SaveChanges(); order.OrderCode = CreateOrderCode(orderTime, order.OrderId); //string orderNumber = order.OrderId.ToString().PadLeft(4, '0'); //order.OrderCode = String.Format("{0}{1}{2}", 'O', orderTime, orderNumber); db.SaveChanges(); foreach (var item in cart) { OrderItem orderDetail = new OrderItem(); orderDetail.OrderId = order.OrderId; orderDetail.ProductId = item.ProductId; orderDetail.Quantity = item.Quantity; orderDetail.RealPrice = item.Price; orderDetail.Amount = item.Total; db.OrderItems.Add(orderDetail); } db.SaveChanges(); try { contextTransaction.Commit(); } catch (Exception) { contextTransaction.Rollback(); } finally { contextTransaction.Dispose(); } return true; }
public bool GuestOrderProduct(string orderTime, DateTime planDeliveryDate, int Amount, int taxAmount, int discount, List<CustomerCartViewModel> cart, string sName, string sPhone, string sAddress, string sEmail, string Note) { DbContextTransaction contextTransaction = db.Database.BeginTransaction(); Order order = new Order(); order.OrderCode = orderTime; order.CreateTime = DateTime.Now; order.PlanDeliveryTime = planDeliveryDate; order.DepositAmount = 0; order.IsStaffEdit = false; order.CustomerEditingFlag = false; order.OrderStatus = 0; order.Amount = Amount; order.TaxAmount = taxAmount; order.DiscountAmount = discount; order.OrderNote = Note; GuestInfo guestInfo = new GuestInfo(); guestInfo.GuestInfoName = sName; guestInfo.GuestInfoPhone = sPhone; guestInfo.GuestInfoAddress = sAddress; guestInfo.GuestInfoEmail = sEmail; db.GuestInfoes.Add(guestInfo); db.SaveChanges(); order.GuestInfoId = guestInfo.GuestInfoId; db.Orders.Add(order); db.SaveChanges(); order.OrderCode = CreateOrderCode(orderTime, order.OrderId); db.SaveChanges(); foreach (var item in cart) { OrderItem orderDetail = new OrderItem(); orderDetail.OrderId = order.OrderId; orderDetail.ProductId = item.ProductId; orderDetail.Quantity = item.Quantity; orderDetail.RealPrice = item.Price; orderDetail.Amount = item.Total; db.OrderItems.Add(orderDetail); } db.SaveChanges(); try { contextTransaction.Commit(); } catch (Exception) { contextTransaction.Rollback(); } finally { contextTransaction.Dispose(); } return true; }