public void Init() { i1 = new StockItem ("BMAC56790", "Propelling Pencil", "Supply Master", "1.49", "10", "20"); stock_list = new Stock(); stock_list.AddStockItem(i1.StockCode, i1); order_history = new OrderHistory(); DateTime timestamp = DateTime.Now; o1 = new Order (timestamp, i1.StockCode, i1.Supplier, 10, 10); order_history.AddOrder (o1); }
public int UpdateOrderHistory(OrderHistory A) { try { db.Entry(A).State = EntityState.Modified; return db.SaveChanges(); } catch (Exception e) { throw new Exception(e.Message); } }
public int DeleteOrderHistory(OrderHistory C) { try { db.Entry(C).State = EntityState.Deleted; return db.SaveChanges(); } catch (Exception e) { throw new Exception(e.Message); } }
public int CreateOrderHistory(OrderHistory A) { try { db.OrderHistories.Add(A); return db.SaveChanges(); } catch (Exception e) { throw new Exception(e.Message); } }
public OrderHistory GetStatus() { OrderHistory history = new OrderHistory(); try { history = this.history.OrderByDescending(x => x.dateAdded).First(); } catch { history = new OrderHistory { OrderStatus = new OrderStatus { status = "Unknown" }, }; } return history; }
public IList <OrderHistory> LoadByOrderId(int OrderId) { IList <OrderHistory> Users = new List <OrderHistory>(); DbCommand cmd = CreateCommand("UP_ORDERHISTORY_GETBYORDERID"); AddParameter(cmd, "@ORDER_ID", DbType.Int16, OrderId); cmd.Connection.Open(); try { DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (reader.Read()) { OrderHistory u = new OrderHistory(); PopulateDomain(reader, u); Users.Add(u); } } finally { CloseCommand(cmd); } return(Users); }
internal void AddHistoryRecordToDatabase() { OrderHistory history = new OrderHistory() { Id = Guid.NewGuid(), OrderTime = DateTime.Now, Address = AddressTextBox.Text, OrderMessage = NotesTextBox.Text, CustomerName = $"{FirstNameTextBox.Text} {LastNameTextBox.Text}" }; try { using (AppDBContext db = new AppDBContext()) { db.OrderHistory.Add(history); db.SaveChanges(); } } catch (Exception) { MessageBox.Show(UserMessages.DatabaseRecordNotAdded, WindowsTypes.Information, MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public async Task <List <OrderHistory> > GetOrderDetailsAsync() { var uname = Preferences.Get("Username", "Invite"); var orders = (await client.Child("Orders").OnceAsync <Order>()).Where(o => o.Object.Username.Equals(uname)).Select(o => new Order { OrderId = o.Object.OrderId, ReceiptId = o.Object.ReceiptId, TotalCost = o.Object.TotalCost }).ToList(); foreach (var order in orders) { OrderHistory oh = new OrderHistory(); oh.OrderId = order.OrderId; oh.ReceiptId = order.ReceiptId; oh.TotalCost = order.TotalCost; var orderDetails = (await client.Child("OrderDetails").OnceAsync <OrderDetails>()) .Where(o => o.Object.Equals(order.OrderId)) .Select(o => new OrderDetails { OrderId = o.Object.OrderId, OrderDetailId = o.Object.OrderDetailId, Price = o.Object.Price, ProductID = o.Object.ProductID, ProductName = o.Object.ProductName, Quantity = o.Object.Quantity }).ToList(); oh.AddRange(orderDetails); UserOrders.Add(oh); } return(UserOrders); }
public void save(SalesOrder dbitem) { dbitem.DateStatus = DateTime.Now; var order_history = new OrderHistory(); if (dbitem.Id == 0) //create { context.SalesOrder.Add(dbitem); } else { context.SalesOrder.Attach(dbitem); if (dbitem.Status == "save") { var last_oh = context.OrderHistory.Where(d => d.SalesOrderId == dbitem.Id && d.StatusFlow == 1).FirstOrDefault(); if (last_oh == null) { order_history = new OrderHistory { SalesOrderId = dbitem.Id, StatusFlow = 1, FlowDate = DateTime.Now, SavedAt = DateTime.Now, ProcessedAt = DateTime.Now, PIC = dbitem.UpdatedBy } } ; else { order_history = new OrderHistory { SalesOrderId = dbitem.Id, StatusFlow = 1, FlowDate = DateTime.Now, SavedAt = last_oh.SavedAt, ProcessedAt = DateTime.Now, PIC = dbitem.UpdatedBy } }; } context.OrderHistory.Add(order_history); var entry = context.Entry(dbitem); entry.State = EntityState.Modified; } dbitem.DateStatus = DateTime.Now; context.SaveChanges(); }
public async Task <IActionResult> OrderHistory() { var user = await _userManager.GetUserAsync(User); UserOrders userOrders = new UserOrders() { Orders = new List <OrderHistory>() }; foreach (var partialOrder in _context.PartialOrder.Where(order => user.Id == order.UserId) .GroupBy(order => order.OrderId) .Select(g => g.First())) { List <Product> orderedProducts = new List <Product>(); foreach (var pOrder in _context.PartialOrder.Where(order => partialOrder.OrderId == order.OrderId)) { Product tempProd = _context.Products.Where(p => pOrder.ProductId == p.Id).First(); tempProd.Amount = pOrder.Amount; orderedProducts.Add(tempProd); } OrderHistory orderHistory = new OrderHistory() { OrderId = partialOrder.OrderId, Price = partialOrder.Price, Date = partialOrder.Date, Orders = orderedProducts }; userOrders.Orders.Add(orderHistory); } return(View(userOrders)); }
public async Task <JsonResult> Action(int ID, int?orderStatus, string note) { JsonResult result = new JsonResult(); if (ID > 0 && orderStatus.HasValue && !string.IsNullOrEmpty(note)) { var order = OrdersService.Instance.GetOrderByID(ID); if (order != null) { var orderHistory = new OrderHistory() { OrderID = order.ID, OrderStatus = orderStatus.Value, Note = note, ModifiedOn = DateTime.Now }; var dbOperation = OrdersService.Instance.AddOrderHistory(orderHistory); if (dbOperation) { result.Data = new { Success = true }; if (!order.IsGuestOrder) { //send order placed notification email await UserManager.SendEmailAsync(order.CustomerID, EmailTextHelpers.OrderStatusUpdatedEmailSubject(AppDataHelper.CurrentLanguage.ID, order.ID, orderStatus.Value), EmailTextHelpers.OrderStatusUpdatedEmailBody(AppDataHelper.CurrentLanguage.ID, order.ID, orderStatus.Value, Url.Action("Tracking", "Orders", new { area = "", orderID = order.ID }, protocol: Request.Url.Scheme))); } return(result); } } } result.Data = new { Success = false, Message = "Dashboard.OrderDetails.UpdateStatus.Validation.UnableToUpdateOrderStatus".LocalizedString() }; return(result); }
private static async Task SearchEngineMatch(UserSettingsView settings, int rptNumber, int minSold, int daysBack, int?minPrice, int?maxPrice, bool?activeStatusOnly, bool?isSellerVariation, string itemID, double pctProfit, decimal wmShipping, decimal wmFreeShippingMin, double eBayPct, int imgLimit, string supplierTag) { string loopItemID = null; bool found = false; try { var mv = new ModelViewTimesSold(); mv.TimesSoldRpt = FilterMatch(settings, rptNumber, minSold, daysBack, minPrice, maxPrice, activeStatusOnly, isSellerVariation, itemID); // Only search where MatchCount is null or does not equal 1 mv.TimesSoldRpt = mv.TimesSoldRpt.Where(p => !p.MatchCount.HasValue || (p.MatchCount.HasValue && p.MatchCount.Value != 1)).ToList(); foreach (var row in mv.TimesSoldRpt) { loopItemID = row.ItemID; if (loopItemID == "392388202275") { var stop = 999; } ISupplierItem walitem; string descr = row.Description; found = false; // Search sections of description since most search engines only use first part of query anyway for (int i = 0; i < 5; i++) { string section = GetDescrSection(descr, i); if (!string.IsNullOrEmpty(section)) { section = supplierTag + " " + section; //var links = dsutil.DSUtil.BingSearch(section); var links = dsutil.DSUtil.GoogleSearchSelenium(section); var validLinks = wallib.wmUtility.ValidURLs(links); // just get supplier links if (validLinks.Count > 0) { // Collect valid supplier links from search engine result foreach (string supplierURL in validLinks) { walitem = await wallib.wmUtility.GetDetail(supplierURL, imgLimit, false); if (walitem != null) { // If can't get supplier pics, not much point in posting. // Can happen when not matching correctly on something like an eBook or giftcard where walmart // is not providing "standard" images. (error is logged in GetDetail()). if (!string.IsNullOrEmpty(walitem.SupplierPicURL)) { if (!string.IsNullOrEmpty(walitem.ItemID) || !string.IsNullOrEmpty(walitem.UPC) || !string.IsNullOrEmpty(walitem.MPN)) { found = true; walitem.Updated = DateTime.Now; _repository.SupplierItemUpdateByID(walitem, "Updated", "ItemURL", "SoldAndShippedBySupplier", "SupplierBrand", "SupplierPrice", "IsVariation", "SupplierPicURL", "IsFreightShipping"); var oh = new OrderHistory(); oh.ItemID = row.ItemID; oh.MatchCount = 1; oh.MatchType = 3; oh.SourceID = walitem.SourceID; oh.SupplierItemID = walitem.ID; if (walitem.SupplierPrice.HasValue) { var p = wallib.wmUtility.wmNewPrice(walitem.SupplierPrice.Value, pctProfit, wmShipping, wmFreeShippingMin, eBayPct); oh.ProposePrice = p.ProposePrice; _repository.OrderHistoryUpdate(oh, "ProposePrice", "MatchType", "MatchCount", "SourceID", "SupplierItemID"); } else { _repository.OrderHistoryUpdate(oh, "MatchType", "MatchCount", "SourceID", "SupplierItemID"); } } } if (found) { break; } } } } } if (found) { break; } } } } catch (Exception exc) { string msgItemID = (!string.IsNullOrEmpty(loopItemID)) ? "ItemID: " + loopItemID : ""; string header = "SearchEngineMatch RptNumber: " + rptNumber.ToString() + " " + msgItemID; string msg = dsutil.DSUtil.ErrMsg(header, exc); dsutil.DSUtil.WriteFile(_logfile, msg, ""); } }
public async Task <IActionResult> TicketBought(string CustEmail, int id) //See this when ticket is bought { OrderHistory order = new OrderHistory() { CustomerEmail = CustEmail, EventID = id }; _context.OrderHistories.Add(order); _context.SaveChanges(); string UserId = User.FindFirstValue(ClaimTypes.NameIdentifier); string email = (from u in _context.ApplicationUser where u.Id == UserId select u.Email).FirstOrDefault(); var @event = await _context.Events .SingleOrDefaultAsync(m => m.EventID == id); if (@event == null) { return(NotFound()); } var query = (from events in _context.Events where events.EventID == id select events); foreach (Event events in query) { if (events.AvailableTickets > 0) { events.AvailableTickets = events.AvailableTickets - 1; } } try { _context.SaveChanges(); } catch (Exception e) { Console.WriteLine(e); } var message = new MimeMessage(); message.From.Add(new MailboxAddress("TicketShop", "*****@*****.**")); message.To.Add(new MailboxAddress(email, email)); message.Subject = "Order confirmation"; message.Body = new TextPart("plain") { Text = "Thank you for buying " + @event.Eventname.ToString() + " You can find the detailed information about you ticket on your Order History page" }; using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.Authenticate("*****@*****.**", "Ticketshop123!"); client.Send(message); client.Disconnect(true); } return(View(@event)); }
public Response Put([FromBody] OrderHistory value) { return(repo.Update(value)); }
public StockControl(Stock stock_list) { this.stock_list = stock_list; order_history = new OrderHistory (); }
public void LogOrder(IOrderDetails order) { OrderHistory.Push(order); }
public void SetOrderHistory(Order order) { OrderHistory.Add(order); }
protected void Page_Load(object sender, EventArgs e) { string aAccount = Request.QueryString["Account"]; //語法 string aStr = "Select * FROM BuyData WHERE UserAccount = '{0}' order by RecTime Desc"; aStr = string.Format(aStr, aAccount); //準備連線 using (SqlConnection aCon = new SqlConnection("Data Source=184.168.47.10;Integrated Security=False;User ID=MobileDaddy;PASSWORD=Aa54380438!;Connect Timeout=15;Encrypt=False;Packet Size=4096")) { //連線成功打開 aCon.Open(); //準備要做的事情 using (SqlCommand aComm = new SqlCommand(aStr, aCon)) { //讀檔 SqlDataReader aDataReader = aComm.ExecuteReader(); List <OrderHistory> ListData = new List <OrderHistory>(); int[] OrderTotalMoney; while (aDataReader.Read()) { OrderHistory aData = new OrderHistory(); aData.ProductID = aDataReader["ProductID"].ToString(); aData.ProductCount = aDataReader["ProductCount"].ToString(); aData.SingleNumber = aDataReader["SingleNumber"].ToString(); aData.RecTime = aDataReader["RecTime"].ToString(); ListData.Add(aData); } //這個LIST有所有這個玩家的資料。要分成 A.單號 (Only One) ListData==(Total) List <OrderHistory> aList = new List <OrderHistory>(); bool Insert = true; for (int i = 0; i < ListData.Count; i++) { //如果沒有資料,就塞第一筆資料進去 if (aList.Count == 0) { aList.Add(ListData[i]); } //開始判斷要塞進去的資料跟已經存起來的資料是否相同 for (int j = 0; j < aList.Count; j++) { if (aList[j].SingleNumber == ListData[i].SingleNumber) { //如果有一筆資料相同的話, Insert = false; } } if (Insert != false) { aList.Add(ListData[i]); } Insert = true; } OrderTotalMoney = new int[aList.Count]; //塞總金額 for (int i = 0; i < aList.Count; i++) { for (int j = 0; j < ListData.Count; j++) { if (aList[i].SingleNumber == ListData[j].SingleNumber) { OrderTotalMoney[i] += GetTotalPrice(ListData[j]); } } } string jsonData = ""; ProductData bData = new ProductData(); //要先塞一筆ALIST的資料。在塞入LISTDATA 相對應的資料。 for (int i = 0; i < aList.Count; i++) { jsonData += BaseStr; jsonData += string.Format(CreateString, aList[i].SingleNumber, aList[i].RecTime, aList[i].ProductID, OrderTotalMoney[i].ToString(), ""); jsonData += EndStr; jsonData += string.Format(SliderTop, aList[i].SingleNumber); for (int j = 0; j < ListData.Count; j++) { if (aList[i].SingleNumber == ListData[j].SingleNumber) { bData = GetData(ListData[j]); jsonData += string.Format(SliderStr, bData.ProductName, ListData[j].ProductCount, bData.TotalPrice, "", ""); } } jsonData += EndStr; jsonData += SlidetEnd; jsonData += string.Format(SlidetBtn, aList[i].SingleNumber); } Response.Write(jsonData); } } }
public override int GetHashCode() { int hashCode = 820864276; if (Context != null) { hashCode += Context.GetHashCode(); } if (Errors != null) { hashCode += Errors.GetHashCode(); } if (Id != null) { hashCode += Id.GetHashCode(); } if (BuyerEmail != null) { hashCode += BuyerEmail.GetHashCode(); } if (RecipientName != null) { hashCode += RecipientName.GetHashCode(); } if (RecipientPhoneNumber != null) { hashCode += RecipientPhoneNumber.GetHashCode(); } if (State != null) { hashCode += State.GetHashCode(); } if (ShippingAddress != null) { hashCode += ShippingAddress.GetHashCode(); } if (SubtotalMoney != null) { hashCode += SubtotalMoney.GetHashCode(); } if (TotalShippingMoney != null) { hashCode += TotalShippingMoney.GetHashCode(); } if (TotalTaxMoney != null) { hashCode += TotalTaxMoney.GetHashCode(); } if (TotalPriceMoney != null) { hashCode += TotalPriceMoney.GetHashCode(); } if (TotalDiscountMoney != null) { hashCode += TotalDiscountMoney.GetHashCode(); } if (CreatedAt != null) { hashCode += CreatedAt.GetHashCode(); } if (UpdatedAt != null) { hashCode += UpdatedAt.GetHashCode(); } if (ExpiresAt != null) { hashCode += ExpiresAt.GetHashCode(); } if (PaymentId != null) { hashCode += PaymentId.GetHashCode(); } if (BuyerNote != null) { hashCode += BuyerNote.GetHashCode(); } if (CompletedNote != null) { hashCode += CompletedNote.GetHashCode(); } if (RefundedNote != null) { hashCode += RefundedNote.GetHashCode(); } if (CanceledNote != null) { hashCode += CanceledNote.GetHashCode(); } if (Tender != null) { hashCode += Tender.GetHashCode(); } if (OrderHistory != null) { hashCode += OrderHistory.GetHashCode(); } if (PromoCode != null) { hashCode += PromoCode.GetHashCode(); } if (BtcReceiveAddress != null) { hashCode += BtcReceiveAddress.GetHashCode(); } if (BtcPriceSatoshi != null) { hashCode += BtcPriceSatoshi.GetHashCode(); } return(hashCode); }
public async Task AddOrderAsync(Users currentUser, OrderHistory order, OrderDetails details) { await Task.Run(() => AddOrder(currentUser, order, details)); }
public async Task ModifyOrderAsync(OrderHistory modifiedOrder) { await Task.Run(() => ModifyOrder(modifiedOrder)); }
public int AddOrder(OrderHistory order) { return(_foodDataAccess.AddOrder(order)); }
public ActionResult CompleteOrder() { //finalize the order from cart //shopping cart data int Locationid = int.Parse(HttpContext.Request.Cookies["LocationID"]); int customerid = int.Parse(HttpContext.Request.Cookies["CustomerID"]); int ProductID1 = int.Parse(HttpContext.Request.Cookies["ProID1"]); int ProductID2 = int.Parse(HttpContext.Request.Cookies["ProID2"]); int ProductID3 = int.Parse(HttpContext.Request.Cookies["ProID3"]); int ProductID4 = int.Parse(HttpContext.Request.Cookies["ProID4"]); int ProductID5 = int.Parse(HttpContext.Request.Cookies["ProID5"]); int Amount1 = int.Parse(HttpContext.Request.Cookies["PA1"]); int Amount2 = int.Parse(HttpContext.Request.Cookies["PA2"]); int Amount3 = int.Parse(HttpContext.Request.Cookies["PA3"]); int Amount4 = int.Parse(HttpContext.Request.Cookies["PA4"]); int Amount5 = int.Parse(HttpContext.Request.Cookies["PA5"]); //New Order History OrderHistory orderHistory = new OrderHistory { LocationId = Locationid, CustomerId = customerid }; _orderhistoryRepo.Create(orderHistory); //The new Order ID int orderid = _orderhistoryRepo.GetAll().Count(); //note to self, compress next step into dynamic //new orders if (ProductID1 == 1) { Inventory inventory1 = new Inventory { LocationId = Locationid, ProductId = ProductID1, Amount = Amount1 }; Orders orders1 = new Orders { OrderID = orderid, ProductID = ProductID1, Amount = Amount1 }; //finalize _inventoryRepo.Update(inventory1); _ordersRepo.Create(orders1); } if (ProductID2 == 2) { Inventory inventory2 = new Inventory { LocationId = Locationid, ProductId = ProductID2, Amount = Amount2 }; Orders orders2 = new Orders { OrderID = orderid, ProductID = ProductID2, Amount = Amount2 }; //finalize _inventoryRepo.Update(inventory2); _ordersRepo.Create(orders2); } if (ProductID3 == 3) { Inventory inventory3 = new Inventory { LocationId = Locationid, ProductId = ProductID3, Amount = Amount3 }; Orders orders3 = new Orders { OrderID = orderid, ProductID = ProductID3, Amount = Amount3 }; //finalize _inventoryRepo.Update(inventory3); _ordersRepo.Create(orders3); } if (ProductID4 == 4) { Inventory inventory4 = new Inventory { LocationId = Locationid, ProductId = ProductID4, Amount = Amount4 }; Orders orders4 = new Orders { OrderID = orderid, ProductID = ProductID4, Amount = Amount4 }; //finalize _inventoryRepo.Update(inventory4); _ordersRepo.Create(orders4); } if (ProductID5 == 5) { Inventory inventory5 = new Inventory { LocationId = Locationid, ProductId = ProductID5, Amount = Amount5 }; Orders orders5 = new Orders { OrderID = orderid, ProductID = ProductID5, Amount = Amount5 }; //finalize _inventoryRepo.Update(inventory5); _ordersRepo.Create(orders5); } return(RedirectToAction(nameof(Index))); }
public async Task <bool> MakeOrderAsync(/*string name, string emailAddress*/ OrderData data) { //OrderData: [email protected], adresa, [{id=1], {id=4}], quantity bool isCreated = true; /* * * * * String orderId = Guid.NewGuid().ToString(); * MakeOder(OrderData data){ * foreach(products in data.products){ * * OrderHistory order = new OrderHistory * { * Id = Guid.NewGuid().ToString(), * OrderId = orderId, * CompleteName = DATA.name, * EmailAddress = emailAddress, * EquipmentId = products.id, * Quantity = products.quantity * * * }; * _orderHistoryRepository.Create(order); * } * } */ String orderId = Guid.NewGuid().ToString(); int totalPrice = 0; foreach (OrderProduct products in data.Products) { totalPrice = totalPrice + products.Price * int.Parse(products.Quantity); } int saleTotal = totalPrice - (25 * totalPrice) / 100; foreach (OrderProduct products in data.Products) { OrderHistory order = new OrderHistory { Id = Guid.NewGuid().ToString(), OrderId = orderId, CompleteName = data.Name, EmailAddress = data.Email, EquipmentId = products.Id, ProductQuantity = products.Quantity, DeliveryAddress = data.DeliveryAddress, TotalPrice = totalPrice, }; _orderHistoryRepository.Create(order); } string tableContent = ""; string tableHead = "<table><tr><th>Product Name</th><th></th><th>Measure</th><th>Quantity</th><th>Price</th></tr>"; string tableEnd = "</table>"; string totalTableVoucherPrice = "<br></br><br></br><table><tr><th></th><th>Total Price</th></tr>" + "<tr><td>TOTAL ORDER</td><td>" + totalPrice.ToString() + " RON" + "</td></tr><tr><td>-25% OFF VOUCHER</td><td>" + saleTotal + " RON" + "</td></tr><tr><td>EXPRESS COURIER DELIVERY</td><td> 10 RON </td></tr><tr><td>TOTAL ORDER VALUE</td><td>" + (saleTotal + 10).ToString() + " RON" + "</td></tr></table>"; string totalTablePrice = "<br></br><br></br><table><tr><th></th><th>Total Price</th></tr><tr><td>EXPRESS COURIER DELIVERY</td><td> 10 RON </td></tr>" + "<tr><td>TOTAL ORDER</td><td>" + totalPrice.ToString() + " RON" + "</td></tr><tr><td>TOTAL ORDER VALUE</td><td>" + (totalPrice + 10).ToString() + " RON" + "</td></tr></table>"; string details = "<br></br><br></br>Your products will be delivered in a maximum of 2-3 working days by express courier." + "<br></br><br></br>" + "The order was registered in the name of " + data.Name + " and the delivery address is " + data.DeliveryAddress + "." + "<br></br><br></br>" + "Before delivery, the courier will contact you at the number " + data.PhoneNumber + "." + "<br></br><br></br>" + "Do not hesitate to contact us in case of any questions or problems, thank you for the order you made on our site, " + "<br></br><br></br>" + "Just Move Team ."; foreach (OrderProduct products in data.Products) { tableContent = tableContent + "<tr><td>" + products.Name + "</td>" + "<td>" + "<p><img src='" + products.Image + "'</p> " + "</td>" + "<td> " + products.Measure + "</td>" + "<td> " + products.Quantity + "</td>" + "<td> " + products.Price + " RON" + "</td></tr>"; } if (data.AppliedVoucher == true) { string message = "Dear " + data.Name + ", your order on our website has been registered." + "<br></br><br></br>" + "Your order summary is:" + "<br></br><br></br>" + tableHead + tableContent + tableEnd + totalTableVoucherPrice + details; await _emailSender.SendEmailAsync(data.Email /*"*****@*****.**"*/, "Order Confirmation", message); } else { string message = "Dear " + data.Name + ", your order on our website has been registered." + "<br></br><br></br>" + "Your order summary is:" + "<br></br><br></br>" + tableHead + tableContent + tableEnd + totalTablePrice + details; await _emailSender.SendEmailAsync(data.Email /*"*****@*****.**"*/, "Order Confirmation", message); } /* OrderHistory order = new OrderHistory * { * Id = Guid.NewGuid().ToString(), * * CompleteName = name, * * EmailAddress = emailAddress * * * }; * _orderHistoryRepository.Create(order);*/ return(isCreated); }
public async Task <IActionResult> Buy() { var claimsIdentity = (ClaimsIdentity)this.User.Identity; var claim = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier); var gotuserId = claim.Value; //Get the current users cart var getcart = _context.Cart.Where(m => m.User_Id == gotuserId); var getordernummer = _context.OrderHistory.Where(m => m.User_Id == gotuserId); string product = ""; int totaalprijs = 0; Boolean empty = true; var voorraadproduct = ""; var naamproduct = ""; //Loop all items from the cart in the OrderHistory model foreach (var item in getcart) { string items; items = item + item.Model_naam; OrderHistory order = new OrderHistory { User_Id = gotuserId, Product_Id = item.Product_Id, Model_naam = item.Model_naam, Prijs = item.Prijs, Aantal = item.Aantal, Status = "Besteld", Order_nummer = _context.OrderHistory.Count().ToString() }; switch (item.Model_naam) { case "Kabel": var getkabel = _context.Kabels.Where(m => m.Id == item.Product_Id && item.Model_naam == "Kabel"); voorraadproduct = getkabel.First().Aantal.ToString(); naamproduct = getkabel.First().Naam.ToString(); var checkkabel = getkabel.First().Aantal - item.Aantal; if (checkkabel >= 0) { getkabel.First().Aantal = getkabel.First().Aantal - item.Aantal; getkabel.First().Aantal_gekocht = getkabel.First().Aantal_gekocht + item.Aantal; product = product + getkabel.First().Naam + ","; totaalprijs = totaalprijs + getkabel.First().Prijs; empty = false; } else { empty = true; } break; case "Drone": var getdrone = _context.Drones.Where(m => m.Id == item.Product_Id && item.Model_naam == "Drone"); voorraadproduct = getdrone.First().Aantal.ToString(); naamproduct = getdrone.First().Naam.ToString(); var checkdrone = getdrone.First().Aantal - item.Aantal; if (checkdrone >= 0) { getdrone.First().Aantal = getdrone.First().Aantal - item.Aantal; getdrone.First().Aantal_gekocht = getdrone.First().Aantal_gekocht + item.Aantal; product = product + getdrone.First().Naam + ","; totaalprijs = totaalprijs + getdrone.First().Prijs; empty = false; } else { empty = true; } break; case "Spelcomputer": var getspelcomputer = _context.Spelcomputers.Where(m => m.Id == item.Product_Id && item.Model_naam == "Spelcomputer"); voorraadproduct = getspelcomputer.First().Aantal.ToString(); naamproduct = getspelcomputer.First().Naam.ToString(); var checkspelcomputer = getspelcomputer.First().Aantal - item.Aantal; if (checkspelcomputer >= 0) { getspelcomputer.First().Aantal = getspelcomputer.First().Aantal - item.Aantal; getspelcomputer.First().Aantal_gekocht = getspelcomputer.First().Aantal_gekocht + item.Aantal; product = product + "," + getspelcomputer.First().Naam; totaalprijs = totaalprijs + getspelcomputer.First().Prijs; empty = false; } else { empty = true; } break; case "Horloge": var gethorloge = _context.Horloges.Where(m => m.Id == item.Product_Id && item.Model_naam == "Horloge"); voorraadproduct = gethorloge.First().Aantal.ToString(); naamproduct = gethorloge.First().Naam.ToString(); var checkhorloge = gethorloge.First().Aantal - item.Aantal; if (checkhorloge >= 0) { gethorloge.First().Aantal = gethorloge.First().Aantal - item.Aantal; gethorloge.First().Aantal_gekocht = gethorloge.First().Aantal_gekocht + item.Aantal; product = product + gethorloge.First().Naam + ","; totaalprijs = totaalprijs + gethorloge.First().Prijs; empty = false; } else { empty = true; } break; case "Fotocamera": var getfotocamera = _context.Fotocameras.Where(m => m.Id == item.Product_Id && item.Model_naam == "Fotocamera"); voorraadproduct = getfotocamera.First().Aantal.ToString(); naamproduct = getfotocamera.First().Naam.ToString(); var checkfotocamera = getfotocamera.First().Aantal - item.Aantal; if (checkfotocamera >= 0) { getfotocamera.First().Aantal = getfotocamera.First().Aantal - item.Aantal; getfotocamera.First().Aantal_gekocht = getfotocamera.First().Aantal_gekocht + item.Aantal; product = product + getfotocamera.First().Naam + ","; totaalprijs = totaalprijs + getfotocamera.First().Prijs; empty = false; } else { empty = true; } break; case "Schoen": var getschoen = _context.Schoenen.Where(m => m.Id == item.Product_Id && item.Model_naam == "Schoen"); naamproduct = getschoen.First().Naam.ToString(); voorraadproduct = getschoen.First().Aantal.ToString(); var checkschoen = getschoen.First().Aantal - item.Aantal; if (checkschoen >= 0) { getschoen.First().Aantal = getschoen.First().Aantal - item.Aantal; getschoen.First().Aantal_gekocht = getschoen.First().Aantal_gekocht + item.Aantal; product = product + getschoen.First().Naam + ","; totaalprijs = totaalprijs + getschoen.First().Prijs; empty = false; } else { empty = true; } break; default: Console.WriteLine("Error"); break; } if (empty == false) { _context.OrderHistory.Add(order); } else { return(RedirectToAction("Cart", new { popup = "De voorraad van " + naamproduct + " is helaas " + voorraadproduct + ", bestel een kleiner aantal van dit product!" })); } } if (empty == false) { var ordernummer = _context.OrderHistory.Count().ToString(); _context.Cart.RemoveRange(getcart); await _context.SaveChangesAsync(); var totaal = from item in _context.OrderHistory where item.User_Id == gotuserId && item.Order_nummer == ordernummer group item by item.User_Id into items select new { Totaal = items.Sum(x => x.Prijs * x.Aantal) }; var realtotaal = 0; foreach (var item in totaal) { realtotaal = item.Totaal; } await _emailSender.SendEmailAsync($"{claimsIdentity.Name}", $"Aankoopbevestiging van order: {ordernummer} ", $"Beste meneer/mevrouw, <br> <br>Uw order met order nummer {ordernummer} is bevestigd en zal verzonden worden! <br> <br> Besteld product: {product} <br/> Totaal prijs: {realtotaal} <br> <br> Met vriendelijke groet, <br> Shipped.nl"); return(RedirectToAction("Cart", new { popup = "Uw bestelling is met succes geplaatst! Bekijk uw mail of de ordergeschiedenis voor meer informatie!" })); } return(RedirectToAction("Cart", new { popup = "De voorraad van " + naamproduct + "is " + voorraadproduct + ", koop een kleiner aantal van dit product" })); }
public int DeleteOrderHistory(int Id) { OrderHistory order = db.OrderHistories.Where(u => u.ID == Id).FirstOrDefault(); return(DeleteOrderHistory(order)); }
public static IOrderHistory ToOrderHistoryDomain(this OrderFullContract src) { var orderContract = new OrderHistory { Id = src.Id, Code = src.Code, ClientId = src.ClientId, AccountId = src.AccountId, TradingConditionId = src.TradingConditionId, AccountAssetId = src.AccountAssetId, Instrument = src.Instrument, Type = src.Type.ToType <OrderDirection>(), CreateDate = src.CreateDate, OpenDate = src.OpenDate, CloseDate = src.CloseDate, ExpectedOpenPrice = src.ExpectedOpenPrice, OpenPrice = src.OpenPrice, ClosePrice = src.ClosePrice, QuoteRate = src.QuoteRate, AssetAccuracy = src.AssetAccuracy, Volume = src.Volume, TakeProfit = src.TakeProfit, StopLoss = src.StopLoss, CommissionLot = src.CommissionLot, OpenCommission = src.OpenCommission, CloseCommission = src.CloseCommission, SwapCommission = src.SwapCommission, StartClosingDate = src.StartClosingDate, Status = src.Status.ToType <OrderStatus>(), CloseReason = src.CloseReason.ToType <OrderCloseReason>(), FillType = src.FillType.ToType <OrderFillType>(), RejectReason = src.RejectReason.ToType <OrderRejectReason>(), RejectReasonText = src.RejectReasonText, Comment = src.Comment, MatchedVolume = src.MatchedVolume, MatchedCloseVolume = src.MatchedCloseVolume, Fpl = src.Fpl, PnL = src.PnL, InterestRateSwap = src.InterestRateSwap, MarginInit = src.MarginInit, MarginMaintenance = src.MarginMaintenance, EquivalentAsset = src.EquivalentAsset, OpenPriceEquivalent = src.OpenPriceEquivalent, ClosePriceEquivalent = src.ClosePriceEquivalent, OrderUpdateType = src.OrderUpdateType.ToType <OrderUpdateType>(), OpenExternalOrderId = src.OpenExternalOrderId, OpenExternalProviderId = src.OpenExternalProviderId, CloseExternalOrderId = src.CloseExternalOrderId, CloseExternalProviderId = src.CloseExternalProviderId, MatchingEngineMode = src.MatchingEngineMode.ToType <MatchingEngineMode>(), LegalEntity = src.LegalEntity, }; foreach (var order in src.MatchedOrders) { orderContract.MatchedOrders.Add(order.ToDomain()); } foreach (var order in src.MatchedCloseOrders) { orderContract.MatchedCloseOrders.Add(order.ToDomain()); } return(orderContract); }
//might not be in this class (maybe move to order) public void PlaceOrder(MakeupStoreDbContext dbContext) { var o = new Orders(); string ans = ""; string where = ""; if (defaultStoreLocation != null) { Console.WriteLine($"Would you like to shop at {defaultStoreLocation}?"); ans = Console.ReadLine(); if (ans.Equals("y")) { where = "Arlington"; } else { Console.WriteLine("Enter your preffered store to shop:"); foreach (var loc in dbContext.Locations.Include(l => l.Inventory)) { Console.WriteLine($"{loc.LocationId}. {loc.LocationName}"); } where = Console.ReadLine(); } } else { Console.WriteLine("Enter your preffered store to shop:"); foreach (var loc in dbContext.Locations.Include(l => l.Inventory)) { Console.WriteLine($"{loc.LocationId}. {loc.LocationName}"); } where = Console.ReadLine(); } Console.WriteLine($"Displaying Inventory for {where}:"); foreach (var item in dbContext.InventoryItem.Include(i => i.Inventory)) { Console.WriteLine($"{item.ItemId}. {item.ItemName} Price: ${item.Price}"); } int it = 0; float tot = 0; while (true) { Console.WriteLine("Enter ID to Item you want:"); it = Convert.ToInt32(Console.ReadLine()); foreach (var item in dbContext.InventoryItem.Include(i => i.Inventory)) { if (it == item.ItemId) { tot += item.Price; } } o.LocationName = where; o.ItemId = it; o.OrderTime = DateTime.Now; //dbContext.Database.ExecuteSqlCommand("UPDATE TABLE [dbo].[Inventory] WHERE [LocationId] =="); foreach (var cust in dbContext.Customer.Include(c => c.Orders)) { if (cust.FirstName.Equals(firstName) && cust.LastName.Equals(LastName)) { o.CustomerId = cust.CustomerId; } } dbContext.Add(o); var newOrderHistory = new OrderHistory { OrderId = o.OrderId, CustomerId = o.CustomerId, Total = tot }; try { dbContext.Add(newOrderHistory); dbContext.SaveChanges(); } catch (DbUpdateException e) { Console.WriteLine("Unable yo update thr database!", e); } finally { } Console.WriteLine("Buy another item? (y/n)"); ans = Console.ReadLine(); if (ans.Equals("n")) { break; } } }
public bool CanBuy(BuyOptions options, out string message) { IPairConfig pairConfig = GetPairConfig(options.Pair); if (!options.ManualOrder && !options.Swap && IsTradingSuspended) { message = $"Cancel buy request for {options.Pair}. Reason: trading suspended"; return(false); } else if (!options.ManualOrder && !options.Swap && !pairConfig.BuyEnabled) { message = $"Cancel buy request for {options.Pair}. Reason: buying not enabled"; return(false); } else if (!options.ManualOrder && Config.ExcludedPairs.Contains(options.Pair)) { message = $"Cancel buy request for {options.Pair}. Reason: exluded pair"; return(false); } else if (!options.ManualOrder && !options.Arbitrage && !options.IgnoreExisting && Account.HasTradingPair(options.Pair)) { message = $"Cancel buy request for {options.Pair}. Reason: pair already exists"; return(false); } else if (!options.ManualOrder && !options.Swap && !options.Arbitrage && pairConfig.MaxPairs != 0 && Account.GetTradingPairs().Count() >= pairConfig.MaxPairs && !Account.HasTradingPair(options.Pair)) { message = $"Cancel buy request for {options.Pair}. Reason: maximum pairs reached"; return(false); } else if (!options.ManualOrder && !options.Swap && !options.IgnoreBalance && pairConfig.BuyMinBalance != 0 && (Account.GetBalance() - options.MaxCost) < pairConfig.BuyMinBalance && Exchange.GetPairMarket(options.Pair) == Config.Market) { message = $"Cancel buy request for {options.Pair}. Reason: minimum balance reached"; return(false); } else if (options.Price != null && options.Price <= 0) { message = $"Cancel buy request for {options.Pair}. Reason: invalid price"; return(false); } else if (options.Amount != null && options.Amount <= 0) { message = $"Cancel buy request for {options.Pair}. Reason: invalid amount"; return(false); } else if (!options.IgnoreBalance && Account.GetBalance() < options.MaxCost && Exchange.GetPairMarket(options.Pair) == Config.Market) { message = $"Cancel buy request for {options.Pair}. Reason: not enough balance"; return(false); } else if (options.Amount == null && options.MaxCost == null || options.Amount != null && options.MaxCost != null) { message = $"Cancel buy request for {options.Pair}. Reason: either max cost or amount needs to be specified (not both)"; } else if (!options.ManualOrder && !options.Swap && !options.Arbitrage && pairConfig.BuySamePairTimeout > 0 && OrderHistory.Any(h => h.Side == OrderSide.Buy && (h.Pair == options.Pair || h.Pair == h.OriginalPair)) && (DateTimeOffset.Now - OrderHistory.Where(h => (h.Pair == options.Pair || h.Pair == h.OriginalPair)).Max(h => h.Date)).TotalSeconds < pairConfig.BuySamePairTimeout) { var elapsedSeconds = (DateTimeOffset.Now - OrderHistory.Where(h => (h.Pair == options.Pair || h.Pair == h.OriginalPair)).Max(h => h.Date)).TotalSeconds; message = $"Cancel buy request for {options.Pair}. Reason: buy same pair timeout (elapsed: {elapsedSeconds:0.#}, timeout: {pairConfig.BuySamePairTimeout:0.#})"; return(false); } message = null; return(true); }
private void PopulateDailyOrderEmailModel(dynamic emailModel, Customer customer, OrderHistory orderHistory) { emailModel.OrderNumber = orderHistory.WebOrderNumber; emailModel.CustomerName = customer.FirstName + " " + customer.LastName; emailModel.CustomerNumber = customer.CustomerNumber; if (customer != null && !string.IsNullOrEmpty(customer.CustomerSequence)) { emailModel.CustomerShipToNumber = customer.CustomerSequence; } else { emailModel.CustomerShipToNumber = string.Empty; } List <ExpandoObject> OrderHistoryLines = new List <ExpandoObject>(); foreach (var orderline in orderHistory.OrderHistoryLines) { dynamic values = new ExpandoObject(); var productDetails = this.UnitOfWork.GetRepository <Product>().GetTable().FirstOrDefault(x => x.ErpNumber == orderline.ProductErpNumber); if (orderline.QtyShipped < orderline.QtyOrdered) { values.ProductName = productDetails.Name; values.ProductDescription = productDetails.ShortDescription; values.Quantity = orderline.QtyOrdered; values.BackorderQuantity = orderline.QtyOrdered - orderline.QtyShipped; OrderHistoryLines.Add(values); } } emailModel.OrderHistoryLines = OrderHistoryLines; }
public static string PlaceOrder(OrderHistory order) { bool loop = true; string input; do { Console.WriteLine(); input = DisplayMenu(); if (input == "b") { return(input); } else if (input == "1") { order = PlainBurger(order); } else if (input == "2") { order = GoodBurger(order); } else if (input == "3") { order = AddCheese(order); } else if (input == "4") { order = AddBacon(order); } else if (input == "5") { order = AddEdSauce(order); } else if (input == "6") { order = AddFries(order); } else if (input == "7") { order = AddCola(order); } else if (input == "8") { var loop2 = true; do { Console.WriteLine(); input = DisplayCondims(); if (input == "b") { loop2 = false; } else if (input == "1") { order = AddLettuce(order); } else if (input == "2") { order = AddOnions(order); } else if (input == "3") { order = AddPickles(order); } else if (input == "4") { order = AddTomatoes(order); } else if (input == "5") { order = AddMayo(order); } else if (input == "6") { order = AddKetchup(order); } } while (loop2); } else if (input == "0") { loop = false; } else { Console.WriteLine(); Console.WriteLine("Invalid entry. Please try again."); } } while (loop); do { Console.WriteLine(order.Order + " = $" + order.TotalPrice); Console.WriteLine(); Console.Write("Are you finished with your order? (y/n)"); Console.WriteLine(); input = Console.ReadLine(); if (input == "n") { PlaceOrder(order); } else if (input == "y") { order.DateTime = DateTime.Now; using (var db = new BurgerDbContext()) { db.OrderHistory.Add(order); db.SaveChanges(); } Console.Write("Your order has been placed. Thank you"); Console.WriteLine(); input = "q"; return(input); } else { Console.WriteLine(); Console.WriteLine("Invalid entry. Please try again."); } } while (true); }
public static OrderHistory OrderHistory(int? counter) { var rtValue = new OrderHistory(); rtValue.OrderId = counter ?? 99; rtValue.WorkgroupId = counter ?? 99; rtValue.StatusId = "StatusId" + counter.Extra(); rtValue.OrderTypeId = "OrderTypeId" + counter.Extra(); rtValue.RequestNumber = "RequestNumber" + counter.Extra(); rtValue.WorkgroupName = "WorkgroupName" + counter.Extra(); rtValue.Vendor = "Vendor" + counter.Extra(); rtValue.CreatedBy = "CreatedBy" + counter.Extra(); rtValue.CreatorId = "CreatorId" + counter.Extra(); rtValue.DateCreated = DateTime.UtcNow.ToPacificTime().AddDays(counter ?? 0); rtValue.Status = "Status" + counter.Extra(); rtValue.IsComplete = true; rtValue.TotalAmount = 99.99m; rtValue.LineItems = "LineItems" + counter.Extra(); rtValue.AccountSummary = "AccountSummary" + counter.Extra(); rtValue.HasAccountSplit = true; rtValue.ShipTo = "ShipTo" + counter.Extra(); rtValue.AllowBackorder = "AllowBackorder" + counter.Extra(); rtValue.Restricted = "Restricted" + counter.Extra(); rtValue.DateNeeded = DateTime.UtcNow.ToPacificTime().AddDays(counter ?? 0); rtValue.ShippingType = "ShippingType" + counter.Extra(); rtValue.ReferenceNumber = "ReferenceNumber" + counter.Extra(); rtValue.LastActionDate = DateTime.UtcNow.ToPacificTime().AddDays(counter ?? 0); rtValue.LastActionUser = "******" + counter.Extra(); rtValue.Received = "Received" + counter.Extra(); rtValue.OrderType = "OrderType" + counter.Extra(); return rtValue; }
// returns any rejected orders public ICollection <IOrder> Order(IUser user, ICollection <IOrder> orders) { if (user is null) { throw new ArgumentNullException(paramName: nameof(user)); } if (orders is null) { throw new ArgumentNullException(paramName: nameof(orders)); } var attemptedOrderTime = TimeProvider.Current.UtcNow; if (orders.Count > user.MaxOrdersPerCall) { throw new ArgumentException(message: $"user should not exceed {user.MaxOrdersPerCall} orders per call.", paramName: nameof(orders)); } if (LastOrderTime.TryGetValue(user, out DateTime userLastOrderTime) && attemptedOrderTime - userLastOrderTime < MinOrderInterval) { // user cannot order from here within 2 hours of last order return(new List <IOrder>(orders)); } ICollection <IOrder> rejectedOrders = new List <IOrder>(); IPizzaStoreDBContext context = PSDBContextProvider.Current.NewPSDBContext; foreach (IOrder order in orders) { // reject if this order is for another location if (order.Location != this) { rejectedOrders.Add(order); continue; } // reject if this exact order has already been ordered if (order.Time != null) { rejectedOrders.Add(order); continue; } int piesRequired = order.PizzasByPrice.Sum(x => x.Value); // reject if there is not enough inventory for this order if (piesRequired > PieCount) { rejectedOrders.Add(order); continue; } if (!OrderHistory.TryGetValue(user, out Stack <IOrder> userOrderHistory)) { userOrderHistory = new Stack <IOrder>(); OrderHistory[user] = userOrderHistory; } userOrderHistory.Push(order); LastOrderTime[user] = attemptedOrderTime; order.Time = attemptedOrderTime; PieCount -= piesRequired; Dao.Inventory = PieCount; context.Update(Dao); context.Update(order.Dao); } context.SaveChanges(); context.Dispose(); return(rejectedOrders); }
public deliveryboydatalist getDBoyOrdersHistory(string mob, DateTime?start, DateTime?end, int dboyId) { try { deliveryboydatalist orderhistory = new deliveryboydatalist(); orderhistory.totalOrder = 0; orderhistory.AllOrderAmount = 0; orderhistory.DeliveredOrderAmount = 0; orderhistory.Canceled = 0; orderhistory.CanceledOderAmount = 0; orderhistory.RedispatchedOrderAmount = 0; orderhistory.Redispatched = 0; orderhistory.Delivered = 0; orderhistory.Pending = 0; orderhistory.PendingOderAmount = 0; var Issulist = db.DeliveryIssuanceDb.Where(x => x.CreatedDate > start && x.CreatedDate <= end && x.PeopleID == dboyId).ToList(); if (Issulist != null) { orderhistory.name = Issulist[0].DisplayName; orderhistory.DBoyId = Issulist[0].PeopleID; } foreach (var o in Issulist) { if (o.Status == "Accepted") { var orderhistory1 = new OrderHistory(); List <OrderDispatchedMaster> OrdersObj = new List <OrderDispatchedMaster>(); string[] ids = o.OrderdispatchIds.Split(','); foreach (var od in ids) { var oid = Convert.ToInt16(od); var orderdipatchmaster = db.OrderDispatchedMasters.Where(x => x.OrderDispatchedMasterId == oid).SingleOrDefault(); if (orderdipatchmaster != null) { if ((orderdipatchmaster.Status == "Delivery Canceled" || orderdipatchmaster.Status == "Order Canceled")) { orderhistory.Canceled = orderhistory.Canceled + 1; orderhistory.CanceledOderAmount = orderhistory.CanceledOderAmount + orderdipatchmaster.GrossAmount; } else if ((orderdipatchmaster.Status == "Delivered" || orderdipatchmaster.Status == "sattled" || orderdipatchmaster.Status == "Account settled" || orderdipatchmaster.Status == "Partial settled" || orderdipatchmaster.Status == "Partial receiving -Bounce")) { orderhistory.Delivered = orderhistory.Delivered + 1; orderhistory.DeliveredOrderAmount = orderhistory.DeliveredOrderAmount + orderdipatchmaster.GrossAmount; } if ((orderdipatchmaster.Status == "Ready to Dispatch" || orderdipatchmaster.Status == "Delivery Redispatch") && (orderdipatchmaster.ReDispatchCount > 0)) { orderhistory.Redispatched = orderhistory.Redispatched + 1; orderhistory.RedispatchedOrderAmount = orderhistory.RedispatchedOrderAmount + orderdipatchmaster.GrossAmount; } if ((orderdipatchmaster.Status == "Ready to Dispatch")) { orderhistory.ReadyToDispatch = orderhistory.ReadyToDispatch + 1; orderhistory.ReadyToDispatchOderAmount = orderhistory.ReadyToDispatchOderAmount + orderdipatchmaster.GrossAmount; } if ((orderdipatchmaster.Status == "Pending" || orderdipatchmaster.Status == "Shipped")) { orderhistory.Pending = orderhistory.Pending + 1; orderhistory.PendingOderAmount = orderhistory.PendingOderAmount + orderdipatchmaster.GrossAmount; } orderhistory.AllOrderAmount = orderhistory.AllOrderAmount + orderdipatchmaster.GrossAmount; orderhistory.totalOrder = orderhistory.totalOrder + 1; } } } } return(orderhistory); } catch (Exception ex) { return(null); } }
/// <summary> /// Based on filtering a seller's sales, try to match a prodID with a prodID on walmart /// </summary> /// <param name="settings"></param> /// <param name="rptNumber"></param> /// <param name="minSold"></param> /// <param name="daysBack"></param> /// <param name="minPrice"></param> /// <param name="maxPrice"></param> /// <param name="activeStatusOnly"></param> /// <param name="nonVariation"></param> /// <param name="itemID"></param> /// <param name="pctProfit"></param> /// <returns></returns> private static async Task UPCMatch(IUserSettingsView settings, int rptNumber, int minSold, int daysBack, int?minPrice, int?maxPrice, bool?activeStatusOnly, bool?isSellerVariation, string itemID, double pctProfit, decimal wmShipping, decimal wmFreeShippingMin, double eBayPct, int imgLimit) { string loopItemID = null; try { var mv = new ModelViewTimesSold(); mv.TimesSoldRpt = FilterMatch(settings, rptNumber, minSold, daysBack, minPrice, maxPrice, activeStatusOnly, isSellerVariation, itemID); foreach (var row in mv.TimesSoldRpt) { loopItemID = row.ItemID; bool tryAgain = false; WalmartSearchProdIDResponse response; //var walitem = new SupplierItem(); ISupplierItem walitem; if (row.SellerUPC != null) { response = wallib.wmUtility.SearchProdID(row.SellerUPC); if (response.Count == 1) { walitem = await wallib.wmUtility.GetDetail(response.URL, imgLimit, false); // If can't get supplier pics, not much point in posting. // Can happen when not matching correctly on something like an eBook or giftcard where walmart // is not providing "standard" images. (error is logged in GetDetail()). if (!string.IsNullOrEmpty(walitem.SupplierPicURL)) { walitem.UPC = row.SellerUPC; walitem.Updated = DateTime.Now; _repository.SupplierItemUpdateByProdID(row.SellerUPC, "", walitem as SupplierItem, "Updated", "ItemURL", "SoldAndShippedBySupplier", "SupplierBrand", "SupplierPrice", "IsVariation", "SupplierPicURL", "IsFreightShipping"); var oh = new OrderHistory(); oh.ItemID = row.ItemID; oh.MatchCount = response.Count; oh.MatchType = 1; oh.SourceID = walitem.SourceID; oh.SupplierItemID = walitem.ID; if (walitem.SupplierPrice.HasValue) { var p = wallib.wmUtility.wmNewPrice(walitem.SupplierPrice.Value, pctProfit, wmShipping, wmFreeShippingMin, eBayPct); oh.ProposePrice = p.ProposePrice; _repository.OrderHistoryUpdate(oh, "ProposePrice", "MatchType", "MatchCount", "SourceID", "SupplierItemID"); } else { _repository.OrderHistoryUpdate(oh, "MatchType", "MatchCount", "SourceID", "SupplierItemID"); } } } else { tryAgain = true; } } else { tryAgain = true; } if (tryAgain) { if (row.SellerMPN != null) { response = wallib.wmUtility.SearchProdID(row.SellerMPN); if (response.Count == 1) { walitem = await wallib.wmUtility.GetDetail(response.URL, imgLimit, false); // If can't get supplier pics, not much point in posting. // Can happen when not matching correctly on something like an eBook or giftcard where walmart // is not providing "standard" images. (error is logged in GetDetail()). if (!string.IsNullOrEmpty(walitem.SupplierPicURL)) { walitem.MPN = row.SellerMPN; walitem.Updated = DateTime.Now; _repository.SupplierItemUpdateByProdID("", row.SellerMPN, walitem as SupplierItem, "Updated", "ItemURL", "SoldAndShippedBySupplier", "SupplierBrand", "SupplierPrice", "IsVariation", "SupplierPicURL"); // now update the ebay seller item specific UPC // but walmart doesn't always give a UPC if (!string.IsNullOrEmpty(walitem.UPC)) { var itemSpecific = new OrderHistoryItemSpecific(); itemSpecific.SellerItemID = row.ItemID; itemSpecific.ItemName = "UPC"; itemSpecific.ItemValue = walitem.UPC; itemSpecific.Flags = true; _repository.OrderHistoryItemSpecificUpdate(itemSpecific); } if (walitem.SupplierPrice.HasValue) { var oh = new OrderHistory(); oh.ItemID = row.ItemID; var p = wallib.wmUtility.wmNewPrice(walitem.SupplierPrice.Value, pctProfit, wmShipping, wmFreeShippingMin, eBayPct); oh.ProposePrice = p.ProposePrice; oh.MatchCount = response.Count; oh.MatchType = 1; oh.SourceID = walitem.SourceID; oh.SupplierItemID = walitem.ID; _repository.OrderHistoryUpdate(oh, "ProposePrice", "MatchType", "MatchCount", "SourceID", "SupplierItemID"); } } } } } } } catch (Exception exc) { string msgItemID = (!string.IsNullOrEmpty(loopItemID)) ? "ItemID: " + loopItemID : ""; string header = "UPCMatch RptNumber: " + rptNumber.ToString() + " " + msgItemID; string msg = dsutil.DSUtil.ErrMsg(header, exc); dsutil.DSUtil.WriteFile(_logfile, msg, ""); } }
public static OrderHistory ToOrderHistoryDomain(this OrderContract order, OrderHistoryTypeContract historyType, string correlationId) { var orderContract = new OrderHistory { Id = order.Id, AccountId = order.AccountId, AssetPairId = order.AssetPairId, CreatedTimestamp = order.CreatedTimestamp, Direction = order.Direction.ToType <OrderDirection>(), ExecutionPrice = order.ExecutionPrice, FxRate = order.FxRate, FxAssetPairId = order.FxAssetPairId, FxToAssetPairDirection = order.FxToAssetPairDirection.ToType <FxToAssetPairDirection>(), ExpectedOpenPrice = order.ExpectedOpenPrice, ForceOpen = order.ForceOpen, ModifiedTimestamp = order.ModifiedTimestamp, Originator = order.Originator.ToType <OriginatorType>(), ParentOrderId = order.ParentOrderId, PositionId = order.PositionId, Status = order.Status.ToType <OrderStatus>(), FillType = order.FillType.ToType <OrderFillType>(), Type = order.Type.ToType <OrderType>(), ValidityTime = order.ValidityTime, Volume = order.Volume ?? 0, //------ AccountAssetId = order.AccountAssetId, EquivalentAsset = order.EquivalentAsset, ActivatedTimestamp = order.ActivatedTimestamp == default(DateTime) ? null : order.ActivatedTimestamp, CanceledTimestamp = order.CanceledTimestamp, Code = order.Code, Comment = order.Comment, EquivalentRate = order.EquivalentRate, ExecutedTimestamp = order.ExecutedTimestamp, ExecutionStartedTimestamp = order.ExecutionStartedTimestamp, ExternalOrderId = order.ExternalOrderId, ExternalProviderId = order.ExternalProviderId, LegalEntity = order.LegalEntity, MatchingEngineId = order.MatchingEngineId, Rejected = order.Rejected, RejectReason = order.RejectReason.ToType <OrderRejectReason>(), RejectReasonText = order.RejectReasonText, RelatedOrderInfos = order.RelatedOrderInfos.Select(o => new RelatedOrderInfo { Id = o.Id, Type = o.Type.ToType <OrderType>() }).ToList(), TradingConditionId = order.TradingConditionId, UpdateType = historyType.ToType <OrderUpdateType>(), MatchedOrders = new List <MatchedOrder>(), AdditionalInfo = order.AdditionalInfo, CorrelationId = correlationId, PendingOrderRetriesCount = order.PendingOrderRetriesCount, }; foreach (var mo in order.MatchedOrders) { orderContract.MatchedOrders.Add(mo.ToDomain()); } return(orderContract); }
public void CreateOrderHistory(int orderId, OrderHistory orderHistory) { }
private void btnHistory_Click(object sender, EventArgs e) { OrderHistory form = new OrderHistory(); form.Show(); }