public async Task <CartOutputModel> CheckoutCartAsync(string customerId, CartModel cart) { if (cart?.Items == null || !cart.Items.Any()) { throw new CheckoutFailedException($"Cannot send shippment for empty cart"); } if (cart.DeliveryAddress == null) { throw new CheckoutFailedException($"Customer address is null"); } var shippment = new Shippment { CustomerId = customerId, Description = GetDescriptionFromCart(cart), UniqueNumber = (int)this.randomizer.RandomNumber(), ShippmentDate = DateTime.UtcNow, ExpectedDeliveryDate = DateTime.UtcNow.AddDays(3), Address = cart.DeliveryAddress }; this.dbContext.Shippments.Add(shippment); await this.dbContext.SaveChangesAsync(); return(new CartOutputModel(shippment.UniqueNumber, shippment.Description, shippment.Address, shippment.ShippmentDate, shippment.ExpectedDeliveryDate)); }
public ActionResult SearchRoute(Shippment model) { var shippment = new Shippment(); var Model = new Shippment(); var categories = DbHelper.GetAllCategoriesFromDb(); Model.Categories = GetCategoryListItems(categories); var cities = DbHelper.GetAllCities(); Model.CitiesFrom = GetCityListItems(cities); Model.CitiesTo = GetCityListItems(cities); if (ModelState.IsValid) { shippment.Category = model.Category; shippment.Weight = model.Weight; shippment.CityFrom = model.CityFrom; shippment.CityTo = model.CityTo; CalculatedRoute calculatedRoute = null; CalculatedRoute calculatedRouteCheap = null; try { calculatedRoute = RouteCalculator.Calculate(model.Category, model.Weight, DbHelper.GetCityByName(model.CityFrom), DbHelper.GetCityByName(model.CityTo), true); calculatedRouteCheap = RouteCalculator.Calculate(model.Category, model.Weight, DbHelper.GetCityByName(model.CityFrom), DbHelper.GetCityByName(model.CityTo), false); } catch (Exception e) { Console.WriteLine(e.ToString()); } shippment.searchedSections = calculatedRoute; shippment.searchedSectionsCheap = calculatedRouteCheap; shippment.Categories = GetCategoryListItems(categories); shippment.CitiesFrom = GetCityListItems(cities); shippment.CitiesTo = GetCityListItems(cities); if (shippment.searchedSections != null && shippment.searchedSections.Route != null) { for (int i = 0; i < shippment.searchedSections.Route.Count; i++) { TempData["price" + i] = shippment.searchedSections.Route[i].Price.ToString(); TempData["duration" + i] = shippment.searchedSections.Route[i].Duration.ToString(); TempData["from" + i] = shippment.searchedSections.Route[i].From.Name; TempData["to" + i] = shippment.searchedSections.Route[i].To.Name; } TempData["price"] = shippment.searchedSections.Price; TempData["duration"] = shippment.searchedSections.Duration; } return(View("index", shippment)); } return(View("index", Model)); }
public void Update(OrderDetail dbEntity, OrderDetail entity) { try { string action = "SendToShip"; if (action == "Complete") { OrderDetail orderDetail = _Context.OrderDetails.Where(s => s.UniqueID == dbEntity.UniqueID).FirstOrDefault(); if (orderDetail != null) { orderDetail.Status = "Complete"; _Context.SaveChanges(); CompletedOrder completed = new CompletedOrder(); completed.UniqueID = orderDetail.UniqueID; completed.DateOfCompliletion = DateTime.Now; _Context.CompletedOrders.Add(completed); _Context.SaveChanges(); } } else if (action == "Cancel") { OrderDetail orderDetail = _Context.OrderDetails.Where(s => s.UniqueID == entity.UniqueID).FirstOrDefault(); if (orderDetail != null) { orderDetail.Status = "Cancel"; _Context.SaveChanges(); CancelOrder cancelOrder = new CancelOrder(); cancelOrder.UniqueID = orderDetail.UniqueID; cancelOrder.DateOfCompliletion = DateTime.Now; _Context.CancelOrders.Add(cancelOrder); _Context.SaveChanges(); } } else if (action == "SendToShip") { OrderDetail orderDetail = _Context.OrderDetails.Where(s => s.UniqueID == dbEntity.UniqueID).FirstOrDefault(); if (orderDetail != null) { orderDetail.Status = "Send To Ship"; _Context.SaveChanges(); Shippment ship = new Shippment(); ship.Status = "Pending"; ship.UniqueID = orderDetail.UniqueID; ship.DateOfCompliletion = DateTime.Now; _Context.Shippments.Add(ship); _Context.SaveChanges(); } } } catch { } }
public ActionResult DeleteConfirmed(int id) { Shippment shippment = db.Shippments.Find(id); db.Shippments.Remove(shippment); db.SaveChanges(); return(RedirectToAction("Index")); }
public IActionResult Postshippment([FromBody] Shippment shippment) { if (shippment == null) { return(BadRequest("shippment is null !!!")); } _dataRepository.Add(shippment); return(CreatedAtRoute("GetShippment", new { Id = shippment.ShippmentID }, shippment)); }
public IActionResult GetShippmentById(long ShippmentId) { Shippment shippment = _dataRepository.Get(ShippmentId); if (shippment == null) { return(NotFound("shippment record not found !!!")); } return(Ok(shippment)); }
public IActionResult DeleteShippment(long ShippmentId) { Shippment shippment = _dataRepository.Get(ShippmentId); if (shippment == null) { return(NotFound("Shippment record not found !!!")); } _dataRepository.Delete(shippment); return(GetPayment()); }
public ActionResult Edit([Bind(Include = "shippmentID,source,destination,departTime,arrivalTime,cargoID")] Shippment shippment) { if (ModelState.IsValid) { db.Entry(shippment).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.cargoID = new SelectList(db.Cargoes, "cargoID", "cargoID", shippment.cargoID); ViewBag.source = new SelectList(db.Warehouses, "warehouseID", "warehouseName", shippment.source); ViewBag.destination = new SelectList(db.Warehouses, "warehouseID", "warehouseName", shippment.destination); return(View(shippment)); }
public ActionResult Index() { var categories = DbHelper.GetAllCategoriesFromDb(); var model = new Shippment(); model.Categories = GetCategoryListItems(categories); var cities = DbHelper.GetAllCities(); model.CitiesFrom = GetCityListItems(cities); model.CitiesTo = GetCityListItems(cities); return(View(model)); }
// GET: Shippments/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Shippment shippment = db.Shippments.Find(id); if (shippment == null) { return(HttpNotFound()); } return(View(shippment)); }
public void Put(int id, OrderDetail entity) { try { string action = "Cancel"; if (action == "Cancel") { OrderDetail orderDetail = db.OrderDetails.Where(s => s.UniqueID == id).FirstOrDefault(); if (orderDetail != null) { orderDetail.Status = "Cancel"; db.SaveChanges(); Stock stock = db.Stocks.Where(s => s.StockID == orderDetail.StockID).FirstOrDefault(); stock.AvailableQuantity = stock.AvailableQuantity + orderDetail.Quantity; db.SaveChanges(); CancelOrder cancelOrder = new CancelOrder(); cancelOrder.UniqueID = orderDetail.UniqueID; cancelOrder.DateOfCompliletion = DateTime.Now; db.CancelOrders.Add(cancelOrder); db.SaveChanges(); } } else if (action == "SendToShip") { OrderDetail orderDetail = db.OrderDetails.Where(s => s.UniqueID == id).FirstOrDefault(); if (orderDetail != null) { orderDetail.Status = "Send To Ship"; db.SaveChanges(); Shippment ship = new Shippment(); ship.Status = "Pending"; ship.UniqueID = orderDetail.UniqueID; ship.DateOfCompliletion = DateTime.Now; db.Shippments.Add(ship); db.SaveChanges(); } } } catch { } }
// GET: Shippments/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Shippment shippment = db.Shippments.Find(id); if (shippment == null) { return(HttpNotFound()); } ViewBag.cargoID = new SelectList(db.Cargoes, "cargoID", "cargoID", shippment.cargoID); ViewBag.source = new SelectList(db.Warehouses, "warehouseID", "warehouseName", shippment.source); ViewBag.destination = new SelectList(db.Warehouses, "warehouseID", "warehouseName", shippment.destination); return(View(shippment)); }
public IActionResult PutShippment(long ShippmentId, [FromBody] Shippment shippment) { if (shippment == null) { return(BadRequest("Shippment is null !!!")); } Shippment ShippmentToUpdate = _dataRepository.Get(ShippmentId); if (ShippmentToUpdate == null) { return(NotFound("shippment record not found !!!")); } _dataRepository.Update(ShippmentToUpdate, shippment); return(CreatedAtRoute("GetShippment", new { Id = shippment.ShippmentID }, shippment)); //_dataRepository.Update(ShippmentId, shippment); //return CreatedAtRoute("GetShippment", new { Id = shippment.ShippmentID }, shippment); }
public IHttpActionResult PutItem(int shipmentId, Shippment shippment) { _repository.Put(shipmentId, shippment); return(CreatedAtRoute("Get", new { Id = shippment.ShippmentID }, shippment)); }
public IHttpActionResult PostItem(Shippment shippment) { _repository.Post(shippment); return(Ok(shippment)); }
/// <summary> /// Create the order /// </summary> /// <param name="currentUser"></param> public void CreateOrder(ApplicationUser currentUser) { //start by getting the current user AdminEngine adminEngine = new AdminEngine(); //// && System.Web.HttpContext.Current.User.IsInRole("user") string user = System.Web.HttpContext.Current.User.Identity.Name; //var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); //store.AutoSaveChanges = false; //var currentUserId = User.Identity.GetUserId(); //var manager = new UserManager<ApplicationUser>(store); //var currentUser = manager.FindById(User.Identity.GetUserId()); //currentUser.MyUserInfo = new MyUserInfo(); //extractCartItems(); using (var context = new EntityMappingContext()) { //Session["Error"] = m_items; //Response.Redirect("/UserPages/ErrorPage.aspx"); m_items = GetCartItems(); //lists to store ids and quantity respectively m_listIds = new List <int>(); m_listQuantity = new List <int>(); //fill order items - from the cart //get just the product id and the quantity. The rest I search for for (int i = 0; i < m_items.Count; i++) { m_orderItem = new OrderItem() { // OrderId = order.OrderId, ProductId = m_items[i].ProductId, Quantity = m_items[i].Quantity, Price = m_items[i].Product.UnitPrice, ItemName = m_items[i].Product.ProductName, Specs = m_items[i].Product.Specifications, }; //add items and their corresponding id m_listIds.Add(m_items[i].ProductId); m_listQuantity.Add(m_items[i].ProductId); //Product Data m_ProductName += Environment.NewLine + m_items[i].Product.ProductName + ","; // drop lines m_orderQuantity += m_items[i].Quantity; m_ProductPrice = Convert.ToDouble(m_items[i].Product.UnitPrice); m_Subtotal += m_items[i].Quantity * Convert.ToDouble(m_items[i].Product.UnitPrice); m_Total = m_Subtotal * 1.25; try { // Add OrderDetail to DB. ctx.OrderItems.Add(m_orderItem); ctx.SaveChanges(); } catch (Exception ex) { HttpContext.Current.Session["Error"] = ex; HttpContext.Current.Response.Redirect("ErrorPage.aspx"); } } HttpContext.Current.Session["m_listIds"] = m_listIds; HttpContext.Current.Session["m_listQuantity"] = m_listQuantity; //Generate Order Confirmation OrderConfirmation orderConfirmation = new OrderConfirmation() { CustomerName = currentUser.MyUserInfo.FirstName, CustomerMiddle = currentUser.MyUserInfo.MiddleName, CustomerLast = currentUser.MyUserInfo.LastName, CustomerPhone = currentUser.MyUserInfo.Telephone, CustomerCell = currentUser.MyUserInfo.Cellphone, CustomerEmail = currentUser.MyUserInfo.Email, BillingAddressName = currentUser.BillingAddress.AddressName, BillingAddressNo = currentUser.BillingAddress.AddressNumber, BillingApartment = currentUser.BillingAddress.Apartment, BillingStair = currentUser.BillingAddress.Stair, BillingZipCode = currentUser.BillingAddress.Zipcode, BillingCity = currentUser.BillingAddress.City, BillingCountry = currentUser.BillingAddress.Country, ShippingAddressName = currentUser.ShippingAddress.AddressName, ShippingAddressNo = currentUser.ShippingAddress.AddressNumber, ShippingApartment = currentUser.ShippingAddress.Apartment, ShippingStair = currentUser.ShippingAddress.Stair, ShippingZipCode = currentUser.ShippingAddress.Zipcode, ShippingCity = currentUser.ShippingAddress.City, ShippingCountry = currentUser.ShippingAddress.Country, ////Product Data ProductName = m_ProductName, Quantity = m_orderQuantity, ProductSpec = m_orderItem.Specs, Subtotal = m_Subtotal, Total = m_Total, //Payment Data - Credit Card CCardName = currentUser.MyUserCCardInfo.CardName, CCardNo = currentUser.MyUserCCardInfo.CardNumber, CCArdExpiryDate = currentUser.MyUserCCardInfo.CardExpiryDate, CCardSecurityCode = currentUser.MyUserCCardInfo.CardSecurityCode, }; //for (int i = 0; i < m_items.Count; i++) //{ // //instantiate orderEngine to access GetLineItem method // OrderEngine orderEngine = new OrderEngine(); //get the item list //List<LineItem> itemList = orderEngine.GetLineItems(); //create order m_order = new Order() { Created = DateTime.Now.ToString(), BillingAddress = orderConfirmation.BillingAddress, ShippingAddress = orderConfirmation.ShippingAddress, CustomerName = currentUser.UserName, Total = orderConfirmation.Total, }; //} //Generate invoice Invoice invoice = new Invoice() { SubTotal = m_orderItem.Price, Tax = 0.25, Total = (m_orderItem.Price * (0.25)) + m_orderItem.Quantity, // BillingAddress = billingAddress, }; //initialize type to avoid nulle refference //CreateAddress Address billingAddress = new Address() { //Address part StreetName = currentUser.BillingAddress.AddressName, StreetNo = currentUser.BillingAddress.AddressNumber, City = currentUser.BillingAddress.City, Country = currentUser.BillingAddress.Country, ZipCode = currentUser.BillingAddress.Zipcode, }; //Create customer Customer customer = new Customer() { FirstName = currentUser.MyUserInfo.FirstName, MiddleName = currentUser.MyUserInfo.MiddleName, LastName = currentUser.MyUserInfo.LastName, Phone = currentUser.MyUserInfo.Telephone, CellPhone = currentUser.MyUserInfo.Cellphone, Email = currentUser.MyUserInfo.Email //BillingAddress = billingAddress }; //add delivery address Address deliveryAddress = new Address() { //Address part StreetName = currentUser.ShippingAddress.AddressName, StreetNo = currentUser.ShippingAddress.AddressNumber, City = currentUser.ShippingAddress.City, Country = currentUser.ShippingAddress.Country, ZipCode = currentUser.ShippingAddress.Zipcode, }; //Shippment Shippment shipment = new Shippment() { State = "Not shipped", AddresName = currentUser.ShippingAddress.AddressName, AddressNo = currentUser.ShippingAddress.AddressNumber, AddresApt = currentUser.ShippingAddress.Apartment, AddresStair = currentUser.ShippingAddress.Stair, Country = currentUser.ShippingAddress.Country, City = currentUser.ShippingAddress.City, ZipCode = currentUser.ShippingAddress.Zipcode, }; try { ctx.OrderConfirmations.Add(orderConfirmation); ctx.Orders.Add(m_order); // ctx.LineItems.Add(m_lineItem); // Add OrderDetail to DB. ctx.Invoices.Add(invoice); ctx.Customers.Add(customer); ctx.Addresses.Add(billingAddress); ctx.Shipments.Add(shipment); ctx.SaveChanges(); // Prepare for the items to be saved. this is used to display the line items List <CartItem> orderDetailList = GetCartItems(); // Add OrderDetail information to the DB for each product purchased. for (int i = 0; i < orderDetailList.Count; i++) { // Create a new OrderDetail object. m_lineItem = new LineItem(); m_lineItem.OrderId = m_order.OrderId; m_lineItem.UserName = currentUser.UserName; m_lineItem.ProductID = orderDetailList[i].ProductId; m_lineItem.ProductName = orderDetailList[i].Product.ProductName; m_lineItem.Quantity = orderDetailList[i].Quantity; m_lineItem.UnitPrice = orderDetailList[i].Product.UnitPrice; ctx.LineItems.Add(m_lineItem); ctx.SaveChanges(); } m_lastOrderId = m_order.OrderId; HttpContext.Current.Session["lastId"] = m_lastOrderId; m_lastOrderConfirmationId = orderConfirmation.OrderConfirmationId; HttpContext.Current.Session["lastOrderConfId"] = m_lastOrderConfirmationId; //validate ctx.Configuration.ValidateOnSaveEnabled = true; } catch (DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); HttpContext.Current.Session["Error"] = fullErrorMessage; HttpContext.Current.Response.Redirect("/UserPages/ErrorPage.aspx"); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } finally { //orderId var orderId = ctx.Orders.OrderByDescending(myorder => myorder.OrderId).FirstOrDefault(); OrderEngine orderEngine = new OrderEngine(); //Change the status or the order var anorder = (from myorder in ctx.Orders where myorder.OrderId == m_lastOrderId // get the corresponding order select myorder).First(); // this will fetch the record. anorder.Submitted = DateTime.Now.ToString(); ctx.SaveChanges(); } ////reset the cart for next order //// cartEngine.ZeroCart(); // EmptyCart(); //HttpContext.Current.Response.Redirect("/UserPages/Products.aspx"); }//end EntityMappingContext }
public IHttpActionResult DeletePayment(int shipmentId, Shippment shippment) { _repository.Delete(shipmentId); return(CreatedAtRoute("GetItem", new { Id = shippment.ShippmentID }, shippment)); }