public IHttpActionResult ResignOffer(ReserveOfferDto dto) { using (var context = _provider.GetNewContext()) { using (var transaction = new TransactionScope()) { Offer offer = context.Offers.FirstOrDefault(o => o.Id == dto.OfferId); User customer = context.Users.FirstOrDefault(u => u.Username.Equals(dto.Username)); User vendor = context.Users.FirstOrDefault(x => x.Id == offer.VendorId); if (offer == null || customer == null) { return(NotFound()); } if (!offer.IsBooked) { return(BadRequest()); } OfferInfo offerInfo = context.OfferInfo.FirstOrDefault(o => o.Id == offer.OfferInfoId); UserData customerData = context.UserData.FirstOrDefault(x => x.Id == customer.UserDataId); UserData vendorData = context.UserData.FirstOrDefault(x => x.Id == vendor.UserDataId); Room room = context.Rooms.FirstOrDefault(x => x.Id == offer.RoomId); Place place = context.Places.FirstOrDefault(x => x.Id == room.PlaceId); offer.IsBooked = false; offer.Customer = null; context.SaveChanges(); //Wysłanie powiadomienia mailowego, ostatni parametr oznacza rezygnację EmailNotification.SendNotification(offerInfo, place, vendorData, customerData, room, false); transaction.Complete(); } } return(Ok(true)); }
public static bool IsPassedSetting(Settings settings, OfferInfo info, bool usingQcode = false) { if (settings.Payout > 0 && info.Payout < settings.Payout) { return(false);//Check minium payout } if (settings.EndWith > 0 && settings.EndWith > settings.StartWith) { if (!usingQcode && (Convert.ToInt32(info.Id) < settings.StartWith || Convert.ToInt32(info.Id) > settings.EndWith)) { return(false);//Check start/end } } if (settings.Platform != 0) { if ((settings.Platform == 1 && !info.Platform.ToLower().Equals("android")) || (settings.Platform == 2 && !info.Platform.ToLower().Equals("ios"))) { if (settings.Platform == 2) { if (info.Platform.ToLower().Contains("ipad") || info.Platform.ToLower().Contains("iphone")) { info.Platform = "iOS"; return(true); } } return(false); } } return(true); }
public async void Load() { var ret = new ObservableCollection <DisplayableOffer>(); string currentUser = Thread.CurrentPrincipal.Identity.Name; User user = await usersProxy.GetUser(currentUser); var list = await offersProxy.GetUserOffers(user.Id); foreach (var item in list) { OfferInfo oi = await offerInfoesProxy.Get(item.OfferInfoId); Room r = await _roomsProxy.Get(item.RoomId); Place p = await PlacesProxy.Get(r.PlaceId); Address a = await addressesProxy.Get(p.AddressId); p.Address = a; r.Place = p; item.OfferInfo = oi; item.Room = r; DisplayableOffer dof = new DisplayableOffer(item); ret.Add(dof); } this.CurrentOffersList = ret; }
/// <summary> /// Usuwa ofertę o danym id z bazy /// </summary> /// <param name="context">Kontekst bazy danych</param> /// <param name="offerId">Id oferty</param> /// <param name="username">Nazwa użytkownika</param> /// <returns></returns> public static bool DeleteOfferById(IAccommodationContext context, int offerId, string username) { try { Offer offer = context.Offers.FirstOrDefault(x => x.Id == offerId); if (offer == null) { return(false); } User user = context.Users.FirstOrDefault(u => u.Username == username); OfferInfo offerInfo = context.OfferInfo.FirstOrDefault(x => x.Id == offer.OfferInfoId); Room room = context.Rooms.FirstOrDefault(x => x.Id == offer.RoomId); Place place = context.Places.FirstOrDefault(x => x.Id == room.PlaceId); Address address = context.Addresses.FirstOrDefault(x => x.Id == place.AddressId); var ho = context.HistoricalOffers.FirstOrDefault(h => h.OriginalOfferId == offer.Id); if (ho != null) { ho.OriginalOffer = null; } //usuń z bazy ofertę oraz jej dane context.Offers.Remove(offer); user?.MyOffers?.Remove(offer); context.SaveChanges(); return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// Wczytywanie historii ofert /// </summary> public async void Load() { var ret = new ObservableCollection <DisplayableOffer>(); //nazwa aktualnego usera string currentUser = Thread.CurrentPrincipal.Identity.Name; //wyslij zapytanie o akutualnego usera User user = await usersProxy.GetUser(currentUser); //wyslij zapytanie o listę ofert var list = await offersProxy.GetUserHistoricalOffers(user.Id); //Dla każdej oferty w historii stwórz jej wersję do wyświetlenia foreach (var item in list) { OfferInfo oi = await offerInfoesProxy.Get(item.OfferInfoId); Room r = await roomsProxy.Get(item.RoomId); Place p = await placesProxy.Get(r.PlaceId); Address a = await addressesProxy.Get(p.AddressId); p.Address = a; r.Place = p; item.OfferInfo = oi; item.Room = r; DisplayableOffer dof = new DisplayableOffer(item); ret.Add(dof); } this.CurrentOffersList = ret; }
/// <summary> /// Umożliwia edycję oferty w bazie /// </summary> /// <param name="context">Kontekst bazy danych</param> /// <param name="model">Model z danymi oferty</param> /// <returns></returns> public static bool EditOffer(IAccommodationContext context, AddNewOfferViewModel model) { try { Offer offer = context.Offers.FirstOrDefault(x => x.Id == model.Id); if (offer == null) { return(false); } HistoricalOffer ho = context.HistoricalOffers.FirstOrDefault(x => x.OriginalOfferId == offer.Id); OfferInfo newOfferInfo = new OfferInfo { Description = model.Description, OfferEndTime = model.EndDate, OfferStartTime = model.StartDate, OfferPublishTime = DateTime.Now, Price = double.Parse(model.Price) }; Address newAddress = new Address { City = model.City, Street = model.Street, LocalNumber = model.LocalNumber, PostalCode = model.PostalCode, }; Place newPlace = new Place { Address = newAddress, PlaceName = model.AccommodationName, }; Room newRoom = new Room { Capacity = int.Parse(model.AvailiableVacanciesNumber), Number = model.RoomNumber, Place = newPlace, }; ho.OfferInfo = offer.OfferInfo = newOfferInfo; ho.Room = offer.Room = newRoom; ho.Room.Place = offer.Room.Place = newPlace; ho.Room.Place.Address = offer.Room.Place.Address = newAddress; context.SaveChanges(); return(true); } catch (Exception ex) { return(false); } }
public static void TestFullDealGraph(TestContext context) { var expectedContent = System.IO.File.ReadAllText("FullResponse.json"); var deal = JsonConvert.DeserializeObject <Deal>(expectedContent); OfferDetails = deal.OfferDetails; User = deal.User; Package = deal.OfferCollections.Packages[0]; Flight = deal.OfferCollections.Flights[0]; Hotel = deal.OfferCollections.Hotels[0]; }
/// <summary> /// Wysyła zapytanie dodające usera do bazy /// </summary> /// <param name="offerInfo"></param> /// <param name="vendor"></param> /// <param name="place"></param> /// <param name="room"></param> /// <returns></returns> public async Task SaveOfferAsync(OfferInfo offerInfo, User vendor, Place place, Room room) { OfferAllDataDto dto = new OfferAllDataDto() { Vendor = vendor, OfferInfo = offerInfo, Place = place, Room = room }; await Post <OfferAllDataDto, object>("saveOffer", dto); }
public UserMarksViewModel(HistoricalOffer offer, User user) { OfferInfo offerInfo = offer.OfferInfo; OfferStartTime = offerInfo.OfferStartTime.Date.ToString("dd/MM/yyyy"); OfferEndTime = offerInfo.OfferEndTime.Date.ToString("dd/MM/yyyy"); OfferEndTimeDate = offerInfo.OfferEndTime; OfferStartTimeDate = offerInfo.OfferStartTime; PlaceName = offer.Room.Place.PlaceName; RoomNumber = offer.Room.Number; Username = user.Username; ReservedOfferId = offer.Id; }
/// <summary> /// Wysyła zapytanie do modyfikacji oferty /// </summary> /// <param name="username"></param> /// <param name="Id"></param> /// <param name="offerInfo"></param> /// <param name="place"></param> /// <param name="room"></param> /// <returns></returns> public async Task EditOfferAsync(string username, int Id, OfferInfo offerInfo, Place place, Room room) { OfferEditDataDto dataDto = new OfferEditDataDto() { OfferInfo = offerInfo, Place = place, Username = username, OfferId = Id, Room = room }; await Post <OfferEditDataDto, bool>("editOffer", dataDto); }
private int GetProviderId(OfferInfo oi) { if (oi.OfferName == "ARIA" || oi.OfferName == "BAHAMAS") { return(70206); } if (oi.OfferName == "850" || oi.OfferName == "811" || oi.OfferName == "XLINE") { return(70201); } return(70001); }
/// <summary> /// Funkcja aktualizująca ofertę w bazie /// </summary> public async void UpDate() { Address address = new Address() { City = this.City, Street = this.Street, LocalNumber = this.LocalNumber, PostalCode = this.PostalCode }; OfferInfo offerInfo = new OfferInfo() { OfferStartTime = TimeZoneInfo.ConvertTimeToUtc(this.StartDate), OfferEndTime = TimeZoneInfo.ConvertTimeToUtc(this.EndDate), Description = this.Description, Price = double.Parse(this.Price), OfferPublishTime = DateTime.UtcNow }; Place place = new Place() { PlaceName = this.AccommodationName, Address = address }; Room room = new Room() { Capacity = int.Parse(AvailiableVacanciesNumber), Number = RoomNumber }; //nazwa aktualnego usera string currentUser = Thread.CurrentPrincipal.Identity.Name; try { //asynchronicznie wysyła zapytanie do edycji oferty await offersProxy.EditOfferAsync(currentUser, this.Id, offerInfo, place, room); } catch (Exception) { MessageBox.Show("Wystąpił błąd przy edycji oferty"); return; } Close(); //uaktualnij bieżące oferty Ovm.Load(); }
public static void WriteOfferInfo(OfferInfo offerInfo, string savePath) { try { using (StreamWriter stw = File.AppendText(savePath)) { stw.WriteLine($"{offerInfo.Id}\t{offerInfo.Name}\t{offerInfo.Tracking}\t{offerInfo.Platform}\t{offerInfo.Country}\t{offerInfo.Payout}\t{offerInfo.PreviewUrl}"); stw.Flush(); stw.Close(); } } catch { } }
/// <summary> /// Funkcja dodająca nową ofertę /// </summary> public async void Add() { string currentUser = Thread.CurrentPrincipal.Identity.Name; User vendor = await usersProxy.GetUser(currentUser); Address address = new Address() { City = this.City, Street = this.Street, LocalNumber = this.LocalNumber, PostalCode = this.PostalCode }; OfferInfo offer = new OfferInfo() { //przekształcanie dat do odpowiedniej postaci (zgodnej z bazą danych) OfferStartTime = TimeZoneInfo.ConvertTimeToUtc(this.StartDate), OfferEndTime = TimeZoneInfo.ConvertTimeToUtc(this.EndDate), Description = this.Description, Price = double.Parse(this.Price), OfferPublishTime = DateTime.UtcNow }; Place place = new Place() { PlaceName = this.AccommodationName, Address = address }; Room room = new Room() { Capacity = int.Parse(AvailiableVacanciesNumber), Number = RoomNumber }; try { await offersProxy.SaveOfferAsync(offer, vendor, place, room); } catch (ArgumentException) { MessageBox.Show("Nie można dodać już oferty dla tego miejsca na ten pokój. Oferta koliduje z inną."); } catch (Exception) { MessageBox.Show("Dodawanie oferty nie powiodło się"); } }
public static bool SendNotification(OfferInfo offerInfo, Place place, UserData vendor, UserData customer, Room room, bool rezervation) { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); mail.To.Add(vendor.Email); var sb = new StringBuilder(); sb.AppendFormat("Witaj, {0}", vendor.FirstName); sb.AppendLine(); if (rezervation) { mail.Subject = subject1; sb.AppendFormat("Użytkownik {0} {1} zarezerwował ofertę:", customer.FirstName, customer.LastName); } else { sb.AppendFormat("Użytkownik {0} {1} zrezygnował z oferty:", customer.FirstName, customer.LastName); mail.Subject = subject2; } sb.AppendLine(); sb.AppendFormat("{0}, pokój nr {1}, od {2} do {3}", place.PlaceName, room.Number, offerInfo.OfferStartTime.Date.ToString("dd/MM/yyyy"), offerInfo.OfferEndTime.Date.ToString("dd/MM/yyyy")); sb.AppendLine(); sb.AppendLine(); sb.Append(body1); sb.AppendLine(); sb.Append(body2); mail.Body = sb.ToString(); SmtpServer.Port = 587; SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network; SmtpServer.UseDefaultCredentials = false; SmtpServer.Credentials = new System.Net.NetworkCredential(username, password); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); return(true); }
public DisplayableOffer(HistoricalOffer offer) { OfferInfo offerInfo = offer.OfferInfo; OfferStartTime = offerInfo.OfferStartTime.Date.ToString("dd/MM/yyyy"); OfferEndTime = offerInfo.OfferEndTime.Date.ToString("dd/MM/yyyy"); OfferEndTimeDate = offerInfo.OfferEndTime; OfferStartTimeDate = offerInfo.OfferStartTime; Address = offer.Room.Place.Address; PlaceName = offer.Room.Place.PlaceName; AvailableVacanciesNumber = offer.Room.Capacity; RoomNumber = offer.Room.Number; Price = offerInfo.Price; Description = offerInfo.Description; OfferPublishTime = offerInfo.OfferPublishTime; Id = offer.Id; IsBooked = offer.IsBooked; }
/// <summary> /// Wysyła informacje o ofercie o danym id /// </summary> /// <param name="id"></param> /// <returns></returns> public IHttpActionResult Get(int id) { OfferInfo offerinfo = null; using (var context = _provider.GetNewContext()) { if (context is DbContext) { (context as DbContext).Configuration.ProxyCreationEnabled = false; } offerinfo = context.OfferInfo.FirstOrDefault(o => o.Id == id); } if (offerinfo == null) { return((IHttpActionResult)NotFound()); } return(Ok(offerinfo)); }
/// <summary> /// Umożliwia rezygnacje z oferty danemu użytkownikowi /// </summary> /// <param name="context">Kontekst bazy danych</param> /// <param name="offerId">Id oferty</param> /// <param name="username">Nazwa użytkownika</param> /// <returns></returns> public static bool ResignOffer(IAccommodationContext context, int offerId, string username) { try { Offer offer = context.Offers.FirstOrDefault(o => o.Id == offerId); HistoricalOffer historicalOffer = context.HistoricalOffers.FirstOrDefault(ho => ho.OriginalOfferId == offer.Id); User customer = context.Users.FirstOrDefault(u => u.Username.Equals(username)); User vendor = context.Users.FirstOrDefault(x => x.Id == offer.VendorId); if (offer == null || customer == null) { return(false); } if (!offer.IsBooked) { return(false); } OfferInfo offerInfo = context.OfferInfo.FirstOrDefault(o => o.Id == offer.OfferInfoId); UserData customerData = context.UserData.FirstOrDefault(x => x.Id == customer.UserDataId); UserData vendorData = context.UserData.FirstOrDefault(x => x.Id == vendor.UserDataId); Room room = context.Rooms.FirstOrDefault(x => x.Id == offer.RoomId); Place place = context.Places.FirstOrDefault(x => x.Id == room.PlaceId); offer.IsBooked = false; offer.Customer = null; historicalOffer.IsBooked = false; historicalOffer.Customer = null; context.SaveChanges(); //Wysłanie powiadomienia mailowego, ostatni parametr oznacza rezygnację EmailNotification.SendNotification(offerInfo, place, vendorData, customerData, room, false); return(true); } catch (Exception ex) { return(false); } }
public async Task <ActionResult <string> > GetQueueInfo(string ticker, string type) { Dictionary <decimal, OfferInfo> queueInfo = new Dictionary <decimal, OfferInfo>(); IEnumerable <StockOffer> query = _context.StockOffers.AsQueryable().Where(s => s.Ticker == ticker && s.Order_Type == type).OrderByDescending(s => s.Target); foreach (StockOffer offer in query) { if (queueInfo.ContainsKey(offer.Target)) { queueInfo[offer.Target].Amount += offer.Amount; } else { OfferInfo info = new OfferInfo() { Amount = offer.Amount, Target = offer.Target }; queueInfo.Add(info.Target, info); } } IEnumerable <OfferInfo> infoList = null; if (type == "SELL") { infoList = queueInfo.Values.TakeLast(10); } else { infoList = queueInfo.Values.Take(10); } return(JsonConvert.SerializeObject(infoList)); }
public IHttpActionResult RemoveOfferAsync(OfferEditDataDto dto) { using (var context = _provider.GetNewContext()) { using (var transaction = new TransactionScope()) { User user = context.Users.FirstOrDefault(x => x.Username.Equals(dto.Username)); if (user == null) { return(NotFound()); } Offer offer = context.Offers.FirstOrDefault(x => x.Id == dto.OfferId); if (offer == null) { return(NotFound()); } OfferInfo offerInfo = context.OfferInfo.FirstOrDefault(x => x.Id == offer.OfferInfoId); Room room = context.Rooms.FirstOrDefault(x => x.Id == offer.RoomId); Place place = context.Places.FirstOrDefault(x => x.Id == room.PlaceId); Address address = context.Addresses.FirstOrDefault(x => x.Id == place.AddressId); var ho = context.HistoricalOffers.FirstOrDefault(h => h.OriginalOfferId == offer.Id); if (ho != null) { ho.OriginalOffer = null; } //usuń z bazy ofertę oraz jej dane context.Offers.Remove(offer); user?.MyOffers?.Remove(offer); context.SaveChanges(); transaction.Complete(); } } return(Ok()); }
public async Task SearchResultAsync() { try { IEnumerable <Offer> offers = await SearchAsync(); foreach (var offer in offers) { Room r = await _roomsProxy.Get(offer.RoomId); Place p = await _placesProxy.Get(r.PlaceId); OfferInfo oi = await _oiProxy.Get(offer.OfferInfoId); Address a = await _addressProxy.Get(p.AddressId); p.Address = a; offer.Room = r; offer.Room.Place = p; offer.OfferInfo = oi; } SearchingResults = offers.Select(o => new DisplayableOfferViewModel(new DisplayableOffer(o))); foreach (var displayableOfferViewModel in SearchingResults) { displayableOfferViewModel.OfferReserved += (x, e) => OnOfferReserved(x, e); } } catch (Exception) { MessageDialog md = new MessageDialog() { Title = "Błąd", Message = "Błąd systemu wyszukiwania" }; md.ShowDialog(); } }
public void GetApiData() { int pageCount = 0; var listNetworks = JsonConvert.DeserializeObject <List <NetworkInfo> >(File.ReadAllText(Utils.networkConfigFileName)); var netInfo = listNetworks.Find(x => x.NetworkUrl == this.NetworkUrl && x.APIKey == this.ApiKey); if (netInfo == null) { Logger.print($"Network Not found!"); return; } string url = apiUrl.Replace("{qcode.net}", NetworkUrl).Replace("{apikey}", ApiKey).Replace("{aff_id}", netInfo.UserId); if (!string.IsNullOrEmpty(Settings.QcodeNetName)) { url = url.Replace("{namenet}", Settings.QcodeNetName); } else { url = url.Replace("&namenet={namenet}", ""); } while (true) { if (pageCount > Settings.EndWith) { Logger.print("[Qcode] Get successed!"); break; } string result = ""; try { Logger.print($"[QCode] Getting {pageCount}..."); string reqUrl = url.Replace("{count}", (pageCount * 500).ToString()); Debug.WriteLine(reqUrl); using (HttpRequest req = new HttpRequest()) { result = req.Get(reqUrl).ToString(); } JArray obj = JArray.Parse(result); if (obj == null || obj.Count <= 0) { Logger.print($"[QCode] Successed"); break; } for (int i = 0; i < obj.Count; i++) { var info = obj[i]; //Debug.WriteLine(info); OfferInfo offer = new OfferInfo { Id = Utils.GetObjectByToken(info, "id").ToString(), Name = Utils.GetObjectByToken(info, "name").ToString(), Tracking = Utils.GetObjectByToken(info, "tracking").ToString(), Payout = double.Parse(Utils.GetObjectByToken(info, "point").ToString()), PreviewUrl = Utils.GetObjectByToken(info, "preview").ToString(), Platform = (Convert.ToInt32(info["typeagent"]) == 1) ? "iOS" : "Android" }; List <string> listCountries = JsonConvert.DeserializeObject <List <string> >($"{info["geo"].ToString().Trim()}").Where(x => x != "").Select(x => x.Trim()).ToList(); bool isCountriesAllowed = false; for (int j = 0; j < Settings.Countries.Count; j++) { if (Utils.IsCountryAllowed(Settings.Countries[j], listCountries)) { offer.Country = listCountries[0]; isCountriesAllowed = true; break; } } if (isCountriesAllowed && Utils.IsPassedSetting(Settings, offer, true)) { if (Settings.GetName.Count <= 0 || Utils.IsExitsFromList(Settings.GetName, $"{info["name"]}") || Utils.IsExitsFromList(Settings.GetName, $"{info["preview"]}") || Utils.IsExitsFromList(Settings.GetName, $"{info["description"]}")) { Utils.WriteOfferInfo(offer, Settings.SavePath); } } } pageCount++; } catch (Exception ex) { Logger.print($"Parser ERROR: {ex.Message}"); break; } } }
public void GetApiData() { Logger.print($"[Inhouse] Getting data from {this.NetworkUrl}..."); string data = GetData(); if (data.Contains("Invalid token")) { Logger.print("Invalid token!!!"); return; } if (data == "ERROR") { Logger.print("Network ERROR!!!"); return; } JObject jObject = JObject.Parse(data); string json = jObject.GetValue("offers").ToString(); if (json.Equals("[]")) { Logger.print("Parser ERROR!!!"); return; } JObject obj = JObject.Parse(json); if (obj.Count > 0) { foreach (KeyValuePair <string, JToken> item in obj) { try { //Debug.WriteLine(item); JArray objArr = JArray.Parse(item.ToString()); if (objArr.Count >= 2) { JToken jToken = objArr[1]; if ($"{jToken["Status"]}".ToLower().Equals("active")) { OfferInfo offerInfo = new OfferInfo { Id = jToken["ID"], Name = jToken["Name"].ToString(), PreviewUrl = $"{jToken["Preview_url"]}", Tracking = $"{jToken["Tracking_url"]}", Platform = $"{jToken["Platforms"].ToString().ToLower()}", Country = $"{jToken["Countries"]}", Payout = double.Parse($"{jToken["Payout"]}") }; List <string> countries = $"{jToken["Countries"]}".Split(',').ToList(); bool isCountriesAllowed = false; for (int j = 0; j < Settings.Countries.Count; j++) { if (Utils.IsCountryAllowed(Settings.Countries[j], countries)) { isCountriesAllowed = true; break; } } if (isCountriesAllowed && Utils.IsPassedSetting(Settings, offerInfo)) { if (Settings.GetName.Count <= 0 || Utils.IsExitsFromList(Settings.GetName, offerInfo.Name) || Utils.IsExitsFromList(Settings.GetName, offerInfo.PreviewUrl)) { Utils.WriteOfferInfo(offerInfo, Settings.SavePath); } } } } } catch (Exception ex) { Logger.print($"Parser ERROR: {ex.Message}"); } } Logger.print($"Success!"); } }
//private IList<ItemBuyBoxResponse> RequestItemsBuyBoxByAdv(ILogService logger, IList<Item> items, AmazonApi api) //{ // var results = new List<ItemBuyBoxResponse>(); // var index = 0; // //var indexToSleep = 0; // while (index < items.Count) // { // var checkedItems = items.Skip(index).Take(10).ToList(); // var resp = RetryHelper.ActionWithRetries(() => // api.RetrieveOffersWithMerchant(logger, checkedItems.Select(i => i.ASIN).ToList()), // logger); // if (resp != null && resp.Items != null && resp.Items.Any() && resp.Items[0].Item != null) // { // foreach (var item in checkedItems) // { // var status = BuyBoxStatusCode.Undefined; // decimal? price = null; // decimal? salePrice = null; // decimal? amountSaved = null; // string merchantName = null; // var el = resp.Items[0].Item.FirstOrDefault(i => i.ASIN == item.ASIN); // if (el != null && el.Offers != null) // { // if (el != null && el.Offers != null && el.Offers.Offer != null) // { // var itemId = item.Id; // var firstOffer = el.Offers.Offer.FirstOrDefault(); // if (firstOffer != null) // { // merchantName = firstOffer.Merchant.Name; // if (String.IsNullOrEmpty(merchantName)) // { // status = BuyBoxStatusCode.NoWinner; // } // else // { // status = (merchantName == AddressService.Name) // ? BuyBoxStatusCode.Win // : BuyBoxStatusCode.NotWin; // } // if (firstOffer.OfferListing != null && firstOffer.OfferListing.Length > 0) // { // //Note: firstOffer.OfferListing[0].Price.Amount stored price in "1499" format without any separators // if (firstOffer.OfferListing[0].Price != null) // { // price = StringHelper.TryGetInt(firstOffer.OfferListing[0].Price.Amount); // if (price != null) // price = price/100; // } // if (firstOffer.OfferListing[0].SalePrice != null) // { // salePrice = StringHelper.TryGetInt(firstOffer.OfferListing[0].SalePrice.Amount); // if (salePrice != null) // salePrice = salePrice/100; // } // if (firstOffer.OfferListing[0].AmountSaved != null) // { // amountSaved = StringHelper.TryGetInt(firstOffer.OfferListing[0].AmountSaved.Amount); // if (amountSaved != null) // amountSaved = amountSaved/100; // } // } // } // } // } // results.Add(new ItemBuyBoxResponse() // { // ASIN = item.ASIN, // CheckedDate = DateTime.UtcNow, // Status = status, // WinnerPrice = price, // WinnerSalePrice = salePrice, // WinnerAmountSaved = amountSaved, // WinnerMerchantName = merchantName // }); // } // } // index += 10; // Thread.Sleep(TimeSpan.FromSeconds(5)); // } // return results; //} public int ProcessOfferChanges(AmazonSQSReader reader, IList <string> sellerIds) { var index = 0; var maxCount = 100; var existNotification = true; using (var db = _dbFactory.GetRWDb()) { while (index < maxCount && existNotification) { var notifications = reader.GetNotification(); existNotification = notifications.Any(); _log.Info("Receive notifications, count=" + notifications.Count); foreach (var n in notifications) { try { var changeDate = AmazonSQSReader.TryGetDate( n.NotificationPayload.AnyOfferChangedNotification.OfferChangeTrigger .TimeOfOfferChange); if (!changeDate.HasValue) { throw new ArgumentNullException("ChangeDate"); } _log.Info("Notification change date=" + changeDate); LowestPrice buyBoxPrice = null; OfferCount buyBoxAmazonOffers = null; OfferCount buyBoxMerchantOffers = null; LowestPrice merchantLowestPrices = null; LowestPrice amazonLowestPrices = null; OfferCount merchantOffers = null; OfferCount amazonOffers = null; if (n.NotificationPayload.AnyOfferChangedNotification != null && n.NotificationPayload.AnyOfferChangedNotification.Summary != null) { if (n.NotificationPayload.AnyOfferChangedNotification.Summary.BuyBoxPrices != null) { buyBoxPrice = n.NotificationPayload.AnyOfferChangedNotification.Summary.BuyBoxPrices .FirstOrDefault( b => b.Condition == "new"); } if (n.NotificationPayload.AnyOfferChangedNotification.Summary.BuyBoxEligibleOffers != null) { buyBoxAmazonOffers = n.NotificationPayload.AnyOfferChangedNotification.Summary .BuyBoxEligibleOffers .FirstOrDefault(o => o.FulfillmentChannel == "Amazon" && o.Condition == "new"); buyBoxMerchantOffers = n.NotificationPayload.AnyOfferChangedNotification.Summary.BuyBoxEligibleOffers .FirstOrDefault( o => o.FulfillmentChannel == "Merchant" && o.Condition == "new"); } if (n.NotificationPayload.AnyOfferChangedNotification.Summary.OfferCounts != null) { amazonOffers = n.NotificationPayload.AnyOfferChangedNotification.Summary.OfferCounts .FirstOrDefault(o => o.FulfillmentChannel == "Amazon" && o.Condition == "new"); merchantOffers = n.NotificationPayload.AnyOfferChangedNotification.Summary .OfferCounts .FirstOrDefault(o => o.FulfillmentChannel == "Merchant" && o.Condition == "new"); } if (n.NotificationPayload.AnyOfferChangedNotification.Summary.LowestPrices != null) { amazonLowestPrices = n.NotificationPayload.AnyOfferChangedNotification.Summary .LowestPrices .FirstOrDefault( p => p.FulfillmentChannel == "Amazon" && p.Condition == "new"); merchantLowestPrices = n.NotificationPayload.AnyOfferChangedNotification.Summary .LowestPrices.FirstOrDefault( p => p.FulfillmentChannel == "Merchant" && p.Condition == "new"); } } var offerChangeEvent = new OfferChangeEvent() { ASIN = n.NotificationPayload.AnyOfferChangedNotification.OfferChangeTrigger.ASIN, MarketplaceId = n.NotificationPayload.AnyOfferChangedNotification.OfferChangeTrigger.MarketplaceId, ChangeDate = changeDate.Value, BuyBoxLandedPrice = buyBoxPrice != null && buyBoxPrice.LandedPrice != null ? decimal.Parse(buyBoxPrice.LandedPrice.Amount) : (decimal?)null, BuyBoxListingPrice = buyBoxPrice != null && buyBoxPrice.ListingPrice != null ? decimal.Parse(buyBoxPrice.ListingPrice.Amount) : (decimal?)null, BuyBoxShipping = buyBoxPrice != null && buyBoxPrice.Shipping != null ? decimal.Parse(buyBoxPrice.Shipping.Amount) : (decimal?)null, BuyBoxEligibleOffersAmazon = buyBoxAmazonOffers != null ? AmazonSQSReader.TryGetInt(buyBoxAmazonOffers.Value) : (int?)null, BuyBoxEligibleOffersMerchant = buyBoxMerchantOffers != null ? AmazonSQSReader.TryGetInt(buyBoxMerchantOffers.Value) : (int?)null, ListPrice = AmazonSQSReader.GetPrice( n.NotificationPayload.AnyOfferChangedNotification.Summary.ListPrice), LowestLandedPriceAmazon = amazonLowestPrices != null ? AmazonSQSReader.GetPrice(amazonLowestPrices.LandedPrice) : null, LowestListingPriceAmazon = amazonLowestPrices != null ? AmazonSQSReader.GetPrice(amazonLowestPrices.ListingPrice) : null, LowestShippingAmazon = amazonLowestPrices != null ? AmazonSQSReader.GetPrice(amazonLowestPrices.Shipping) : null, LowestLandedPriceMerchant = merchantLowestPrices != null ? AmazonSQSReader.GetPrice(merchantLowestPrices.LandedPrice) : null, LowestListingPriceMerchant = merchantLowestPrices != null ? AmazonSQSReader.GetPrice(merchantLowestPrices.ListingPrice) : null, LowestShippingMerchant = merchantLowestPrices != null ? AmazonSQSReader.GetPrice(merchantLowestPrices.Shipping) : null, NumberOfOffersAmazon = amazonOffers != null?AmazonSQSReader.TryGetInt(amazonOffers.Value) : (int?)null, NumberOfOffersMerchant = merchantOffers != null ? AmazonSQSReader.TryGetInt(merchantOffers.Value) : (int?)null, CreateDate = _time.GetAppNowTime(), }; db.OfferChangeEvents.Add(offerChangeEvent); db.Commit(); var offers = new List <OfferInfo>(); foreach (var offer in n.NotificationPayload.AnyOfferChangedNotification.Offers) { var newOffer = new OfferInfo() { OfferChangeEventId = offerChangeEvent.Id, IsBuyBoxWinner = offer.IsBuyBoxWinner, IsFeaturedMerchant = offer.IsFeaturedMerchant, IsFulfilledByAmazon = offer.IsFulfilledByAmazon, ShipsDomestically = offer.ShipsDomestically, SellerId = offer.SellerId, FeedbackCount = offer.SellerFeedbackRating != null ? AmazonSQSReader.TryGetInt(offer.SellerFeedbackRating.FeedbackCount) : null, SellerPositiveFeedbackRating = offer.SellerFeedbackRating != null ? AmazonSQSReader.TryGetInt( offer.SellerFeedbackRating.SellerPositiveFeedbackRating) : null, ListingPrice = AmazonSQSReader.GetPrice(offer.ListingPrice), Shipping = AmazonSQSReader.GetPrice(offer.Shipping), ShippingTimeMaximumHours = AmazonSQSReader.TryGetInt(offer.ShippingTime.MaximumHours), ShippingTimeMinimumHours = AmazonSQSReader.TryGetInt(offer.ShippingTime.MinimumHours), ShippingTimeAvailabilityType = offer.ShippingTime.AvailabilityType, ShipsFromCountry = offer.ShipsFrom != null ? offer.ShipsFrom.Country : null, ShipsFromState = offer.ShipsFrom != null ? offer.ShipsFrom.State : null, CreateDate = _time.GetAppNowTime(), }; db.OfferInfoes.Add(newOffer); offers.Add(newOffer); } db.Commit(); //Update buybox BuyBoxStatusCode status = BuyBoxStatusCode.NoWinner; var winOffer = offers.FirstOrDefault(o => o.IsBuyBoxWinner); if (winOffer != null) { if (sellerIds.Contains(winOffer.SellerId)) { status = BuyBoxStatusCode.Win; } else { status = BuyBoxStatusCode.NotWin; } } db.BuyBoxStatus.Update(_log, _time, new BuyBoxStatusDTO() { ASIN = offerChangeEvent.ASIN, MarketplaceId = offerChangeEvent.MarketplaceId, CheckedDate = offerChangeEvent.ChangeDate, WinnerPrice = offerChangeEvent.BuyBoxListingPrice, Status = status, }, AmazonUtils.GetMarketByMarketplaceId(offerChangeEvent.MarketplaceId), offerChangeEvent.MarketplaceId); } catch (Exception ex) { _log.Info("Process notification", ex); } } index++; } } return(index); }
public void GetApiData() { foreach (string country in Settings.Countries) { int count = 0; while (true) { try { count++; Logger.print("Get Page: " + count.ToString()); string data = GetData(count, country.ToUpper()); if (data.Contains("Invalid token")) { Logger.print("Invalid Token!!!"); break; } if (data == "ERROR") { Logger.print("Network ERROR!!!"); break; } JObject jObject = JObject.Parse(data); string json = jObject.GetValue("offers").ToString(); if (json.Equals("[]")) { Logger.print("Success!"); break; } //Debug.WriteLine(json); JArray listOffers = JArray.Parse(json); if (listOffers != null && listOffers.Count > 0) { listOffers.ToList().ForEach(obj => { try { //Debug.WriteLine(obj); OfferInfo offerInfo = new OfferInfo { Id = obj["offer_id"], Name = obj["title"].ToString(), PreviewUrl = obj["preview_url"].ToString(), Tracking = obj["link"].ToString(), Country = country }; JToken paymentsInfo = JArray.Parse(Utils.GetObjectByToken(obj, "payments").ToString())[0]; offerInfo.Platform = JsonConvert.DeserializeObject <List <string> >(paymentsInfo["os"].ToString().ToLower())[0]; offerInfo.Payout = double.Parse($"{paymentsInfo["revenue"]}"); List <string> listCountries = JsonConvert.DeserializeObject <List <string> >(paymentsInfo["countries"].ToString()); if (Utils.IsCountryAllowed(country, listCountries) && Utils.IsPassedSetting(Settings, offerInfo)) { if (Settings.GetName.Count <= 0 || Utils.IsExitsFromList(Settings.GetName, offerInfo.Name) || Utils.IsExitsFromList(Settings.GetName, obj["description_lang"].ToString()) || Utils.IsExitsFromList(Settings.GetName, offerInfo.PreviewUrl)) { if (offerInfo.Country.ToLower().Equals("all")) { offerInfo.Country = listCountries[0]; } Utils.WriteOfferInfo(offerInfo, Settings.SavePath); } } } catch (Exception ex) { Debug.WriteLine($"Parse ERROR:" + ex.Message); } }); } } catch (Exception ex) { Logger.print($"Parser ERROR: {ex.Message}"); } } } }
public void GetApiData() { foreach (string country in Settings.Countries) { int count = 0; while (true) { try { //{"code":0,"message":"Success","data":{"rowset":[],"totalPages":1,"totalRows":68,"offset":2,"limit":100}} count++; Logger.print("Get Page: " + count.ToString()); string data = GetData(count, country); if (data.Contains("API Key Wrong")) { Logger.print("Invalid Token!!!"); break; } if (data == "ERROR") { Logger.print("Network ERROR!!!"); break; } JObject jObject = JObject.Parse(data); string json = JObject.Parse(jObject.GetValue("data").ToString()).GetValue("rowset").ToString(); if (json.Equals("[]")) { Logger.print("Success!"); break; } //Debug.WriteLine(json); JArray jObjArr = JArray.Parse(json); jObjArr.ToList().ForEach(x => { try { Debug.WriteLine(x); var jObj = JObject.Parse(x["offer"].ToString()); if (jObj["status"].ToString().ToLower().Equals("active")) { var offerInfo = new OfferInfo { Id = $"{jObj["id"]}", Name = $"{jObj["name"]}", Tracking = $"{jObj["tracking_link"]}", PreviewUrl = $"{jObj["preview_url"]}", Payout = double.Parse($"{jObj["payout"]}"), }; offerInfo.Country = JObject.Parse(x["offer_geo"].ToString()).GetValue("target")[0]["country_code"].ToString(); offerInfo.Platform = JObject.Parse(x["offer_platform"].ToString()).GetValue("target")[0]["system"].ToString(); if (Utils.IsCountryAllowed(country, new List <string> { offerInfo.Country }) && Utils.IsPassedSetting(Settings, offerInfo)) { if (Settings.GetName.Count <= 0 || Utils.IsExitsFromList(Settings.GetName, offerInfo.Name) || Utils.IsExitsFromList(Settings.GetName, offerInfo.PreviewUrl)) { Utils.WriteOfferInfo(offerInfo, Settings.SavePath); } } } } catch (Exception ex) { Debug.WriteLine($"Parser ERROR:" + ex.Message); } }); } catch (Exception ex) { Debug.WriteLine("CC" + ex.Message); } } } }