public static async Task <ResultsItem> UpdateUserCoinAsync(LocalCoins.CryptoCoin coin) { try { using (PegasunDBContext db = new PegasunDBContext()) { Coins serviceCoin = db.Coins.FirstOrDefault(x => x.CoinId == coin.CoinId); if (serviceCoin == null) { return(ResultsItem.Error("This coin was not found.")); } serviceCoin.Shares = coin.Shares; serviceCoin.CoinCurrency = (short)coin.CoinCurrency; serviceCoin.PricePerUnit = coin.PricePerUnit; serviceCoin.TotalPricePaidUsd = coin.TotalPricePaidUSD; serviceCoin.Exchange = (short)coin.Exchange; serviceCoin.OrderType = (short)coin.OrderType; serviceCoin.OrderDate = coin.OrderDate; serviceCoin.SoldCoinCurrency = (short)coin.SoldCoinCurrency; serviceCoin.SoldPricePerUnit = coin.SoldPricePerUnit; serviceCoin.TotalSoldPricePaidUsd = coin.TotalSoldPricePaidUSD; db.Update(serviceCoin); await db.SaveChangesAsync(); } return(ResultsItem.Success("Successfully updated coin.")); } catch (Exception ex) { Utilities.LogException(new[] { "UpdateUserCoinAsync", $"coinId:{coin.CoinId},portfolioId:{coin.PortfolioId}" }, ex); return(ResultsItem.Error($"Unable to updated coin. {ex.Message}")); } }
public static ResultsPair <LocalCoins.Portfolio> UpdatePortfolio(int portfolioId, string portfolioName, Types.PortfolioDisplayType displayType, bool isDefault) { try { using (PegasunDBContext db = new PegasunDBContext()) { Portfolios portfolio = db.Portfolios.FirstOrDefault(x => x.PortfolioId == portfolioId); if (portfolio != null) { portfolio.Name = portfolioName.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); portfolio.DisplayType = (short)displayType; portfolio.IsDefault = isDefault; db.Update(portfolio); db.SaveChanges(); } return(ResultsPair.Create(ResultsItem.Success("Successfully updated portfolio name."), portfolio.Adapt <LocalCoins.Portfolio>())); } } catch (Exception ex) { Utilities.LogException(new[] { "UpdatePortfolio", $"portfolioId:{portfolioId},portfolioName:{portfolioName}" }, ex); return(ResultsPair.CreateError <LocalCoins.Portfolio>($"Unable to update portfolio. {ex.Message}")); } }
private static async Task <ResultsPair <LocalAccount.PTUserInfo> > CreateNewPTUserInfo(LocalAccount.PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { PTUserInfo ptUserInfo = new PTUserInfo { UserId = user.UserId, SubscriptionLevel = (byte)SubscriptionLevel.Free, SubscriptionExpireDate = null }; db.PTUserInfo.Add(ptUserInfo); await db.SaveChangesAsync(); LocalAccount.PTUserInfo localSubscription = ptUserInfo.Adapt <LocalAccount.PTUserInfo>(); return(ResultsPair.Create(ResultsItem.Success("Successfully created a new subscription."), localSubscription)); } } catch (Exception ex) { return(ResultsPair.CreateError <LocalAccount.PTUserInfo>($"Unable to create a new PTUserInfo: {ex.Message}")); } }
public async Task <JsonResult> CreateNewUser(PegaUser user) { if (!ModelState.IsValid) { return(Json(ResultsItem.Error(ModelState.GetAllErrorsString()))); } if (!Regex.IsMatch(user.Username, @"^[a-zA-Z0-9_\-\.]+$")) { return(Json(ResultsItem.Error("Username must contain only: Letters(A-Z), Numbers(0-9), _, -, or ."))); } if (!Utilities.IsValidEmailAddress(user.Email)) { return(Json("Please enter a valid email address.")); } var createPair = await AuthorizationLogic.CreateNewUser(user); if (createPair.Result.IsSuccess) { SetSession(Constant.Session.SessionCurrentUser, createPair.Value); TempData["UserCreatedTransferMessage"] = createPair.Result.Message; return(Json(ResultsItem.Success("Success"))); } return(Json(ResultsItem.Error(createPair.Result.Message))); }
public async Task <JsonResult> CurrentUserChangePassword(PegaUser user) { if (user.NewChangedPassword.Length < 8 || user.NewChangedPassword.Length > 30) { return(Json(ResultsItem.Error("Password changed failed: Password length must be from 8 - 30 characters."))); } if (user.NewChangedPassword != user.ConfirmNewChangedPassword) { return(Json(ResultsItem.Error("Passwords does not match."))); } if (CurrentUser.Username != user.Username) { return(Json(ResultsItem.Error("Username does not match."))); } // do-later: check if current pw is valid first. if (!AuthorizationLogic.AuthorizeUser(CurrentUser.Username, user.Password)) // Change password var pwChangeResult = await AuthorizationLogic.ChangePassword(user.Username, user.NewChangedPassword); if (!pwChangeResult.IsSuccess) { return(Json(pwChangeResult)); } HttpContext.Session.Clear(); string successMessage = "Your password has been successfully reset. Please login again"; TempData["message"] = successMessage; return(Json(ResultsItem.Success(successMessage))); }
public static async Task <ResultsItem> CreateBBComment(LocalCommunity.BBComment comment, LocalAccount.PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { comment.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); BBComments serviceComment = comment.Adapt <BBComments>(); serviceComment.CreateDate = DateTime.Now; serviceComment.UserId = user.UserId; serviceComment.Message = serviceComment.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); db.BBComments.Add(serviceComment); await db.SaveChangesAsync(); return(ResultsItem.Success("Successfully posted a new comment.")); } } catch (Exception ex) { Utilities.LogException(new[] { $"User:{user.Username}" }, ex); return(ResultsItem.Error($"Unable to create a comment. {ex.Message}")); } }
public async Task <IActionResult> ConfirmEmail(string username, string authCode) { ResultsItem emailResult = await AuthorizationLogic.ConfirmEmail(username, authCode); TempData["message"] = emailResult.Message; return(RedirectToAction("Index", "Home")); }
public async Task <JsonResult> ExecuteCoinChanges(CoinManagementVM vm) { ResultsItem validationResult = CoinManagementValidation(vm, isSoldMode: false); if (!validationResult.IsSuccess) { return(Json(validationResult)); } vm.Coin.OrderType = Types.OrderType.Buy; vm.Coin.Exchange = Types.Exchanges.Custom; vm.Coin.PortfolioId = vm.SelectedPortfolioID; if (vm.Coin.TotalPricePaidUSD.GetValueOrDefault() == 0) { vm.Coin.TotalPricePaidUSD = vm.Coin.OrderDate.Date == DateTime.Now.Date ? vm.Coin.Shares * CryptoLogic.GetLatestPriceOfSymbol(vm.Coin.Symbol, await GetAllCoinsMarketDetailsAPI()) : CryptoLogic.GenerateTotalPricePaidUSD(vm.Coin, await GetAllHistoricCoinPrices()); } var coinResult = vm.IsCreateMode ? await CryptoLogic.InsertCoinsToUserPortfolioAsync(new List <CryptoCoin> { vm.Coin }, CurrentUser, vm.SelectedPortfolioID) : await CryptoLogic.UpdateUserCoinAsync(vm.Coin, CurrentUser); return(Json(coinResult)); }
public static async Task <ResultsItem> CreateBBThread(LocalCommunity.BBThread thread, LocalAccount.PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { thread.Message = thread.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); thread.UserId = user.UserId; BBThreads serviceMessageThread = thread.Adapt <BBThreads>(); serviceMessageThread.CreateDate = DateTime.Now; serviceMessageThread.UserId = user.UserId; serviceMessageThread.Message = serviceMessageThread.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); serviceMessageThread.Title = serviceMessageThread.Title.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); db.BBThreads.Add(serviceMessageThread); await db.SaveChangesAsync(); return(ResultsItem.Success("Successfully created a new thread")); } } catch (Exception ex) { Utilities.LogException(new[] { $"User:{user.Username}" }, ex); return(ResultsItem.Error($"Unable to create a new thread. {ex.Message}")); } }
public static async Task <ResultsItem> DeleteBBThread(int threadId, LocalAccount.PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { BBThreads serviceThread = db.BBThreads.FirstOrDefault(x => x.ThreadId == threadId); if (serviceThread == null) { return(ResultsItem.Error("This thread was not found or has already been deleted.")); } if (serviceThread.UserId != user.UserId) { return(ResultsItem.Error("This thread belongs to another user.")); } db.Remove(serviceThread); await db.SaveChangesAsync(); return(ResultsItem.Success("Successfully deleted this thread. Please refresh the page to see changes.")); } } catch (Exception ex) { Utilities.LogException(new[] { $"User:{user.Username}" }, ex); return(ResultsItem.Error($"Unable to delete this thread. {ex.Message}")); } }
public static ResultsItem InsertNewAPI(LocalCoins.ExchangeApiInfo exchangeApiDetails, PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { ApiDetails serviceApi = new ApiDetails { Name = exchangeApiDetails.Name.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }), Exchange = (short)exchangeApiDetails.Exchange, ApiAction = (short)exchangeApiDetails.ApiAction, ApiPublic = Cryptography.Encrypt(exchangeApiDetails.ApiPublic, Types.EncryptionType.ApiKey_Public, user), ApiPrivate = Cryptography.Encrypt(exchangeApiDetails.ApiPrivate, Types.EncryptionType.ApiKey_Private, user), ApiThirdKey = exchangeApiDetails.ApiThirdKey.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }), DateAdded = DateTime.Now, UserId = user.UserId, }; db.ApiDetails.Add(serviceApi); db.SaveChanges(); } return(ResultsItem.Success("Successfully created a new API.")); } catch (Exception ex) { return(ResultsItem.Error($"Unable to create a new API. {ex.Message}")); } }
public static async Task <ResultsPair <LocalCoins.Portfolio> > InsertNewPortfolio(int userId, string portfolioName, Types.PortfolioDisplayType displayType, bool isDefault) { try { using (PegasunDBContext db = new PegasunDBContext()) { Portfolios portfolio = new Portfolios { UserId = userId, Name = portfolioName.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }), DisplayType = (short)displayType, IsDefault = isDefault }; db.Portfolios.Add(portfolio); await db.SaveChangesAsync(); return(ResultsPair.Create(ResultsItem.Success("Successfully created a new portfolio."), portfolio.Adapt <LocalCoins.Portfolio>())); } } catch (Exception ex) { return(ResultsPair.CreateError <LocalCoins.Portfolio>($"Unable to create a new portfolio. {ex.Message}")); } }
public static async Task <ResultsItem> DeleteUserCoinsAsync(List <CryptoCoin> coins, PegaUser user) { if (coins.Any(x => !IsValidDBRequest(user, x.PortfolioId, validatePortfolio: true).IsSuccess)) { return(ResultsItem.Error(Lang.PortfolioNotFound)); } return(await CryptoRepository.DeleteUserCoinAsync(coins)); }
public async Task <JsonResult> ImportSyncAPI(int apiId, int portfolioId) { ExchangeApiInfo exchangeApiInfo = CurrentUser.ExchangeApiList.FirstOrDefault(x => x.Id == apiId); if (exchangeApiInfo == null) { return(Json(ResultsItem.Error("This API Id cannot be found"))); } if (!CurrentUser.HasPortfolio(portfolioId)) { return(Json(ResultsItem.Error(Lang.PortfolioNotFound))); } // Test -> Move to .Tests solution //List<Core.Data.ServiceModels.ImportedCoin> importedCoins = FetchAPILogic.ImportCSV_Coins(exchangeApiInfo.Exchange, // System.IO.File.OpenRead(@"C:\Users\Ref\Downloads\pegatrade_importFiles\api_test1\2nd-half.csv")); List <Core.Data.ServiceModels.ImportedCoin> importedCoins = await FetchAPILogic.ImportAPI_Coins(exchangeApiInfo, CurrentUser); if (importedCoins.IsNullOrEmpty()) { return(Json(ResultsItem.Error(Lang.UnableToImportWrongKeyPermission))); } List <CryptoCoin> existingExchangeCoins = (await CryptoLogic.GetAllUserCoinsByPortfolioIdAsync(portfolioId)).Where(x => x.Exchange == exchangeApiInfo.Exchange).ToList(); DateTime latestDate = existingExchangeCoins.IsNullOrEmpty() ? DateTime.MinValue : existingExchangeCoins.Max(x => x.OrderDate); // Get rid of ANY imported coins that are less than already existing date. // We dont' want to mess with those, we just want to add new ones. importedCoins = importedCoins.Where(x => x.OrderDate > latestDate).ToList(); if (importedCoins.IsNullOrEmpty()) { Json(ResultsItem.Error(Lang.ApiAlreadyUptoDate)); } List <CryptoCoin> fetchedCoins = FetchAPILogic.FormatCoinsAndGenerateTotalPricePaid(importedCoins, await GetAllHistoricCoinPrices()); if (fetchedCoins.Count > 0) { // Get all current holding coins that will be affected by new coins. Delete them from db as well, we'll re-add them. existingExchangeCoins = existingExchangeCoins.Where(x => x.OrderType == Types.OrderType.Buy && fetchedCoins.Any(f => f.Symbol.EqualsTo(x.Symbol))).ToList(); await CryptoLogic.DeleteUserCoinsAsync(existingExchangeCoins, CurrentUser); existingExchangeCoins.ForEach(x => x.CoinId = 0); // Reset PK so DB can generate a new one. existingExchangeCoins.AddRange(fetchedCoins); existingExchangeCoins = CryptoLogic.FormatCoinsAndBoughtSoldLogicUpdate(existingExchangeCoins); ResultsItem insertResults = await CryptoLogic.InsertCoinsToUserPortfolioAsync(existingExchangeCoins, CurrentUser, portfolioId); if (insertResults.IsSuccess) { return(Json(ResultsItem.Success("Successfully imported coins to your portfolio."))); } } return(Json(ResultsItem.Error(Lang.ApiNoNewTradesOrError))); }
public async Task <ResultsItem> CreateBBThread(BBThread thread) { if (!ModelState.IsValid) { return(ResultsItem.Error(ModelState.GetAllErrorsString())); } OnThreadUpdatedCacheHandler(thread.CategoryCode, thread.OfficialCoinId.GetValueOrDefault()); return(await CommunityLogic.CreateBBThread(thread, CurrentUser)); }
public PartialViewResult GeneratePartialViewError(string errorMessage) { ResultsItem result = new ResultsItem { MessageColor = "text-danger font-strong", Message = errorMessage }; return(PartialView("~/Views/Shared/_Messages.cshtml", result)); }
public async Task <ResultsItem> CreateBBComment(BBComment comment) { if (!ModelState.IsValid) { return(ResultsItem.Error(ModelState.GetAllErrorsString())); } OnThreadUpdatedCacheHandler(threadId: comment.ThreadId); OnCommentsUpdatedCacheHandler(comment.ThreadId); return(await CommunityLogic.CreateBBComment(comment, CurrentUser)); }
public async Task <JsonResult> DeletePortfolio(int portfolioId) { ResultsItem deleteResult = await CryptoLogic.DeletePortfolio(portfolioId, CurrentUser); if (deleteResult.IsSuccess) { CurrentUser.Portfolios = await CryptoLogic.GetAllUserPortfolioAsync(CurrentUser); SubmitCurrentUserUpdate(); } return(Json(deleteResult)); }
public JsonResult DeleteImportAPI(int apiId) { ResultsItem results = CryptoLogic.DeleteAPI(apiId, CurrentUser); if (results.IsSuccess) { CurrentUser.ExchangeApiList = CurrentUser.ExchangeApiList.Where(x => x.Id != apiId).ToList(); SubmitCurrentUserUpdate(); } return(Json(results)); }
public JsonResult CreateNewImportAPI(ExchangeApiInfo exchangeApiInfo) { if (!ModelState.IsValid) { return(Json(ResultsItem.Error(ModelState.GetAllErrorsString()))); } exchangeApiInfo.ApiAction = Types.ApiAction.TradesImport; exchangeApiInfo.ApiPrivate = exchangeApiInfo.ApiPrivate.Replace("%2B", "+"); ResultsItem apiResult = CryptoLogic.InsertNewAPI(exchangeApiInfo, CurrentUser); return(Json(apiResult)); }
public async Task <JsonResult> DeleteCoin(int coinId, int portfolioId) { CryptoCoin fetchedCoin = await CryptoLogic.GetSingleCoinByUser(coinId, CurrentUser); if (fetchedCoin?.PortfolioId != portfolioId) { return(Json(ResultsItem.Error(Lang.PortfolioNotFound))); } return(Json(await CryptoLogic.DeleteUserCoinsAsync(new List <CryptoCoin> { new CryptoCoin { CoinId = coinId, PortfolioId = portfolioId } }, CurrentUser))); }
private ResultsItem CoinManagementValidation(CoinManagementVM vm, bool isSoldMode = false) { if (!ModelState.IsValid) { return(ResultsItem.Error(ModelState.GetAllErrorsString())); } if (!isSoldMode) { vm.Coin.Symbol = vm.Coin.Symbol.ToUpperInvariant(); if (!vm.Coin.Symbol.StartsWith("BTC-") && !vm.Coin.Symbol.StartsWith("ETH-") && !vm.Coin.Symbol.StartsWith("USD-") && !vm.Coin.Symbol.StartsWith("USDT-")) { return(ResultsItem.Error("Error: The coin symbol must start with BTC-, ETH-, USD-, or USDT-")); } if (vm.Coin.OrderDate > DateTime.Now) { return(ResultsItem.Error("Error: Order date must be today or the past.")); } vm.Coin.CoinCurrency = CryptoLogic.GenerateCoinCurrencyFromSymbol(vm.Coin.Symbol); if (vm.Coin.CoinCurrency == Types.CoinCurrency.Unknown || vm.Coin.CoinCurrency == Types.CoinCurrency.EUR) { return(ResultsItem.Error("Error: only BTC, ETH, and USD currency is currently supported.")); } if (vm.Coin.PricePerUnit <= 0) { return(ResultsItem.Error("Please enter Price Per Unit.")); } } else { if (!CurrentUser.HasPortfolio(vm.Coin.PortfolioId)) { return(ResultsItem.Error(Lang.PortfolioNotFound)); } if (vm.Coin.SoldCoinCurrency == Types.CoinCurrency.Unknown || vm.Coin.SoldPricePerUnit.GetValueOrDefault() <= 0) { return(ResultsItem.Error("Please enter all sold details. TotalSoldPrice is optional.")); } if (vm.SoldDate < vm.Coin.OrderDate) { return(ResultsItem.Error("Sold date cannot be lower than Buy date. Unless you're a time traveler.")); } } return(ResultsItem.Success()); }
public static async Task <ResultsItem> VoteBBComment(long commentId, bool isUpvote, LocalAccount.PegaUser user) { try { string message = "Successfully updated your vote. It will be reflected shortly."; using (PegasunDBContext db = new PegasunDBContext()) { var getServiceCommentTask = db.BBComments.FirstOrDefaultAsync(x => x.CommentId == commentId); var getExistingVoteTask = db.BBCommentVotes.FirstOrDefaultAsync(x => x.CommentId == commentId && x.UserId == user.UserId); var serviceComment = await getServiceCommentTask; var existingVote = await getExistingVoteTask; if (serviceComment == null) { return(ResultsItem.Error("This comment does not exist.")); } if (existingVote != null) { if (existingVote.IsUpvote == isUpvote) { db.Remove(existingVote); message = "Successfully removed your vote. It will be reflected shortly."; } // Same vote (e.g. clicked on upvote twice), which means they are re-tracing their vote. else { existingVote.IsUpvote = isUpvote; } } else { var newServiceVote = new BBCommentVotes { CommentId = commentId, IsUpvote = isUpvote, UserId = user.UserId }; db.BBCommentVotes.Add(newServiceVote); } db.SaveChanges(); return(ResultsItem.Success(message)); } } catch (Exception ex) { Utilities.LogException(new[] { $"User:{user.Username}", $"CommentId:{commentId}" }, ex); return(ResultsItem.Error($"Unable to submit your vote. {ex.Message}")); } }
public ActionResult UpdatePortfolio(int portfolioId) { Portfolio portfolio = CurrentUser.Portfolios.FirstOrDefault(x => x.PortfolioId == portfolioId); if (portfolio == null) { return(Json(ResultsItem.Error("Unable to find the correct portfolio associated with logged in user."))); } PortfolioVM vm = new PortfolioVM { Portfolio = portfolio, IsCreateMode = false }; return(PartialView("Crud/_ManagePortfolio", vm)); }
public void CreateUserTest() { ResultsItem deleteResult = AuthorizationLogic.DeletePegaUser("Test1234").Result; PegaUser user = new PegaUser { Username = "******", Password = "******", Email = "*****@*****.**", IsSubscribeNewsLetter = true }; ResultsPair <PegaUser> result = AuthorizationLogic.CreateNewUser(user).Result; Assert.IsTrue(result.Result.ResultType == Types.ResultsType.Successful); }
public async Task <JsonResult> ImportEtherAddress(ExchangeApiInfo apiInfo) { var resultsPair = await FetchAPILogic.ApiImport_EtherAddress(await GetAllCoinsMarketDetailsAPI(), apiInfo.ApiPublic, apiInfo.PortfolioID, CurrentUser); if (!resultsPair.Result.IsSuccess) { return(Json(resultsPair.Result)); } await CryptoLogic.DeleteAllUserCoinByExchangeAsync(apiInfo.PortfolioID, Types.Exchanges.EtherAddressLookup, CurrentUser); ResultsItem insertResult = await CryptoLogic.InsertCoinsToUserPortfolioAsync(resultsPair.Value, CurrentUser, apiInfo.PortfolioID); return(Json(insertResult)); }
/// <summary> /// Returns the API result from Pegasun API /// </summary> /// <param name="response">the HttpResponseMessage</param> /// <param name="successMessage">You can send a custom success message or leave it empty. If empty, will use APIResult's default message.</param> public static ResultsItem GetSimpleHttpResponseResult(HttpResponseMessage response, string successMessage) { if (response.IsSuccessStatusCode) { string jsonString = response.Content.ReadAsStringAsync().Result; ResultsItem apiResult = NetJSON.NetJSON.Deserialize <PegasunAPIResult>(jsonString).ConvertToResultsItem(); if (apiResult.ResultType == ResultsType.Successful) { return(ResultsItem.Success(string.IsNullOrEmpty(successMessage) ? apiResult.Message : successMessage)); } return(apiResult); // Error } return(ResultsItem.Error(Lang.ServerConnectionError)); }
private static ResultsItem IsValidDBRequest(PegaUser user, int id, bool validateAPI = false, bool validatePortfolio = false, bool validateDemoUser = true) { if (validateDemoUser && user.Username.ToUpperInvariant() == "DEMOUSER") { return(ResultsItem.Error("DemoUser is not allowed to perform this action. Please login or create an account for free.")); } if (validatePortfolio && !user.HasPortfolio(id)) { return(ResultsItem.Error(Lang.PortfolioNotFound)); } if (validateAPI && !user.ExchangeApiList.Any(x => x.Id == id)) { return(ResultsItem.Error(Lang.ApiDeleteNotFound)); } return(ResultsItem.Success(string.Empty)); }
public JsonResult SubmitContactUs(ContactUsVM vm) { if (ModelState.IsValid) { if (!Utilities.IsValidEmailAddress(vm.Email)) { return(Json(ResultsItem.Error("Please enter a valid email address."))); } // Send the email and grab the result bool mailSendSuccess = Utilities.SendEmailUsingSyneiGmail(vm.Email, vm.Name, vm.Subject, $"{vm.Name}, {vm.Email} | {vm.Message}"); return(mailSendSuccess ? Json(ResultsItem.Success("Your email has been successfully sent. We'll get back to you as soon as possible. Thanks!")) : Json(ResultsItem.Error("Sending has failed. Please email us manually at [email protected]."))); } return(Json(ResultsItem.Error(ModelState.GetAllErrorsString()))); }
// Warn, this will delete previous imported Exchange (BitTrex, Kraken, etc) trades public async Task <IActionResult> PostCSVTradeHistoryFile(IFormFile file, Types.Exchanges exchange, int portfolioId) { if (file == null || file.Length > 100000 || (!file.FileName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase) && !file.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))) { return(Json(ResultsItem.Error("Please select a proper .csv/.xlsx file that is less than 100kb."))); } List <Core.Data.ServiceModels.ImportedCoin> importedCoins = new List <Core.Data.ServiceModels.ImportedCoin>(); using (var stream = file.OpenReadStream()) { importedCoins = FetchAPILogic.ImportCSV_Coins(exchange, stream); } if (importedCoins.IsNullOrEmpty()) { return(Json(ResultsItem.Error(Lang.ImportFailedCSV))); } int maxAllowedImport = SubscriptionLogic.GetMaxAllowedTradesImportPerUser(CurrentUser.PTUserInfo.SubscriptionLevel); if (importedCoins.Count > maxAllowedImport) { return(Json(ResultsItem.Error(string.Format(Lang.CSVMaxImportAllowed, maxAllowedImport)))); } List <CryptoCoin> fetchedCoins = FetchAPILogic.FormatCoinsAndGenerateTotalPricePaid(importedCoins, await GetAllHistoricCoinPrices()); if (fetchedCoins.Count > 0) { fetchedCoins = CryptoLogic.FormatCoinsAndBoughtSoldLogicUpdate(fetchedCoins); await CryptoLogic.DeleteAllUserCoinByExchangeAsync(portfolioId, exchange, CurrentUser); ResultsItem insertResults = await CryptoLogic.InsertCoinsToUserPortfolioAsync(fetchedCoins, CurrentUser, portfolioId); if (insertResults.IsSuccess) { return(Json(ResultsItem.Success("Successfully imported coins to your portfolio."))); } } return(Json(ResultsItem.Error("An error occured when trying to import trades. Are you sure the import .csv file has correct format?"))); }