public async Task <Category> Delete(int id) { var categoryRepository = ContextProvider.GetRepository <ICategoryRepository>(); var category = categoryRepository.GetByKey(id); if (category == null) { throw new CashSchedulerException("There is no such category"); } if (!category.IsCustom) { throw new CashSchedulerException("You cannot delete one of the standard categories"); } var relatedTransactions = await ContextProvider.GetRepository <ITransactionRepository>().DeleteByCategoryId(id); await ContextProvider.GetRepository <IRegularTransactionRepository>().DeleteByCategoryId(id); await ContextProvider.GetService <IWalletService>().UpdateBalance( relatedTransactions, relatedTransactions, isDelete: true ); var deletedCategory = await categoryRepository.Delete(id); await EventManager.FireEvent(EventAction.RecordDeleted, deletedCategory); return(deletedCategory); }
public async Task <string> CheckCode(string email, string code) { var user = ContextProvider.GetRepository <IUserRepository>().GetByEmail(email); if (user == null) { throw new CashSchedulerException("There is no such user", new[] { nameof(email) }); } var verificationCode = ContextProvider .GetService <IUserEmailVerificationCodeService>().GetByUserId(user.Id); if (verificationCode == null) { throw new CashSchedulerException("We haven't sent you a code yet", new[] { nameof(email) }); } if (verificationCode.ExpiredDate < DateTime.UtcNow) { throw new CashSchedulerException("This code has been expired", new[] { nameof(code) }); } if (verificationCode.Code != code) { throw new CashSchedulerException("The code is not valid", new[] { nameof(code) }); } return(await Task.FromResult(email)); }
public Task <UserNotification> Update(UserNotification notification) { var notificationRepository = ContextProvider.GetRepository <IUserNotificationRepository>(); var targetNotification = notificationRepository.GetByKey(notification.Id); if (targetNotification == null) { throw new CashSchedulerException("There is no such notification"); } if (notification.Title != default) { targetNotification.Title = notification.Title; } if (notification.Content != default) { targetNotification.Content = notification.Content; } targetNotification.IsRead = notification.IsRead; return(notificationRepository.Update(targetNotification)); }
public async Task <IEnumerable <CurrencyExchangeRate> > GetBySourceAndTarget( string sourceCurrencyAbbreviation, string targetCurrencyAbbreviation ) { var rates = new List <CurrencyExchangeRate>(); var exchangeRatesResponse = await ExchangeRateWebService.GetLatestExchangeRates( sourceCurrencyAbbreviation, new[] { targetCurrencyAbbreviation } ); if (exchangeRatesResponse.Success) { var currencyRepository = ContextProvider.GetRepository <ICurrencyRepository>(); rates.Add(new CurrencyExchangeRate { ExchangeRate = exchangeRatesResponse.Rates[targetCurrencyAbbreviation], IsCustom = false, SourceCurrency = currencyRepository.GetByKey(sourceCurrencyAbbreviation), TargetCurrency = currencyRepository.GetByKey(targetCurrencyAbbreviation), ValidFrom = exchangeRatesResponse.Date, ValidTo = exchangeRatesResponse.Date }); } rates.AddRange( ContextProvider.GetRepository <ICurrencyExchangeRateRepository>() .GetBySourceAndTarget(sourceCurrencyAbbreviation, targetCurrencyAbbreviation) ); return(rates); }
public async Task <Category> Update(Category category) { var categoryRepository = ContextProvider.GetRepository <ICategoryRepository>(); var targetCategory = categoryRepository.GetByKey(category.Id); if (targetCategory == null) { throw new CashSchedulerException("There is no such category"); } if (!string.IsNullOrEmpty(category.Name)) { targetCategory.Name = category.Name; } if (!string.IsNullOrEmpty(category.IconUrl)) { targetCategory.IconUrl = category.IconUrl; } targetCategory.TypeName = targetCategory.Type.Name; var updatedCategory = await categoryRepository.Update(targetCategory); await EventManager.FireEvent(EventAction.RecordUpserted, updatedCategory); return(updatedCategory); }
public async Task <User> Delete(string password) { var user = GetById(); if (user == null) { throw new CashSchedulerException("There is no such user"); } if (user.Password != password.Hash(Configuration)) { throw new CashSchedulerException("Password in not valid", new [] { nameof(password) }); } var settingRepository = ContextProvider.GetRepository <IUserSettingRepository>(); var deleteAccountSetting = settingRepository.GetByName(Setting.SettingOptions.DeleteAccount.ToString()); await settingRepository.Delete(deleteAccountSetting.Id); await Task.Run(() => { Task.Delay(TimeSpan.FromMinutes(Convert.ToInt32(Configuration["App:DeleteAccountTimeout"]))) .ContinueWith(_ => Delete(user.Id)); }); return(user); }
public async Task <Transfer> CreateTransfer(Transfer transfer) { var walletRepository = ContextProvider.GetRepository <IWalletRepository>(); transfer.SourceWallet = walletRepository.GetByKey(transfer.SourceWalletId); if (transfer.SourceWallet == null) { throw new CashSchedulerException("There is no such wallet", new[] { "sourceWalletId" }); } transfer.TargetWallet = walletRepository.GetByKey(transfer.TargetWalletId); if (transfer.TargetWallet == null) { throw new CashSchedulerException("There is no such wallet", new[] { "targetWalletId" }); } ModelValidator.ValidateModelAttributes(transfer); transfer.SourceWallet.Balance -= transfer.Amount; if (transfer.SourceWallet.Balance < 0) { throw new CashSchedulerException("There is not enough money on the wallet", new[] { "amount" }); } await walletRepository.Update(transfer.SourceWallet); transfer.TargetWallet.Balance += transfer.ExchangeRate * transfer.Amount; await walletRepository.Update(transfer.TargetWallet); return(transfer); }
public async Task <User> Update(User user) { var targetUser = UserRepository.GetByKey(user.Id); if (targetUser == null) { throw new CashSchedulerException("There is no such user"); } if (user.FirstName != null) { targetUser.FirstName = user.FirstName; } if (user.LastName != null) { targetUser.LastName = user.LastName; } if (user.Balance != default) { var defaultWallet = ContextProvider.GetRepository <IWalletRepository>().GetDefault(); defaultWallet.Balance = user.Balance; await ContextProvider.GetService <IWalletService>().Update(defaultWallet); } var createdUser = await UserRepository.Update(targetUser); await EventManager.FireEvent(EventAction.RecordUpserted, createdUser); return(createdUser); }
public IEnumerable <UserSetting> GetByUnitName(string unitName = null) { var settingRepository = ContextProvider.GetRepository <IUserSettingRepository>(); return(string.IsNullOrEmpty(unitName) ? settingRepository.GetAll() : settingRepository.GetByUnitName(unitName)); }
public IEnumerable <Category> GetCustomCategories(string transactionType = null) { var categoryRepository = ContextProvider.GetRepository <ICategoryRepository>(); return(string.IsNullOrEmpty(transactionType) ? categoryRepository.GetCustomCategories() : categoryRepository.GetCustomCategories(transactionType)); }
private Task <Wallet> ResetDefault(Wallet wallet) { var walletRepository = ContextProvider.GetRepository <IWalletRepository>(); var defaultWallet = walletRepository.GetDefault(); defaultWallet.IsDefault = false; wallet.IsDefault = true; return(walletRepository.Update(defaultWallet)); }
public Task <UserNotification> ToggleRead(int id, bool read) { var notificationRepository = ContextProvider.GetRepository <IUserNotificationRepository>(); var notification = notificationRepository.GetByKey(id); notification.IsRead = read; return(notificationRepository.Update(notification)); }
public async Task <UserNotification> Create(UserNotification notification) { notification.User ??= ContextProvider.GetRepository <IUserRepository>().GetByKey(UserId); var createdNotification = await ContextProvider.GetRepository <IUserNotificationRepository>().Create(notification); await EventSender.SendAsync($"OnUserNotification_{notification.User.Id}", createdNotification); return(createdNotification); }
public async Task <string> CheckEmail(string email) { var user = ContextProvider.GetRepository <IUserRepository>().GetByEmail(email); if (user == null) { throw new CashSchedulerException("There is no such user", new[] { nameof(email) }); } int allowedVerificationInterval = Convert.ToInt32(Configuration["App:Auth:EmailVerificationTokenLifetime"]); var verificationCodeService = ContextProvider.GetService <IUserEmailVerificationCodeService>(); var existingVerificationCode = verificationCodeService.GetByUserId(user.Id); if (existingVerificationCode != null) { var difference = DateTime.UtcNow.Subtract(existingVerificationCode.ExpiredDate); if (difference.TotalSeconds < 0 && Math.Abs(difference.TotalSeconds) < allowedVerificationInterval * 60 && !bool.Parse(Configuration["App:Auth:SkipAuth"])) { throw new CashSchedulerException( "We already sent you a code. " + $"You can request it again in: {Math.Abs(difference.Minutes)}:{Math.Abs(difference.Seconds)}", new[] { nameof(email) } ); } } var verificationCode = await verificationCodeService.Update(new UserEmailVerificationCode( email.Code(Configuration), DateTime.UtcNow.AddMinutes(allowedVerificationInterval), user )); var notificationDelegator = new NotificationDelegator(); var template = notificationDelegator.GetTemplate( NotificationTemplateType.VerificationCode, new Dictionary <string, string> { { "code", verificationCode.Code } } ); await Notificator.SendEmail(user.Email, template); await ContextProvider.GetService <IUserNotificationService>().Create(new UserNotification { Title = template.Subject, Content = template.Body, User = user }); return(email); }
public Task <UserNotification> Delete(int id) { var notificationRepository = ContextProvider.GetRepository <IUserNotificationRepository>(); var targetNotification = notificationRepository.GetByKey(id); if (targetNotification == null) { throw new CashSchedulerException("There is no such notification"); } return(notificationRepository.Delete(id)); }
public async Task <Wallet> UpdateBalance( Transaction transaction, Transaction oldTransaction, bool isCreate = false, bool isUpdate = false, bool isDelete = false) { int delta = 1; var wallet = transaction.Wallet; if (transaction.Category.Type.Name == TransactionType.Options.Expense.ToString()) { delta = -1; } if (isCreate) { if (transaction.Date <= DateTime.Today) { wallet.Balance += transaction.Amount * delta; } } else if (isUpdate) { if (transaction.Date <= DateTime.Today && oldTransaction.Date <= DateTime.Today) { wallet.Balance += (transaction.Amount - oldTransaction.Amount) * delta; } else if (transaction.Date <= DateTime.Today && oldTransaction.Date > DateTime.Today) { wallet.Balance += transaction.Amount * delta; } else if (transaction.Date > DateTime.Today && oldTransaction.Date <= DateTime.Today) { wallet.Balance -= oldTransaction.Amount * delta; } } else if (isDelete) { if (oldTransaction.Date <= DateTime.Today) { wallet.Balance -= oldTransaction.Amount * delta; } } var updatedWallet = await ContextProvider.GetRepository <IWalletRepository>().Update(wallet); await EventManager.FireEvent(EventAction.RecordUpserted, updatedWallet); return(updatedWallet); }
public Task <CurrencyExchangeRate> Update(CurrencyExchangeRate exchangeRate) { var exchangeRateRepository = ContextProvider.GetRepository <ICurrencyExchangeRateRepository>(); var targetExchangeRate = exchangeRateRepository.GetByKey(exchangeRate.Id); if (targetExchangeRate == null) { throw new CashSchedulerException("There is no such exchange rate"); } var currencyRepository = ContextProvider.GetRepository <ICurrencyRepository>(); if (!string.IsNullOrEmpty(exchangeRate.SourceCurrencyAbbreviation)) { targetExchangeRate.SourceCurrency = currencyRepository.GetByKey(exchangeRate.SourceCurrencyAbbreviation); if (targetExchangeRate.SourceCurrency == null) { throw new CashSchedulerException("There is no such currency", new[] { "sourceCurrencyAbbreviation" }); } } if (!string.IsNullOrEmpty(exchangeRate.TargetCurrencyAbbreviation)) { targetExchangeRate.TargetCurrency = currencyRepository.GetByKey(exchangeRate.TargetCurrencyAbbreviation); if (targetExchangeRate.TargetCurrency == null) { throw new CashSchedulerException("There is no such currency", new[] { "targetCurrencyAbbreviation" }); } } if (exchangeRate.ExchangeRate != default) { targetExchangeRate.ExchangeRate = exchangeRate.ExchangeRate; } if (exchangeRate.ValidFrom != default) { targetExchangeRate.ValidFrom = exchangeRate.ValidFrom; } if (exchangeRate.ValidTo != default) { targetExchangeRate.ValidTo = exchangeRate.ValidTo; } return(exchangeRateRepository.Update(targetExchangeRate)); }
public Task <Wallet> CreateDefault(User user) { var targetUser = ContextProvider.GetRepository <IUserRepository>().GetByKey(user.Id); var defaultCurrency = ContextProvider.GetRepository <ICurrencyRepository>().GetDefaultCurrency(); return(ContextProvider.GetRepository <IWalletRepository>().Create(new Wallet { Name = "Default Wallet", Balance = user.Balance, Currency = defaultCurrency, User = targetUser, IsDefault = true })); }
public async Task <AuthTokens> AppLogin(string appToken) { if (string.IsNullOrEmpty(appToken)) { throw new CashSchedulerException("App token is required for connecting an app", new[] { nameof(appToken) }); } var tokenClaims = appToken.EvaluateToken(); if (!tokenClaims.IsTokenValid()) { throw new CashSchedulerException("Access token is invalid", new[] { nameof(appToken) }); } string role = tokenClaims.GetRole(); if (role != AuthOptions.APP_ROLE) { throw new CashSchedulerException("Method allowed only for connected apps", new[] { nameof(appToken) }); } var user = ContextProvider.GetRepository <IUserRepository>().GetByKey(Convert.ToInt32(tokenClaims.GetUserId())); if (user == null) { throw new CashSchedulerException("Invalid user id provided", new[] { nameof(appToken) }); } var accessToken = user.GenerateToken(AuthOptions.TokenType.AppAccess, Configuration); var refreshToken = user.GenerateToken(AuthOptions.TokenType.AppRefresh, Configuration); await ContextProvider.GetService <IUserRefreshTokenService>().Create(new UserRefreshToken { User = user, Token = refreshToken.token.Hash(Configuration), ExpiredDate = refreshToken.expiresIn, Type = (int)AuthOptions.TokenType.AppRefresh }); await EventManager.FireEvent(EventAction.UserLogin, user); return(new AuthTokens { AccessToken = accessToken.token, RefreshToken = refreshToken.token }); }
public async Task <Category> Create(Category category) { category.Type = ContextProvider.GetRepository <ITransactionTypeRepository>().GetByKey(category.TypeName); if (category.Type == null) { throw new CashSchedulerException("There is no such transaction type", new[] { "transactionTypeName" }); } category.User = ContextProvider.GetRepository <IUserRepository>().GetByKey(UserId); var createdCategory = await ContextProvider.GetRepository <ICategoryRepository>().Create(category); await EventManager.FireEvent(EventAction.RecordUpserted, createdCategory); return(createdCategory); }
public Task <CurrencyExchangeRate> Delete(int id) { var exchangeRateRepository = ContextProvider.GetRepository <ICurrencyExchangeRateRepository>(); var exchangeRate = exchangeRateRepository.GetByKey(id); if (exchangeRate == null) { throw new CashSchedulerException("There is no exchange rate with such id"); } if (!exchangeRate.IsCustom) { throw new CashSchedulerException("You cannot delete one of the standard exchange rates"); } return(exchangeRateRepository.Delete(id)); }
public async Task <Wallet> Update(Wallet wallet, bool convertBalance, float?exchangeRate = null) { var walletRepository = ContextProvider.GetRepository <IWalletRepository>(); var targetWallet = walletRepository.GetByKey(wallet.Id); if (!string.IsNullOrEmpty(wallet.Name)) { targetWallet.Name = wallet.Name; } if (!string.IsNullOrEmpty(wallet.CurrencyAbbreviation) && targetWallet.Currency.Abbreviation != wallet.CurrencyAbbreviation) { if (convertBalance && exchangeRate != null) { targetWallet.Balance *= (double)exchangeRate; } targetWallet.Currency = ContextProvider.GetRepository <ICurrencyRepository>() .GetByKey(wallet.CurrencyAbbreviation); if (targetWallet.Currency == null) { throw new CashSchedulerException("There is no such currency", new[] { "currencyAbbreviation" }); } } if (!convertBalance && wallet.Balance != default) { targetWallet.Balance = wallet.Balance; } var updatedWallet = await walletRepository.Update(targetWallet); if (wallet.IsDefault) { await ResetDefault(targetWallet); } await EventManager.FireEvent(EventAction.RecordUpserted, updatedWallet); return(updatedWallet); }
public async Task <AuthTokens> Token(string email, string refreshToken) { var user = ContextProvider.GetRepository <IUserRepository>().GetByEmail(email); if (user == null) { throw new CashSchedulerException("There is no such user", new[] { nameof(email) }); } var refreshTokenRepository = ContextProvider.GetRepository <IUserRefreshTokenRepository>(); var userRefreshToken = refreshTokenRepository.GetByUserAndToken(user.Id, refreshToken.Hash(Configuration)); if (userRefreshToken == null) { throw new CashSchedulerException("Invalid refresh token", new[] { nameof(refreshToken) }); } var accessTokenType = AuthOptions.TokenType.Access; var refreshTokenType = AuthOptions.TokenType.Refresh; if (userRefreshToken.Type == (int)AuthOptions.TokenType.AppRefresh) { accessTokenType = AuthOptions.TokenType.AppAccess; refreshTokenType = AuthOptions.TokenType.AppRefresh; } var newAccessToken = user.GenerateToken(accessTokenType, Configuration); var newRefreshToken = user.GenerateToken(refreshTokenType, Configuration); userRefreshToken.Token = newRefreshToken.token.Hash(Configuration); userRefreshToken.ExpiredDate = newRefreshToken.expiresIn; await ContextProvider.GetService <IUserRefreshTokenService>().Update(userRefreshToken); await EventManager.FireEvent(EventAction.UserLogin, user); return(new AuthTokens { AccessToken = newAccessToken.token, RefreshToken = newRefreshToken.token }); }
public async Task <Wallet> Delete(int id) { var walletRepository = ContextProvider.GetRepository <IWalletRepository>(); var wallet = walletRepository.GetByKey(id); if (wallet == null) { throw new CashSchedulerException("There is no such wallet"); } if (wallet.IsDefault) { throw new CashSchedulerException("Default wallet cannot be deleted"); } var deletedWallet = await walletRepository.Delete(id); await EventManager.FireEvent(EventAction.RecordDeleted, deletedWallet); return(deletedWallet); }
public async Task <AuthTokens> Login(string email, string password) { if (string.IsNullOrEmpty(email)) { throw new CashSchedulerException("Email is a required field for sign in", new[] { nameof(email) }); } if (string.IsNullOrEmpty(password)) { throw new CashSchedulerException("Password is a required field for sign in", new[] { nameof(password) }); } var user = ContextProvider.GetRepository <IUserRepository>().GetByEmail(email); if (user == null || user.Password != password.Hash(Configuration)) { throw new CashSchedulerException("Invalid email or password", new[] { nameof(email), nameof(password) }); } var accessToken = user.GenerateToken(AuthOptions.TokenType.Access, Configuration); var refreshToken = user.GenerateToken(AuthOptions.TokenType.Refresh, Configuration); await ContextProvider.GetService <IUserRefreshTokenService>().Create(new UserRefreshToken { User = user, Token = refreshToken.token.Hash(Configuration), ExpiredDate = refreshToken.expiresIn, Type = (int)AuthOptions.TokenType.Refresh }); await EventManager.FireEvent(EventAction.UserLogin, user); return(new AuthTokens { AccessToken = accessToken.token, RefreshToken = refreshToken.token }); }
public async Task <Wallet> Create(Wallet wallet) { wallet.User ??= ContextProvider.GetRepository <IUserRepository>().GetByKey(UserId); wallet.Currency ??= ContextProvider.GetRepository <ICurrencyRepository>() .GetByKey(wallet.CurrencyAbbreviation); if (wallet.Currency == null) { throw new CashSchedulerException("There is no such currency", new[] { "currencyAbbreviation" }); } var createdWallet = await ContextProvider.GetRepository <IWalletRepository>().Create(wallet); if (wallet.IsDefault) { await ResetDefault(wallet); } await EventManager.FireEvent(EventAction.RecordUpserted, createdWallet); return(createdWallet); }
public Task <CurrencyExchangeRate> Create(CurrencyExchangeRate exchangeRate) { var currencyRepository = ContextProvider.GetRepository <ICurrencyRepository>(); exchangeRate.SourceCurrency ??= currencyRepository.GetByKey(exchangeRate.SourceCurrencyAbbreviation); exchangeRate.TargetCurrency ??= currencyRepository.GetByKey(exchangeRate.TargetCurrencyAbbreviation); if (exchangeRate.SourceCurrency == null) { throw new CashSchedulerException("There is no such currency", new[] { "sourceCurrencyAbbreviation" }); } if (exchangeRate.TargetCurrency == null) { throw new CashSchedulerException("There is no such currency", new[] { "targetCurrencyAbbreviation" }); } if (exchangeRate.IsCustom && exchangeRate.User == null) { exchangeRate.User = ContextProvider.GetRepository <IUserRepository>().GetByKey(UserId); } return(ContextProvider.GetRepository <ICurrencyExchangeRateRepository>().Create(exchangeRate)); }
public IEnumerable <TransactionDelta> GetTransactionsDelta(int year) { var transactionsByYear = ContextProvider.GetRepository <ITransactionRepository>() .GetTransactionsByYear(year); var groupedByMonth = transactionsByYear.GroupBy(t => t.Date.Month);
public IEnumerable <Transaction> GetTransactionsByMonth(int month, int year) { return(ContextProvider.GetRepository <ITransactionRepository>().GetTransactionsByMonth(month, year)); }
public int GetUnreadCount() { return(ContextProvider.GetRepository <IUserNotificationRepository>().GetUnread().Count()); }