public async Task <List <TransactionDto> > Handle(UpdateUserTransactionCommand request, CancellationToken cancellationToken) { var transactionIds = request.Transactions.Select(t => t.Id).ToList(); var transactions = _dbContext.Transactions .Include(t => t.Account) .Include(t => t.Category) .Where(t => transactionIds.Contains(t.Id) && t.Account.User.Id == request.UserId) .ToList(); request.Transactions.ForEach(rt => { var transaction = transactions.FirstOrDefault(t => t.Id == rt.Id); if (transaction == null) { return; } ComputeNewBalance(transaction, rt); transaction.InjectFrom(rt); }); _dbContext.SaveChanges(); return(transactions .Select(t => { var dto = Mapper.Map <TransactionDto>(t); dto.Category = Mapper.Map <TransactionCategoryDto>(t.Category); dto.Account = AccountDto.From(t.Account); return dto; }) .ToList()); }
public async Task <NewUserTransactionCommandVm> Handle(NewUserTransactionsCommand request, CancellationToken cancellationToken) { var account = _dbContext.Accounts.FirstOrDefault(a => a.Id == request.AccountId); if (account == null) { throw new NotFoundException("This account does not exist."); } var categoryIds = request.Transactions.Select(t => t.Category.Id).ToList(); var categories = _dbContext.TransactionCategories.Where(tc => categoryIds.Contains(tc.Id)).ToList(); var transactions = request.Transactions.Select(t => { var transaction = Mapper.Map <Transaction>(t); transaction.Category = categories.First(c => c.Id == t.Category.Id); transaction.Account = account; if (transaction.Type == TransactionType.Income) { account.Balance += t.Amount; } else { account.Balance -= t.Amount; } return(transaction); }).ToList(); await _dbContext.Transactions.AddRangeAsync(transactions, cancellationToken); _dbContext.SaveChanges(); return(new NewUserTransactionCommandVm { Account = AccountDto.From(account), Transactions = transactions .Select(t => { var dto = Mapper.Map <TransactionDto>(t); dto.Category = Mapper.Map <TransactionCategoryDto>(t.Category); return dto; }) .ToList() }); }