public static bool GetSales(DateTime fromDate, DateTime toDate, Account account, BackgroundWorker backgroundWorker) { List <Transaction> transactions = new List <Transaction>(); JArray jOrderInfoArray = new JArray(); var i = 0; while (true) { try { i++; var response = EnvatoAPIRequest( $"https://api.envato.com/v3/market/user/statement?page={i}&from_date={fromDate:yyyy-MM-dd}&to_date={toDate:yyyy-MM-dd}", account); var responseStream = response?.GetResponseStream(); if (responseStream != null) { using (var streamReader = new StreamReader(responseStream)) { var orderInfoJson = streamReader.ReadToEnd(); var tempJArray = JArray.Parse(orderInfoJson); jOrderInfoArray.Merge(tempJArray); if (tempJArray.Count.Equals(0)) { break; } } } } catch (WebException) { return(false); } } int progress = 0; backgroundWorker.ReportProgress(progress, 1); using (var db = new SalesManagerContext()) { for (var count = 0; count < jOrderInfoArray.Count; count++) { var jToken = jOrderInfoArray[count]; var type = jToken["type"].ToString(); if (type.Equals("Withdrawal Request") || type.Equals("Skrill Fee") || type.Equals("Refund") || type.Equals("Withdrawal Cancellation") || type.Equals("Skrill Fee Reversal") || type.Equals("Purchase") || type.Equals("Agreement Change") || type.Equals("Manual Adjustment") || type.Equals("Withdrawal Rejection")) { backgroundWorker.ReportProgress(count + 1, jOrderInfoArray.Count, 1); continue; } var transaction = new Transaction { OrderID = jToken["order_id"].ToString(), ReceivedAmount = 0, Date = ((DateTimeOffset)jToken["date"]).DateTime, Account = db.Accounts.First(ac => ac.ID.Equals(account.ID)) }; var detail = jToken["detail"].ToString(); if (type.Equals("Referral Cut")) { transaction.Detail = detail; transaction.ReceivedAmount = (double)jToken["amount"]; if ( db.Transactions.Any( tr => tr.Product.ID.Equals(2) && tr.Date.Equals(transaction.Date) && tr.ReceivedAmount.Equals(transaction.ReceivedAmount) && tr.Detail.Equals(transaction.Detail))) { backgroundWorker.ReportProgress(count + 1, jOrderInfoArray.Count, 1); continue; } transaction.Product = db.Products.First(product => product.ID.Equals(2)); transaction.Country = db.Countries.First(country => country.ID.Equals(1)); transaction.PartnerShare = 0; db.Transactions.Add(transaction); db.SaveChanges(); backgroundWorker.ReportProgress(count + 1, jOrderInfoArray.Count, 1); continue; } int itemID = Convert.ToInt32(jToken["item_id"]); transaction.Product = db.Products.FirstOrDefault(product => product.ID.Equals(itemID)); if (transaction.Product == null) { var newProduct = new Product { ID = itemID, Account = account }; db.Products.Add(newProduct); db.SaveChanges(); transaction.Product = newProduct; } var tempTransaction = transactions.FirstOrDefault( tr => tr.OrderID.Equals(transaction.OrderID) && tr.Date.Equals(transaction.Date) && tr.Product.ID.Equals(transaction.Product.ID)); if (tempTransaction != null) { transaction = tempTransaction; } else { if (db.Transactions.Include(tr => tr.Product).Any( tr => tr.OrderID.Equals(transaction.OrderID) && tr.Date.Equals(transaction.Date) && tr.Product.ID.Equals(transaction.Product.ID))) { backgroundWorker.ReportProgress(count + 1, jOrderInfoArray.Count, 1); continue; } transactions.Add(transaction); } if (!type.Equals("Author Fee")) { if (string.IsNullOrEmpty(transaction.Detail)) { transaction.Detail = detail; } else { if (detail.Contains("(")) { var index = detail.LastIndexOf("(", StringComparison.InvariantCulture); transaction.Detail += $" {detail.Substring(index)}"; } } if (transaction.Country == null) { if (string.IsNullOrEmpty(transaction.Product.Name)) { transaction.Product.Name = detail.Split('(')[0].Replace("Reversal of", "").Replace("Refund for", "").Trim(); db.Products.Update(transaction.Product); db.SaveChanges(); } var orderCountry = jToken["other_party_country"].ToString(); transaction.Country = db.Countries.FirstOrDefault(country => country.Name.Equals(orderCountry)); if (transaction.Country == null) { var countryObject = new Country { Name = orderCountry, Tax = 0 }; db.Countries.Add(countryObject); db.SaveChanges(); transaction.Country = countryObject; } } } if (detail.Contains("extended support") || detail.Contains("support extension")) { transaction.SupportAmount += (double)jToken["amount"]; backgroundWorker.ReportProgress(count + 1, jOrderInfoArray.Count, 1); continue; } if (jToken["us_rwt"].Type != JTokenType.Null) { transaction.Tax += (double)jToken["us_rwt"]; } if (type.Equals("Author Fee") || type.Equals("Author Fee Refund") || type.Equals("Author Fee Reversal")) { transaction.PriceAfterAuthorFee += Math.Abs((double)jToken["amount"]); } else { transaction.PriceAfterBuyerFee += (double)jToken["price"]; } transaction.ReceivedAmount += (double)jToken["amount"]; backgroundWorker.ReportProgress(count + 1, jOrderInfoArray.Count, 1); } foreach (var transaction in transactions) { if (transaction.Detail.ToLower().Contains("extended support") && !transaction.Detail.ToLower().Contains("included support")) { db.Transactions.Add(transaction); continue; } transaction.PriceAfterAuthorFee = transaction.PriceAfterBuyerFee - transaction.PriceAfterAuthorFee; transaction.GetPartnerShare(); db.Transactions.Add(transaction); } db.SaveChanges(); foreach (var transaction in transactions.Where(tr => tr.ReceivedAmount < 0)) { var refundedTransaction = db.Transactions.FirstOrDefault( tr => !tr.ID.Equals(transaction.ID) && tr.OrderID.Equals(transaction.OrderID) && tr.Product.ID.Equals(transaction.Product.ID) && tr.PriceAfterAuthorFee.Equals(transaction.PriceAfterAuthorFee)); if (refundedTransaction != null) { transaction.ReceivedAmount = refundedTransaction.ReceivedAmount * -1; transaction.PartnerShare = refundedTransaction.PartnerShare * -1; transaction.Detail += $" (Original Order was from {refundedTransaction.Date.ToShortDateString()})"; } } db.SaveChanges(); } return(true); }
public FormMain() { //#if DEBUG // var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "RBSoft", // "Sales Manager", "database.smdb"); // if (File.Exists(databasePath)) // { // File.Delete(databasePath); // } //#endif InitializeComponent(); dateTimePickerFrom.Value = new DateTime(dateTimePickerTo.Value.Year, dateTimePickerTo.Value.Month, 1, 0, 0, 0); dateTimePickerTo.Value = dateTimePickerTo.Value.AbsoluteEnd(); dateTimePickerFrom.MaxDate = dateTimePickerTo.Value.AbsoluteStart(); HelperMethods.FixFonts(this); WindowSettings.Restore(Settings.Default.WindowSettings, this); Application.CurrentCulture = new CultureInfo("en-US") { NumberFormat = { CurrencyNegativePattern = 1 } }; objectListViewTransactions.RestoreState( Convert.FromBase64String(Settings.Default.ObjectListViewTransactionsState)); olvColumnDate.AspectGetter += delegate(object rowObject) { var transaction = rowObject as Transaction; return(transaction?.Date.ToString("d", Application.CurrentCulture) ?? DateTime.Now.ToString("d", Application.CurrentCulture)); }; objectListViewTransactions.AboutToCreateGroups += ObjectListViewTransactionsOnAboutToCreateGroups; objectListViewTransactions.BeforeCreatingGroups += (sender, args) => { args.Parameters.GroupComparer = args.Parameters.GroupByColumn.Equals(olvColumnDate) ? new GroupDateComparer(args.Parameters.PrimarySortOrder) : null; }; thirtyMinutesToolStripMenuItem.Checked = Settings.Default.AutoRefreshInterval.Equals(30 * 60 * 1000); oneHourToolStripMenuItem.Checked = Settings.Default.AutoRefreshInterval.Equals(60 * 60 * 1000); twoHourToolStripMenuItem.Checked = Settings.Default.AutoRefreshInterval.Equals(2 * 60 * 60 * 1000); threeHourToolStripMenuItem.Checked = Settings.Default.AutoRefreshInterval.Equals(3 * 60 * 60 * 1000); fourHourToolStripMenuItem.Checked = Settings.Default.AutoRefreshInterval.Equals(4 * 60 * 60 * 1000); enableUpdateNotificationToolStripMenuItem.Checked = Settings.Default.EnableUpdateNotification; minimizeToTrayToolStripMenuItem.Checked = Settings.Default.MinimizeToTray; using (var db = new SalesManagerContext()) { db.Database.EnsureCreated(); if (!db.Countries.Any()) { var referral = new Country { ID = 1, Name = "Referral", Tax = 0 }; db.Countries.Add(referral); db.SaveChanges(); } if (!db.Products.Any()) { var all = new Product { ID = 1, Name = "All", BuyerFee = 0, AuthorFee = 0, Price = 0, PartnerShare = 0, Account = null }; db.Products.Add(all); var referral = new Product { ID = 2, Name = "Referral", BuyerFee = 0, AuthorFee = 0, Price = 0, PartnerShare = 0, Account = null }; db.Products.Add(referral); db.SaveChanges(); } comboBoxProducts.DisplayMember = "Name"; comboBoxAccounts.DisplayMember = "Name"; } _timer = new Timer { Interval = Settings.Default.AutoRefreshInterval, Enabled = true }; _timer.Tick += toolStripButtonUpdate_Click; _timer.Start(); filterTextBox.Select(); }