示例#1
0
 private UserTransactionDto BuildUserTransactionDto(AddTransactionViewModel model)
 {
     return(new UserTransactionDto
     {
         Date = model.Date,
         CompanyId = model.SelectedCompanyId,
         Price = model.Price,
         Quantity = model.TransactionType == TransactionActionType.Buy ? model.Quantity : -model.Quantity,
         UserId = CurrentUserId
     });
 }
示例#2
0
        /// <summary>
        /// Saves a new transaction for the user
        /// </summary>
        /// <param name="user">The user to save the transaction for</param>
        /// <param name="model">The transaction viewmodel</param>
        /// <returns></returns>
        public async Task <Transaction> SaveTransaction(User user, AddTransactionViewModel model)
        {
            Transaction transaction = await SetTransactionData(new Transaction(), model);

            transaction.User = user;

            _context.Transactions.Add(transaction);
            await _context.SaveChangesAsync();

            return(transaction);
        }
示例#3
0
        private async Task <Transaction> SetTransactionData(Transaction transaction, AddTransactionViewModel details)
        {
            transaction.Amount       = details.Category.Name == "Income" ? details.Amount : -details.Amount;
            transaction.Date         = details.Date;
            transaction.IsExtraneous = details.IsExtraneous;
            transaction.Label        = details.Label;
            transaction.Notes        = details.Notes;

            transaction.Category = details.Category != null ? await _context.Categories.FindAsync(details.Category.Id) : null;

            transaction.Location = details.Location != null ? await _context.Locations.FindAsync(details.Location.Id) : null;

            // Remove people that exist
            if (transaction.TransactionPeople != null)
            {
                _context.RemoveRange(transaction.TransactionPeople);
            }

            if (details.People != null)
            {
                List <int>    peopleIds = details.People.Select(p => p.Id).ToList();
                List <Person> people    = await _context.People.Where(p => peopleIds.Contains(p.Id)).ToListAsync();

                foreach (Person tag in people)
                {
                    _context.Add(new TransactionPerson {
                        Transaction = transaction, Person = tag
                    });
                }
            }

            // Remove tags that exist
            if (transaction.TransactionTags != null)
            {
                _context.RemoveRange(transaction.TransactionTags);
            }

            if (details.Tags != null)
            {
                List <int> tagIds = details.Tags.Select(t => t.Id).ToList();
                List <Tag> tags   = await _context.Tags.Where(t => tagIds.Contains(t.Id)).ToListAsync();

                foreach (Tag tag in tags)
                {
                    _context.Add(new TransactionTag {
                        Transaction = transaction, Tag = tag
                    });
                }
            }

            return(transaction);
        }
示例#4
0
        public void AddTransactionViewModel_ReturnTransferDefault()
        {
            _transactionRepository.Selected = new FinancialTransaction {
                Type = (int)TransactionType.Transfer
            };
            var viewModel = new AddTransactionViewModel(_transactionRepository,
                                                        _accountRepository,
                                                        _categoryRepository,
                                                        new CurrencyManager(new JsonService()),
                                                        _settingRepository);

            Assert.AreEqual("add transfer", viewModel.Title);
        }
示例#5
0
        public IActionResult AddTransaction([FromBody] AddTransactionViewModel model)
        {
            try
            {
                var transaction = _blockchain.AddTransaction(model.Sender, model.Receiver, model.Amount);

                return(Ok(transaction));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
示例#6
0
        public async Task <IActionResult> Add()
        {
            var viewModel = new AddTransactionViewModel
            {
                Date           = DateTime.Today,
                CategoriesList = new SelectList(
                    await _categoriesDataService.RetrieveCategoriesAsync().ConfigureAwait(false),
                    nameof(Category.Id),
                    nameof(Category.Name))
            };

            return(View(viewModel));
        }
        public void AddTransaction_saves_new_transaction()
        {
            AddTransactionViewModel viewModel = CreateAddTransactionViewModel();

            viewModel.Amount.Value = 1;
            viewModel.SelectedCoin = Coin.GetAvailableAssets().First();

            viewModel.AddTransactionCommand.Execute(null);

            viewModel.Amount.Errors.Should().BeEmpty();

            _mockRepository.VerifyThatSaveAsyncWasCalled();
        }
        public void Withdrawal_transaction_is_created_ok()
        {
            List <Accounts> accounts    = ctx.Accounts.ToList();
            var             fromAccount = accounts[0];

            fromAccount.Balance = 1000;
            ctx.Accounts.Update(fromAccount);
            ctx.SaveChanges();

            var model = new AddTransactionViewModel
            {
                Date = DateTime.Now.Date,
                OldAccountBalance = fromAccount.Balance,
                Type          = "Debit",
                Operation     = "Withdrawal in Cash",
                Amount        = 500,
                FromAccountId = fromAccount.AccountId,
                Symbol        = null,
                Bank          = null,
                ToAccount     = null
            };

            var expectedTransaction = new Transactions
            {
                AccountId = model.FromAccountId,
                Date      = model.Date,
                Balance   = model.OldAccountBalance - model.Amount,
                Type      = model.Type,
                Operation = model.Operation,
                Amount    = -model.Amount,
                Symbol    = model.Symbol,
                Bank      = model.Bank,
                Account   = model.ToAccount
            };

            sut.CreateWithdrawalTransaction(model);

            IQueryable <Transactions> transactions = ctx.Transactions;
            var transactionID      = transactions.Max(x => x.TransactionId);
            var createdTransaction = transactions.Where(x => x.TransactionId == transactionID).FirstOrDefault();

            Assert.AreEqual(expectedTransaction.AccountId, createdTransaction.AccountId);
            Assert.AreEqual(expectedTransaction.Date, createdTransaction.Date);
            Assert.AreEqual(expectedTransaction.Balance, createdTransaction.Balance);
            Assert.AreEqual(expectedTransaction.Type, createdTransaction.Type);
            Assert.AreEqual(expectedTransaction.Operation, createdTransaction.Operation);
            Assert.AreEqual(expectedTransaction.Amount, createdTransaction.Amount);
            Assert.AreEqual(expectedTransaction.Symbol, createdTransaction.Symbol);
            Assert.AreEqual(expectedTransaction.Bank, createdTransaction.Bank);
            Assert.AreEqual(expectedTransaction.Account, createdTransaction.Account);
        }
示例#9
0
        /// <summary>
        /// Updates a transaction of the user
        /// </summary>
        /// <param name="user">The user to update the transaction for</param>
        /// <param name="model">The transaction viewmodel</param>
        /// <returns></returns>
        public async Task <Transaction> UpdateTransaction(User user, AddTransactionViewModel model)
        {
            Transaction transactionToUpdate = await GetUserTransactionById(user.Id, model.Id);

            if (transactionToUpdate == null)
            {
                return(null);
            }

            transactionToUpdate = await SetTransactionData(transactionToUpdate, model);

            _context.Entry(transactionToUpdate).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(transactionToUpdate);
        }
示例#10
0
        public void Withdrawal_transaction_is_created_ok()
        {
            var ctx = GetContextWithData();

            var model = new AddTransactionViewModel
            {
                Date = DateTime.Now,
                OldAccountBalance = 1000,
                Type          = "Debit",
                Operation     = "Withdrawal in Cash",
                Amount        = 2000,
                FromAccountId = 1,
            };

            var accounts = ctx.Accounts;
        }
示例#11
0
        public AddTransactionPage(Account account) : this()
        {
            this.account = account;

            viewModel = new AddTransactionViewModel(account);

            BindingContext = viewModel;

            viewModel.OnAdded += OnTransactionAdded;

            viewModel.OnCancel += OnCancel;

            viewModel.OnError += ViewModel_OnError;

            viewModel.OnInitializationFinished += ViewModel_OnInitializationFinished;
        }
示例#12
0
        public async Task <ActionResult <Transaction> > Update([FromBody] AddTransactionViewModel transaction)
        {
            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            var updatedTransaction = await _transactionService.UpdateTransaction(_user, transaction);

            if (updatedTransaction == null)
            {
                return(NotFound());
            }

            return(Ok(AutoMapper.Mapper.Map <TransactionViewModel>(updatedTransaction)));
        }
        public void When_withdrawing_can_not_take_more_money_than_balance_on_account()
        {
            var model = new AddTransactionViewModel {
                Date = DateTime.Now,
                OldAccountBalance = 1000,
                Type          = "Debit",
                Operation     = "Withdrawal in Cash",
                Amount        = 2000,
                FromAccountId = 1,
            };

            var expectedErrorMessage = "Insufficient funds on account to perform the transaction.";

            var newModel = sut.CheckWithdrawalTransactionModelIsOkAndReturnViewmodel(model);

            Assert.AreEqual(expectedErrorMessage, newModel.ErrorMessageViewModel.ErrorMessage);
        }
示例#14
0
        public void AddTransactionViewModel_ReturnEditTransferTitle()
        {
            _transactionRepository.Selected = new FinancialTransaction {
                Type = (int)TransactionType.Transfer
            };
            var viewModel = new AddTransactionViewModel(_transactionRepository,
                                                        _accountRepository,
                                                        _categoryRepository,
                                                        new CurrencyManager(new JsonService()),
                                                        _settingRepository)
            {
                IsEdit     = true,
                IsTransfer = true
            };

            Assert.AreEqual("edit transfer", viewModel.Title);
        }
        public void When_depositing_cannot_enter_negative_amount()
        {
            var model = new AddTransactionViewModel
            {
                Date = DateTime.Now,
                OldAccountBalance = 1000,
                Type          = "Credit",
                Operation     = "Credit in Cash",
                Amount        = -500,
                FromAccountId = 1,
            };

            var expectedErrorMessage = "The amount entered cannot be negative or 0.";

            var newModel = sut.CheckDepositTransactionModelIsOkAndReturnViewmodel(model);

            Assert.AreEqual(expectedErrorMessage, newModel.ErrorMessageViewModel.ErrorMessage);
        }
示例#16
0
        public AddTransactionViewModel CreateWithdrawalViewModel(int accountId)
        {
            var account    = _accountsRepository.GetOneByID(accountId);
            var oldBalance = _accountServices.GetBalanceOnAccount(account);

            var model = new AddTransactionViewModel()
            {
                Date              = DateTime.Now,
                Type              = "Debit",
                Operation         = "Withdrawal in Cash",
                FromAccountId     = accountId,
                OldAccountBalance = oldBalance,
            };

            model.ErrorMessageViewModel = new ErrorMessageViewModel()
            {
                ErrorMessage = ""
            };

            return(model);
        }
示例#17
0
        public FrontView(int frontID)
        {
            this.frontID = frontID;
            InitializeComponent();

            List <string> transactionTypes = new List <string>();

            transactionTypes.Add("Buy");
            transactionTypes.Add("Sell");

            TransactionTypeCombo.ItemsSource = transactionTypes;

            var transactionRepository = Global.Kernel.Get <ITransactionRepository>();
            var frontRepository       = Global.Kernel.Get <IFrontRepository>();

            var front = frontRepository.GetById(frontID);

            companySymbol = front.Company.Symbol;

            FrontInfoViewModel = new FrontInformationViewModel(front);

            FrontInformations.DataContext = FrontInfoViewModel;

            TransactionsViewModel = new ObservableCollection <TransactionListItemViewModel>(transactionRepository.Where(t => t.FrontID == frontID)
                                                                                            .OrderBy(t => t.Date)
                                                                                            .Select(t => new TransactionListItemViewModel()
            {
                Amount          = t.Amount,
                Commision       = t.Commision,
                Price           = t.Price,
                TransactionType = (TransactionTypeEnum)t.TypeID,
                Profit          = t.Total.Value,
                Date            = t.Date
            }).ToList());

            TransactionList.ItemsSource = TransactionsViewModel;
            NewTransaction.DataContext  = AddViewModel = new AddTransactionViewModel();

            GetInformationAboutFront().RunAsync();
        }
        public async Task Add_WithInvalidViewModel_ShouldReturnViewWithSameViewModel()
        {
            // Arrange
            var controllerBuilder = new TransactionsControllerBuilder();

            using var controller = controllerBuilder.Build();

            controller.ModelState.AddModelError("SomeKey", "SomeErrorMessage");

            var postedViewModel = new AddTransactionViewModel
            {
                Date       = new DateTime(2008, 11, 17),
                CategoryId = 101,
                Memo       = "Something",
                Amount     = 123.45m,
                IsCredit   = false
            };

            // Act
            var result = await controller.Add(postedViewModel);

            // Assert
            Assert.IsNotNull(result, FailureMessages.ResultIsNull);
            Assert.IsInstanceOfType(result, typeof(ViewResult), FailureMessages.ResultNotExpectedType);

            var viewResult = result as ViewResult;

            Assert.IsNotNull(viewResult.Model, FailureMessages.ViewModelIsNull);
            Assert.IsInstanceOfType(viewResult.Model, typeof(AddTransactionViewModel), FailureMessages.ViewModelNotExpectedType);

            var resultViewModel = viewResult.Model as AddTransactionViewModel;

            Assert.AreEqual(postedViewModel.Date, resultViewModel.Date, FailureMessages.ViewModelPropertyNotExpectedValue);
            Assert.AreEqual(postedViewModel.CategoryId, resultViewModel.CategoryId, FailureMessages.ViewModelPropertyNotExpectedValue);
            Assert.AreEqual(postedViewModel.Memo, resultViewModel.Memo, FailureMessages.ViewModelPropertyNotExpectedValue);
            Assert.AreEqual(postedViewModel.Amount, resultViewModel.Amount, FailureMessages.ViewModelPropertyNotExpectedValue);
            Assert.AreEqual(postedViewModel.IsCredit, resultViewModel.IsCredit, FailureMessages.ViewModelPropertyNotExpectedValue);
        }
示例#19
0
        public async Task <IActionResult> Add(AddTransactionViewModel viewModel)
        {
            if (viewModel is null)
            {
                throw new ArgumentNullException(nameof(viewModel));
            }

            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            _ = await _transactionsDataService.CreateTransactionAsync(new Transaction
            {
                Date       = viewModel.Date,
                CategoryId = viewModel.CategoryId,
                Memo       = viewModel.Memo,
                Amount     = viewModel.Amount,
                IsCredit   = viewModel.IsCredit
            }).ConfigureAwait(false);

            return(RedirectToAction(nameof(Index)));
        }
示例#20
0
        private void Add(object sender, RoutedEventArgs e)
        {
            if (AddViewModel.Price.HasValue == false || AddViewModel.Price <= 0 ||
                AddViewModel.Amount.HasValue == false || AddViewModel.Amount <= 0)
            {
                MessageBox.Show("Wrong values", "Wrong values");
                return;
            }

            var transaction = new Transaction()
            {
                Amount    = (int)AddViewModel.Amount,
                Commision = AddViewModel.Comission,
                Date      = AddViewModel.Date,
                FrontID   = frontID,
                Price     = (decimal)AddViewModel.Price,
                TypeID    = (int)AddViewModel.TransactionTypeEnum
            };

            var repo = Global.Kernel.Get <ITransactionRepository>();

            repo.Add(transaction);
            repo.SaveChanges();

            TransactionsViewModel.Add(new TransactionListItemViewModel()
            {
                Amount          = transaction.Amount,
                Commision       = transaction.Commision,
                Price           = transaction.Price,
                TransactionType = (TransactionTypeEnum)transaction.TypeID,
                Profit          = transaction.Total.Value,
                Date            = transaction.Date
            });

            NewTransaction.DataContext = AddViewModel = new AddTransactionViewModel();
        }
示例#21
0
        public void CreateWithdrawalTransaction(AddTransactionViewModel model)
        {
            var account    = _accountsRepository.GetOneByID(model.FromAccountId);
            var oldBalance = model.OldAccountBalance;
            var newBalance = oldBalance - model.Amount;

            var newTransaction = new Transactions()
            {
                AccountId = model.FromAccountId,
                Date      = model.Date,
                Type      = model.Type,
                Operation = model.Operation,
                Amount    = -model.Amount,
                Balance   = newBalance,
                Symbol    = model.Symbol,
                Bank      = model.Bank,
                Account   = model.ToAccount,
            };

            _transactionsRepository.Create(newTransaction);

            account.Balance = newBalance;
            _accountsRepository.Update(account);
        }
示例#22
0
        public IActionResult Deposit(AddTransactionViewModel model)
        {
            bool ok = true;

            if (!ModelState.IsValid || !ok)
            {
                ModelState.AddModelError(string.Empty, "Please fill in all the required fields.");

                var newModel = _viewmodelsServices.CreateDepositViewModel(model.FromAccountId);

                return(View(newModel));
            }

            model = _transactionServices.CheckDepositTransactionModelIsOkAndReturnViewmodel(model);

            if (model.ErrorMessageViewModel.ErrorMessage != "")
            {
                return(View(model));
            }

            _transactionServices.CreateDepositTransaction(model);

            return(View("SuccessConfirmation"));
        }
示例#23
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var model = new AddTransactionViewModel((AssetViewModel)e.Parameter);

            DataContext = model;
        }
示例#24
0
        public AddTransactionViewModel CheckWithdrawalTransactionModelIsOkAndReturnViewmodel(AddTransactionViewModel viewModel)
        {
            if (!IsAmountOk(viewModel.Amount))
            {
                viewModel.ErrorMessageViewModel = new ErrorMessageViewModel()
                {
                    ErrorMessage = "The amount entered cannot be negative or 0."
                };

                return(viewModel);
            }

            if (!IsDateOk(viewModel.Date))
            {
                viewModel.ErrorMessageViewModel = new ErrorMessageViewModel()
                {
                    ErrorMessage = "You cannot make a transaction in the past."
                };

                return(viewModel);
            }

            if (!IsBalanceEnough(viewModel.Amount, viewModel.OldAccountBalance))
            {
                viewModel.ErrorMessageViewModel = new ErrorMessageViewModel()
                {
                    ErrorMessage = "Insufficient funds on account to perform the transaction."
                };

                return(viewModel);
            }

            viewModel.ErrorMessageViewModel = new ErrorMessageViewModel()
            {
                ErrorMessage = ""
            };

            return(viewModel);
        }
示例#25
0
        public AddTransactionViewModel CheckDepositTransactionModelIsOkAndReturnViewmodel(AddTransactionViewModel viewModel)
        {
            if (!IsAmountOk(viewModel.Amount))
            {
                viewModel.ErrorMessageViewModel = new ErrorMessageViewModel()
                {
                    ErrorMessage = "The amount entered cannot be negative or 0."
                };

                return(viewModel);
            }

            if (!IsDateOk(viewModel.Date))
            {
                viewModel.ErrorMessageViewModel = new ErrorMessageViewModel()
                {
                    ErrorMessage = "You cannot make a transaction in the past."
                };

                return(viewModel);
            }

            viewModel.ErrorMessageViewModel = new ErrorMessageViewModel()
            {
                ErrorMessage = ""
            };

            return(viewModel);
        }
 public AddTransactionView()
 {
     InitializeComponent();
     DataContextChanged += (s, e) => { ViewModel = DataContext as AddTransactionViewModel; };
 }
 public TransactionViewModelTest()
 {
     _transactionViewModel    = new TransactionViewModel(_unitOfWork);
     _addTransactionViewModel = new AddTransactionViewModel(_unitOfWork);
 }