private async Task <Charge> UpdateOrInsertCharge(User user, Transaction trans, double rate) { var charges = user.Charges.FindAll(x => x.ChargeDate.Month == DateTime.Now.Month && x.ChargeDate.Year == DateTime.Now.Year && x.currency == trans.Currency); double amount = trans.Amount / rate; var aux = double.Parse(_config[trans.Currency.ToString()]); if (charges.Count > 0) { foreach (var charge in charges) { if (charge.amount + amount <= double.Parse(_config[trans.Currency.ToString()])) { // Ideally here we would check again for the rate of usd just in case it has changed, but because it only changes at the end and beginning of the day // and not to waste a call to an external api I skipped this validation // var currentRate = await _currencyService.GetRate(trans.Currency); // if(trans.Amount / currentRate ){ // throw Exception() // } Charge userCharge = await _transactionContext.Charges.FindAsync(charge.UserId); userCharge.amount = userCharge.amount + (trans.Amount / rate); userCharge.ChargeDate = DateTime.Now; _transactionContext.Entry(userCharge).CurrentValues.SetValues(userCharge); _transactionContext.Entry(userCharge).State = EntityState.Modified; await _transactionContext.SaveChangesAsync(); return(userCharge); } else { Exception excp = new ErrorHandler(HttpStatusCode.Forbidden, "The amount is invalid for the current month"); _logger.LogError(new EventId((int)HttpStatusCode.Forbidden, excp.Message), excp, excp.Message); throw excp; } } } if (amount > double.Parse(_config[trans.Currency.ToString()])) { Exception excp = new ErrorHandler(HttpStatusCode.Forbidden, $"Invalid operation, the amount is greater than:{_config[trans.Currency.ToString()]}"); _logger.LogError(new EventId((int)HttpStatusCode.Forbidden, excp.Message), excp, excp.Message); throw excp; } Charge newCharge = new Charge(amount, trans.Currency, DateTime.Now, user.UserId); await _transactionContext.AddAsync(newCharge); await _transactionContext.SaveChangesAsync(); return(newCharge); }
public async Task <Transaction> CreateTransactionAsync(User sender, User recipient, decimal amount) { var transaction = new Transaction() { Id = Guid.NewGuid(), Sender = sender.Id, Recipient = recipient.Id, Amount = amount, BalanceSender = sender.Balance, BalanceRecipient = recipient.Balance, CreatedAt = DateTime.Now }; await _transactionContext.AddAsync(transaction); sender.Balance -= amount; _userContext.Users.Update(sender); recipient.Balance += amount; _userContext.Users.Update(recipient); await _transactionContext.SaveChangesAsync(); await _userContext.SaveChangesAsync(); return(transaction); }