public OrderCreateViewModel OrderCreateFactory( Customer customer, List<Product> products, OrderCreateViewModel vm = null) { // Check if the view model exists, if not create new one vm = vm ?? new OrderCreateViewModel(); // Assign the order details if it exists or create new one vm.Order = vm.Order ?? new OrderViewModel(); // Products var productsList = products.Select( e => new OrderProductViewModel { ProductId = e.ProductId, ProductName = e.ProductName, Price = e.UnitPrice, SupplierName = e.Supplier.CompanyName, Qauntity = 0 }).ToList(); // Reassign products with proper quanities vm.Products?.ForEach(e => { if (e.Qauntity <= 0) return; var orderProductViewModel = productsList.FirstOrDefault(x => x.ProductId == e.ProductId); if (orderProductViewModel != null) orderProductViewModel.Qauntity = e.Qauntity; }); vm.Products = productsList; vm.Customer = customer; return vm; }
public ActionResult SubmitOrder(OrderCreateViewModel vm) { // No Data was included, return with error if (vm == null) { Danger("No data was included with your Submit Order Request"); return RedirectToAction("Oops", "Home"); } try { // Model state is invalid, return with error if (!ModelState.IsValid) { vm = new CustomerViewFactories().OrderCreateFactory( _repo.GetCustomerById(vm.Customer.CustomerId), _repo.GetProducts().ToList(), vm ); return View("CreateOrder", vm); } // Make a quantity list for the repo var productList = new Dictionary<int, int>(); vm.Products.Where(e => e.Qauntity > 0).ForEach(e => { productList.Add(e.ProductId, e.Qauntity); }); // Create the Order _repo.CreateProduct( vm.Customer.CustomerId, User.Identity.GetUserId(), productList, vm.Order.RequiredDate, vm.Order.ShippedDate); Success("The Order has been placed"); return RedirectToAction("Index","Customers"); } catch (OrderNeedsProductsException) { Danger("No Products were included in your Add Order request"); } catch (UserNotFoundException) { Danger("The User you are trying to attach to the Order request does not exist"); } catch (CustomerNotFoundException) { Danger("The Customer you are trying to attach an Order to does not exist"); } catch (ProductNotFoundException) { Danger("A Product you are trying to attach to an Order request does not exist"); } // If we got here, something did not work return RedirectToAction("Oops", "Home"); }