public async Task <ViewResult> OrderDetails(int OrderId) { OrderRootSingleObject orderDetails = new OrderRootSingleObject(); CustomerOrderModel custModel = new CustomerOrderModel(); if (ModelState.IsValid) { ViewBag.LoginID = Session["LoginID"].ToString(); ViewBag.Username = Session["Username"].ToString(); ViewBag.StoreId = Session["StoreId"].ToString(); //ViewBag.OrderId = OrderId; string strurl = GetUrl(2); strurl = strurl + "UserLogin/GetOrderByOrderId?orderid=" + OrderId + "&storeid=" + ViewBag.StoreId + ""; using (HttpClient client = new HttpClient()) { HttpResponseMessage CustomerresponseMessage = await client.GetAsync(strurl); if (CustomerresponseMessage.IsSuccessStatusCode) { var response = CustomerresponseMessage.Content.ReadAsStringAsync().Result; var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore }; orderDetails = JsonConvert.DeserializeObject <OrderRootSingleObject>(response, settings); custModel = orderDetails.data; ViewBag.Transaction = custModel; } } return(View(custModel)); } return(View(custModel)); }
public IActionResult AddCustomerOrder(CustomerOrderViewModel customerorder) { //ViewBag.Locations = new SelectList() //if (customerorder is null) //{ // throw new ArgumentNullException(nameof(customerorder)); //} try { if (ModelState.IsValid) { var addtorepo = new CustomerOrderModel { LocationName = customerorder.LocationName, AmountPurchased = customerorder.AmountPurchased, CustomerName = customerorder.CustomerName, ProductId = customerorder.ProductId, }; _orderRepo.AddOrder(addtorepo); _orderRepo.Save(); return(RedirectToAction(nameof(Index))); } return(View(customerorder)); } catch { return(View(customerorder)); } }
public HttpResponseMessage EventOrderCancel(CustomerOrderModel model) { try { if (model.OrderNumber.ToString() != null || model.OrderNumber != "") { var result = _repository.EventOrderCancel(model.OrderNumber, model.CustomerId, model.StoreId); if (result.isSuccess == true) { return(Request.CreateResponse(HttpStatusCode.OK, new { result })); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, new { result })); } } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something Worng !")); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something Worng !", ex)); } }
public HttpResponseMessage EventOrderUpdate(CustomerOrderModel model) { ResponseStatus response = new ResponseStatus(); try { if (ModelState.IsValid) { var data = _repository.EventOrderUpdate(model); if (data.OrderId > 0) { response.serverResponseTime = System.DateTime.Now; response.isSuccess = true; return(Request.CreateResponse(HttpStatusCode.OK, new { data, response })); } else { response.serverResponseTime = System.DateTime.Now; response.isSuccess = false; return(Request.CreateResponse(HttpStatusCode.BadRequest, new { response })); } } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something Worng !")); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something Worng !", ex)); } }
public void OrderItem(int orderId, int itemid, int itemquantity) { ItemModel selecteditem = Items.Where(x => x.ItemId == itemid && x.IsAvailable).FirstOrDefault(); if (selecteditem == null) { Console.WriteLine("Wrong ItemId ,Please Select Valid ItemId"); } else { ItemsWithQuantityModel itemsWithQuantity = new ItemsWithQuantityModel(); itemsWithQuantity.ItemModel = selecteditem; itemsWithQuantity.Quantity = itemquantity; CustomerOrderModel customerOrder = new CustomerOrderModel(); customerOrder.OrderId = orderId; customerOrder.orderedItemsWithQuantity.Add(itemsWithQuantity); //customerOrderedItemsWithQuantityRestro.Add(itemsWithQuantity); //customerOrder.orderedItemsWithQuantity = customerOrderedItemsWithQuantityRestro; //initalize CustomerOrderModel existingOrder = customerOrderModelsList.Where(x => x.OrderId == orderId).FirstOrDefault(); if (existingOrder == null) { customerOrderModelsList.Add(customerOrder); } else { existingOrder.orderedItemsWithQuantity.Add(itemsWithQuantity); } } }
public HttpResponseMessage GetAllEventOrderByOrderNumber(CustomerOrderModel model) { ResponseStatus response = new ResponseStatus(); //OrderModel data = new OrderModel(); try { if (model.OrderNumber != null) { var data = _repository.GetAllEventOrderByOrderNumber(model.OrderNumber); if (data != null) { response.serverResponseTime = System.DateTime.Now; response.isSuccess = true; return(Request.CreateResponse(HttpStatusCode.OK, new { data, response })); } else { response.serverResponseTime = System.DateTime.Now; response.isSuccess = false; return(Request.CreateResponse(HttpStatusCode.BadRequest, new { response })); } } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something Worng !")); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something Worng !", ex)); } }
public ActionResult DeleteConfirmed(int id) { CustomerOrderModel customerOrderModel = db.CustomerOrderModels.Find(id); db.CustomerOrderModels.Remove(customerOrderModel); db.SaveChanges(); return(RedirectToAction("Index")); }
// FullText Search. public List <CustomerOrderModel> SearchOrder(string customerName, string address) { Hashtable ht = new Hashtable(); ht.Add("CustomerName", customerName); ht.Add("Address", address); DataTable dt = GetDataTableFromProcedure("SpSearchCustomer", ht); List <CustomerOrderModel> model = new List <CustomerOrderModel>(); if (dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { CustomerOrderModel cust = new CustomerOrderModel(); cust.Address = row["Address"].ToString(); cust.ContactNo = row["ContactNo"].ToString(); cust.Country = row["Country"].ToString(); cust.Email = row["Email"].ToString(); cust.FullName = row["FullName"].ToString(); cust.Mobile = row["Mobile"].ToString(); cust.ZipCode = row["ZipCode"].ToString(); cust.ContactNo = row["ContactNo"].ToString(); cust.EmailID = row["EmailID"].ToString(); string orderdate = row["OrderDate"].ToString(); if (row["OrderDate"].ToString() != null && orderdate != "") { cust.OrderDate = Convert.ToDateTime(row["OrderDate"].ToString()); } cust.InvoiceNo = row["InvoiceNo"].ToString(); cust.OrderID = Convert.ToInt32(row["OrderID"].ToString()); cust.PaymentInfo = row["PaymentInfo"].ToString(); cust.PaymentMethod = row["PaymentMethod"].ToString(); cust.State = row["State"].ToString(); cust.State2 = row["State2"].ToString(); cust.Status = row["Status"].ToString(); if (row["TaxAmount"].ToString() != null && row["TaxAmount"].ToString() != "") { cust.TaxAmount = Convert.ToDecimal(row["TaxAmount"].ToString()); } cust.ZipCode = row["ZipCode"].ToString(); cust.ZipCode2 = row["ZipCode2"].ToString(); cust.CustomerID = Convert.ToInt32(row["CustomerID"].ToString()); cust.DeliveryAddress = row["DeliveryAddress"].ToString(); cust.DeliveryAddress2 = row["DeliveryAddress2"].ToString(); cust.DeliveryMethod = row["DeliveryMethod"].ToString(); cust.Email = row["Email"].ToString(); if (row["TotalAmount"].ToString() != null && row["TotalAmount"].ToString() != "") { cust.TotalAmount = Convert.ToDecimal(row["TotalAmount"].ToString()); } model.Add(cust); } } return(model); }
public IActionResult Save([FromForm] CustomerOrderModel customerOrder) { if (customerOrder.customer_name == null || customerOrder.customer_surname == null || customerOrder.order_no == null || customerOrder.order_date.Year == 1) { return(Json("-1")); } var customer = repoCustomer.Where(x => x.customer_name == customerOrder.customer_name && x.customer_surname == customerOrder.customer_surname ).FirstOrDefault(); var customer_id = 0; if (customer == null) { var newCustomer = new Customer() { customer_name = customerOrder.customer_name.ToUpper(new CultureInfo("tr-TR", false)), customer_surname = customerOrder.customer_surname.ToUpper(new CultureInfo("tr-TR", false)), created_at = DateTime.Now }; customer_id = repoCustomer.Add(newCustomer); } else { if (customer.id != customerOrder.customer_no) { return(Json("-3")); } } var orderItemList = HttpContext.Session.GetObjectFromJson <OrderSessionModel>("orders"); if (orderItemList == null) { return(Json("-2")); } foreach (var orderItem in orderItemList.Order) { var newOrder = new Orders() { count = orderItem.count, created_at = customerOrder.order_date, customer_id = customerOrder.customer_no != 0 ? customerOrder.customer_no : customer_id, discount = orderItem.discount, order_no = customerOrder.order_no.ToUpper(new CultureInfo("tr-TR", false)), order_price = !string.IsNullOrEmpty(orderItem.order_price) ? Convert.ToDecimal(orderItem.order_price.Replace(".", ",")) : 0, product_id = orderItem.product_id, warehouse_id = orderItem.warehouse_id }; repoOrders.Add(newOrder); } return(Json("1")); }
public ActionResult Edit([Bind(Include = "CustomerOrderID,CustomerID,OrderDate")] CustomerOrderModel customerOrderModel) { if (ModelState.IsValid) { db.Entry(customerOrderModel).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CustomerID = new SelectList(db.CustomerModels, "CustomerID", "Name", customerOrderModel.CustomerID); return(View(customerOrderModel)); }
public ActionResult Create([Bind(Include = "CustomerOrderID,CustomerID,OrderDate")] CustomerOrderModel customerOrderModel) { if (ModelState.IsValid) { db.CustomerOrderModels.Add(customerOrderModel); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CustomerID = new SelectList(db.CustomerModels, "CustomerID", "Name", customerOrderModel.CustomerID); return(View(customerOrderModel)); }
public int GetCustomerBill(int orderId) { CustomerOrderModel customerOrder = customerOrderModelsList.Where(x => x.OrderId == orderId).FirstOrDefault(); var bill = 0; ConsoleTable table = new ConsoleTable("ItemId", "ItemName", "Price", "Quantity", "Amount"); foreach (var items in customerOrder.orderedItemsWithQuantity) { bill += items.ItemModel.Price * items.Quantity; table.AddRow(items.ItemModel.ItemId, items.ItemModel.ItemName, items.ItemModel.Price, items.Quantity, items.ItemModel.Price * items.Quantity); } table.Write(Format.Alternative); return(bill); }
// GET: api/CustomerOrders public IEnumerable <CustomerOrderModel> GetCustomerOrders() { List <CustomerOrderModel> orders = new List <CustomerOrderModel>(); var config = new MapperConfiguration(cfg => cfg.CreateMap <CustomerOrder, CustomerOrderModel>()); var mapper = config.CreateMapper(); foreach (var order in db.CustomerOrders) { CustomerOrderModel model = mapper.Map <CustomerOrderModel>(order); orders.Add(model); } return(orders); }
// GET: CustomerOrder/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } CustomerOrderModel customerOrderModel = db.CustomerOrderModels.Find(id); if (customerOrderModel == null) { return(HttpNotFound()); } return(View(customerOrderModel)); }
public void AddOrder(CustomerOrderModel neworder) { //create new instance of custorder entity and map its values to new order var newdbcustomerorder = new CustomerOrder() { CustomerName = neworder.CustomerName, AmountPurchased = neworder.AmountPurchased, OrderId = neworder.OrderId, ProductId = neworder.ProductId }; _projectZeroContext.Add(newdbcustomerorder); _projectZeroContext.SaveChanges(); }
public void ShowCustomerOrderedItems(int orderId) { Console.WriteLine(); CustomerOrderModel customerOrder = customerOrderModelsList.Where(x => x.OrderId == orderId).FirstOrDefault(); Console.WriteLine("Your Order Details are :"); Console.WriteLine("-------------------------------------------------------------"); ConsoleTable table = new ConsoleTable("ItemId", "ItemName", "Price", "Quantity"); foreach (var items in customerOrder.orderedItemsWithQuantity) { table.AddRow(items.ItemModel.ItemId, items.ItemModel.ItemName, items.ItemModel.Price, items.Quantity); } table.Write(Format.Alternative); }
// GET: CustomerOrder/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } CustomerOrderModel customerOrderModel = db.CustomerOrderModels.Find(id); if (customerOrderModel == null) { return(HttpNotFound()); } ViewBag.CustomerID = new SelectList(db.CustomerModels, "CustomerID", "Name", customerOrderModel.CustomerID); return(View(customerOrderModel)); }
public async Task <IHttpActionResult> GetCustomerOrder(int id) { CustomerOrder customerOrder = await db.CustomerOrders.FindAsync(id); if (customerOrder == null) { return(NotFound()); } var config = new MapperConfiguration(cfg => cfg.CreateMap <CustomerOrder, CustomerOrderModel>()); var mapper = config.CreateMapper(); CustomerOrderModel model = mapper.Map <CustomerOrderModel>(customerOrder); return(Ok(customerOrder)); }
public async Task PostAsync([FromBody] CustomerOrderModel order) { _log.LogInformation("Order received for {description}", order.Description); // Save order to database generating OrderId var orderId = new Random().Next(1, 100); var message = new OrderPlacedEvent { OrderId = orderId, Description = order.Description }; await _publisher.PublishAsync(message); _log.LogInformation("Order {orderId} placed", orderId); }
public HttpResponseMessage GetAllEventOrderList(CustomerOrderModel model) { ResponseStatus response = new ResponseStatus(); //OrderModel data = new OrderModel(); try { if (model.StoreId > 0) { var data = _repository.GetAllEventOrderList(model.StoreId); if (data != null) { //data.OrderId = result.OrderId; //data.OrderNumber = result.OrderNumber; //data.StoreId = (int)result.StoreId; //data.ProductId = (int)result.ProductId; //data.AddressId = (int)result.AddressId; //data.Quantity = (double)result.Quantity; //data.LoginId = (int)result.LoginId; //data.OrderTime = result.OrderTime; //data.TotalPrice = (double)result.TotalPrice; //data.OrderStatus = result.OrderStatus; response.serverResponseTime = System.DateTime.Now; response.isSuccess = true; return(Request.CreateResponse(HttpStatusCode.OK, new { data, response })); } else { response.serverResponseTime = System.DateTime.Now; response.isSuccess = false; return(Request.CreateResponse(HttpStatusCode.BadRequest, new { response })); } } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something Worng !")); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Something Worng !", ex)); } }
public async Task <IHttpActionResult> PutCustomerOrder(CustomerOrderModel model) { var config = new MapperConfiguration(cfg => cfg.CreateMap <CustomerOrderModel, CustomerOrder>()); var mapper = config.CreateMapper(); CustomerOrder order = mapper.Map <CustomerOrder>(model); db.Entry(order).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; } return(StatusCode(HttpStatusCode.NoContent)); }
public void OrderById() { //Arange var orderService = new OrdersService(db); var customerUser = new CustomerUser { Id = "1", FullName = "BHTC" }; var firstOrder = new Order { Id = "0", Name = "firstOrder", CustomerUserId = customerUser.Id, CustomerUser = customerUser }; var secondOrder = new Order { Id = "1", Name = "secondOrder" }; var thirdOrder = new Order { Id = "2", Name = "thirdOrder" }; db.CustomerUser.Add(customerUser); db.Order.AddRange(firstOrder, secondOrder, thirdOrder); db.SaveChanges(); //Act var resultCount = orderService.OrderById("1").Count(); var firstResult = orderService.OrderById("1").First(); //Assert var expected = new CustomerOrderModel { Name = "firstOrder", OrderId = "0", CustomerUserId = "1" }; var expectedResultCount = 1; Assert.Equal(expectedResultCount, resultCount); Assert.Equal(expected.Name, firstResult.Name); Assert.Equal(expected.OrderId, firstResult.OrderId); Assert.Equal(expected.CustomerUserId, firstResult.CustomerUserId); }
/// <summary> /// Create a new order for a given customer at a given store /// </summary> /// <param name="order"></param> /// <param name="customerId"></param> /// <param name="storeId"></param> /// <returns></returns> public virtual async Task AddAsync(CustomerOrderModel order) { var added = mContext.CustomerOrder.Add(new CustomerOrder { CustomerId = order.CustomerId, StoreId = order.StoreId, Timestamp = order.Timestamp, OrderLine = order.OrderLine.Select(o => new OrderLine { ProductId = o.Product.Id, ProductQuantity = o.ProductQuantity }).ToList() }); if (mLogger != null) { mLogger.LogInformation(added.ToString()); } await mContext.SaveChangesAsync(); }
public int InsertCustomerOrder(CustomerOrderModel customerOrderModel, DataTable customerOrderItem) { int insertedId = 0; using (var connection = new SqlConnection(appSettings.GetConnectionString())) { var dynamicParameters = new DynamicParameters(); dynamicParameters.Add("@CustomerOrderItemData", customerOrderItem.AsTableValuedParameter(StoredProcedure.TABLE_TYPE_CUST_ORDER_ITEMDATA)); dynamicParameters.Add("@Id", customerOrderModel.Id); dynamicParameters.Add("@OutletId", customerOrderModel.OutletId); dynamicParameters.Add("@SalesInvoiceNumber", customerOrderModel.SalesInvoiceNumber); dynamicParameters.Add("@CustomerId", customerOrderModel.CustomerId); dynamicParameters.Add("@WaiterEmployeeId", customerOrderModel.WaiterEmployeeId); dynamicParameters.Add("@OrderType", customerOrderModel.OrderType); dynamicParameters.Add("@OrderDate", customerOrderModel.OrderDate); dynamicParameters.Add("@TableId", customerOrderModel.TableId); dynamicParameters.Add("@AllocatedPerson", customerOrderModel.AllocatedPerson); dynamicParameters.Add("@TockenNumber", customerOrderModel.TockenNumber); dynamicParameters.Add("@GrossAmount", customerOrderModel.GrossAmount); dynamicParameters.Add("@DiscountPercentage", customerOrderModel.DiscountPercentage); dynamicParameters.Add("@DiscountAmount", customerOrderModel.DiscountAmount); dynamicParameters.Add("@DeliveryCharges", customerOrderModel.DeliveryCharges); dynamicParameters.Add("@NonVatableAmount", customerOrderModel.NonVatableAmount); dynamicParameters.Add("@VatableAmount", customerOrderModel.VatableAmount); dynamicParameters.Add("@TaxAmount", customerOrderModel.TaxAmount); dynamicParameters.Add("@TotalPayable", customerOrderModel.TotalPayable); dynamicParameters.Add("@CustomerPaid", customerOrderModel.CustomerPaid); dynamicParameters.Add("@CustomerNote", customerOrderModel.CustomerNote); dynamicParameters.Add("@OrderStatus", customerOrderModel.OrderStatus); dynamicParameters.Add("@AnyReason", customerOrderModel.AnyReason); dynamicParameters.Add("@UserIdInserted", customerOrderModel.UserIdInserted); dynamicParameters.Add("@DateInserted", customerOrderModel.DateInserted); dynamicParameters.Add("@KotStatus", customerOrderModel.KotStatus); dynamicParameters.Add("@OrderPrefix", LoginDetail.OrderPrefix); insertedId = connection.Query <int> (StoredProcedure.PX_INSERT_CUSTOMER_ORDER, dynamicParameters, commandType: CommandType.StoredProcedure, commandTimeout: 0).FirstOrDefault(); return(insertedId); } }
public async Task UpdateOrder(CustomerOrderModel order) { HttpClientHandler httpClientHandler = new HttpClientHandler(); httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }; var json = JsonConvert.SerializeObject(order); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); using (var client = new HttpClient(httpClientHandler)) { client.BaseAddress = new Uri(General.BASE_URL + "/"); try { HttpResponseMessage responseMessage = await client.PutAsync("CustomerOrders", content); } catch (Exception e) { throw e; } } }
public ActionResult OrderConfirmation(CustomerOrderModel custOrder) { return(View(custOrder)); }
public ActionResult Index(SnowboardModel sbModel) { Response.Write("Method: POST <br>"); if (sbModel.DiscountSenior && sbModel.DiscountStudent) { ModelState.AddModelError("Discounts", "You annot have both student and senior discounts."); } // return to view if any feilds are invalid if (!ModelState.IsValid) { return(View(sbModel)); } // new custOrder object CustomerOrderModel custOrder = new CustomerOrderModel(); // find board model Boards boardModel = ListBoardsViewModel.BoardList.Find(m => m.ModelId == sbModel.ModelID); // assign model name from boardModel to CustOrder custOrder.ModelName = boardModel.ModelName; // assign model price from boardModel to CustOrder custOrder.ModelPrice = boardModel.Price; // get surcharge from experiences list model Experience expModel = ListExperienceViewModel.ExperienceLevel.Find(m => m.Level == sbModel.ExperienceLevel); // get experieince surcharge percentage custOrder.ExperienceSurchargePercent = expModel.Surcharge; // calculate the surcharge custOrder.ExperienceSurchargeDollars = custOrder.ModelPrice * (1 + expModel.Surcharge); // check for discounts if (sbModel.DiscountStudent) { custOrder.DiscountsTaken += "student, "; custOrder.DiscountsPercent += 0.1; } if (sbModel.DiscountSenior) { custOrder.DiscountsTaken += "senior, "; custOrder.DiscountsPercent += 0.05; } if (sbModel.DiscountGoldClub) { custOrder.DiscountsTaken += "gold club, "; custOrder.DiscountsPercent += 0.08; } // trim list of discounts if (custOrder.DiscountsTaken != null) { custOrder.DiscountsTaken = custOrder.DiscountsTaken.TrimEnd(',', ' '); } // get discount dollar amount custOrder.DiscountDollars = custOrder.ModelPrice * custOrder.DiscountsPercent; // calculate subtotal custOrder.Subtotal = custOrder.ExperienceSurchargeDollars * (1 + custOrder.DiscountsPercent); // get tax rate State stateTax = ListStatesViewModel.StateList.Find(m => m.StateAbbr == sbModel.State); // get tax rate custOrder.TaxPercent = stateTax.TaxRate; // get the tax dollar amount custOrder.TaxDollars = custOrder.Subtotal * custOrder.TaxPercent; // calculate total price custOrder.TotalPrice = custOrder.Subtotal * (1 + stateTax.TaxRate); return(View("OrderConfirmation", custOrder)); }
private async System.Threading.Tasks.Task ConfirmAsync(DeliveryApiModel delivery, DriverApiModel driver, CustomerOrderModel order, OrderStatusModel completedStatus) { // Delivery delivery.Status = "Completed"; delivery.ConfirmationType = "Confirmed by QR Scan"; delivery.TimeDelivered = DateTime.Now; // Driver driver.Status = "Active"; // Order order.OrderStatus = completedStatus; order.OrderStatusId = completedStatus.Id; await deliveryLogic.UpdateDelivery(delivery); await driverLogic.UpdateDriver(driver); await orderLogic.UpdateOrder(order); }
public static CustomerOrderModel PrepareCustomerOrderModel(this Order order) { var priceFormatter = EngineContext.Current.Resolve <IPriceFormatter>(); var model = new CustomerOrderModel { Id = order.Id, OrderTotal = priceFormatter.FormatValue(order.GrandTotal, order.CurrencyCode), CreatedOn = order.OrderPlaced.Value, OrderStatusCode = order.StatusCode, OrderStatus = order.OrderStatus }; // To avoid customer frustration, ON HOLD will be changed to ORDER PLACED if (model.OrderStatusCode == OrderStatusCode.ON_HOLD) { var orderService = EngineContext.Current.Resolve <IOrderService>(); model.OrderStatusCode = OrderStatusCode.ORDER_PLACED; model.OrderStatus = orderService.GetOrderStatusByCode(OrderStatusCode.ORDER_PLACED); } var orderItems = order.LineItemCollection.Where(x => ValidLineStatus.VALID_LINE_STATUSES.Contains(x.StatusCode)).ToList(); foreach (var item in orderItems) { var itemModel = new LineItemModel { Name = item.Name, Option = item.Option, Quantity = item.Quantity, UnitPrice = priceFormatter.FormatValue(item.PriceInclTax * item.ExchangeRate, item.CurrencyCode), Subtotal = priceFormatter.FormatValue(item.PriceInclTax * item.Quantity * item.ExchangeRate, item.CurrencyCode) }; model.Items.Add(itemModel); } model.Totals.Subtotal = priceFormatter.FormatValue(orderItems.Select(x => (x.PriceInclTax * x.Quantity * x.ExchangeRate)).Sum(), order.CurrencyCode); model.Totals.Discount = order.DiscountAmount > 0M ? priceFormatter.FormatValue(order.DiscountAmount, order.CurrencyCode) : null; model.Totals.UsedPointsAmount = order.AllocatedPoint > 0 ? priceFormatter.FormatValue(order.AllocatedPoint / 100M * order.ExchangeRate, order.CurrencyCode) : null; model.Totals.UsedPoints = order.AllocatedPoint; model.Totals.ShippingCost = priceFormatter.FormatValue(order.ShippingCost * order.ExchangeRate, order.CurrencyCode); model.Totals.VAT = priceFormatter.FormatValue(orderItems.Select(x => ((x.PriceInclTax - x.PriceExclTax) * x.Quantity * x.ExchangeRate)).Sum(), order.CurrencyCode); model.Totals.VATMessage = order.ShippingCountry.IsEC ? "included" : "discount"; // Some orders may not have billing address if (order.Country != null) { model.Billing = new AddressModel { Name = order.BillTo, AddressLine1 = order.AddressLine1, AddressLine2 = order.AddressLine2, City = order.City, CountryName = order.Country.Name, PostCode = order.PostCode }; } if (order.ShippingCountry != null) { model.Shipping = new AddressModel { Name = order.ShipTo, AddressLine1 = order.ShippingAddressLine1, AddressLine2 = order.ShippingAddressLine2, City = order.ShippingCity, CountryName = order.ShippingCountry.Name, PostCode = order.ShippingPostCode }; } // Check if the order is valid for invoice download model.IsAllowedToDownloadInvoice = ValidOrderStatus.VALID_STATUSES.Contains(order.StatusCode); return(model); }
public ResponseModel UploadCustomerOrder(System.Web.HttpRequest httpRequest, string rootPath) { ResponseModel res = new ResponseModel(); try { if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { HttpPostedFile fileUploaded = httpRequest.Files[file]; string fileName = UtilityHelper.SaveUploadedFile(fileUploaded, rootPath); string filePath = Path.Combine(rootPath, fileName); if (fileName != "") { using (var reader = new StreamReader(filePath)) using (var csv = new CsvReader(reader)) { int rowCnt = 0; var record = new CustomerOrderModel(); var records = csv.EnumerateRecords(record); using (CustomerDBEntities db = new CustomerDBEntities()) { FileStorageInfo fileInfo = new FileStorageInfo(); fileInfo.FileUploadId = Guid.NewGuid(); fileInfo.OriginalFileName = fileUploaded.FileName; fileInfo.StoredFileName = fileName; fileInfo.CreatedDate = DateTime.Now; db.FileStorageInfoes.Add(fileInfo); db.SaveChanges(); foreach (var r in records) { TempCustomerOrder tmpOrder = new TempCustomerOrder(); tmpOrder.ID = Guid.NewGuid(); tmpOrder.order_number = r.order_number; tmpOrder.qty = r.qty; tmpOrder.user_id = r.user_id; tmpOrder.FileUploadedId = fileInfo.FileUploadId; tmpOrder.CreatedDate = DateTime.Now; tmpOrder.IsAddedToMainTbl = false; db.TempCustomerOrders.Add(tmpOrder); db.SaveChanges(); rowCnt++; } } if (rowCnt > 0) { //Upsert Customer Order Data from Staginig table to Main Table res = UpsertOrderData(); if (res.status) { res.status = true; res.message = "File Upload Completed Successfully...!!!"; res.data = GetAllCustomerOrders(); } return(res); } else { res.message = "No/Invalid Data in File...!!!"; return(res); } } } } } return(res); } catch (Exception ex) { if (ex.Source == "CsvHelper") { res.message = "Invalid File Data...!!!"; } else { res.message = ex.Message; } res.data = ex.InnerException; return(res); } }