Exemplo n.º 1
0
        public IActionResult Create()
        {
            var categories         = _categoryService.GetAll();
            var categorySelectList = categories.Select(c => new SelectListItem
            {
                Text  = c.Name,
                Value = c.Id.ToString()
            });
            var viewModel = new TransactionViewModel();

            viewModel.CategorySelectList = categorySelectList.ToList();

            return(View("Create", viewModel));
        }
Exemplo n.º 2
0
 public ActionResult Create(TransactionViewModel model)
 {
     if (ModelState.IsValid)
     {
         var result = Service.CreateTransaction(model.ToServiceModel(), ((OwnerModel)Session["SelectedAccount"]).Id);
         if (result)
         {
             return(RedirectToAction("List"));
         }
         ModelState.AddModelError("", "Request could not be completed");
     }
     OnCreate();
     return(View(model));
 }
        public async Task <TransactionViewModel> Update(int id, TransactionViewModel transaction)
        {
            try
            {
                TransactionDTO newTransaction     = mapper.Map <TransactionDTO>(transaction);
                TransactionDTO updatedTransaction = await transactionService.UpdateAsync(id, newTransaction);

                return(mapper.Map <TransactionViewModel>(updatedTransaction));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public async void ShouldNot_CreateNewTransactionAsync_Invalid()
        {
            var transactionViewModel = new TransactionViewModel
            {
                AccountId = 0.ToGuid().ToString(),
                Amount    = 0f,
                Info      = "Info"
            };
            var transactionDto = transactionViewModel.ToTransactionModel <TransactionDto>(1.ToGuid().ToString());

            var newCreatedAccount = await _manager.CreateNewTransactionAsync(transactionDto);

            Assert.Null(newCreatedAccount);
        }
        public ActionResult Create(TransactionViewModel obj)
        {
            var data = db.products.Find(obj.Products_id);

            if (data.orginal_Qty > obj.saled_Qty)
            {
                if (obj.check == true)
                {
                    transaction x = new transaction();


                    x.saled_Qty   = obj.saled_Qty * 12;
                    x.saled_Price = (decimal)obj.saled_Price;
                    x.Products_id = obj.Products_id;
                    x.total_price = (obj.saled_Qty * 12) * ((decimal)obj.saled_Price);
                    x.date        = DateTime.Now.ToString();
                    db.transactions.Add(x);
                    db.SaveChanges();



                    return(RedirectToAction("Index"));
                }
                else
                {
                    transaction x = new transaction();


                    x.saled_Qty   = obj.saled_Qty;
                    x.saled_Price = (decimal)obj.saled_Price;
                    x.Products_id = obj.Products_id;
                    x.total_price = (obj.saled_Qty) * ((decimal)obj.saled_Price);
                    x.date        = DateTime.Now.ToString();
                    db.transactions.Add(x);
                    db.SaveChanges();



                    return(RedirectToAction("Index"));
                }
            }
            else
            {
                ViewBag.name    = new SelectList(db.products, "id", "name");
                ViewBag.message = "هذا الصنف به عجز  ";

                return(View());
            }
        }
        public async Task <IActionResult> ConvertMiles(TransactionViewModel model)
        {
            try
            {
                var user = await GetCurrentUser();

                if (user == null)
                {
                    return(RedirectToAction(nameof(AccountController.LoginClient), "Account"));
                }

                if (user.BonusMiles < model.Value)
                {
                    throw new Exception("You do not have enough miles to complete this operation");
                }

                var operation = _transactionRepository.GetTransactionHistory(user);
                if (operation + model.Value > 20000)
                {
                    throw new Exception("Cannot complete this operation. The amount exceeds your maximum amount per year.");
                }

                var trans = _clientConverterHelper.CreateConversionTransaction(model, user);
                trans.StartBalance = user.BonusMiles;
                trans.EndBalance   = user.BonusMiles;

                user.StatusMiles += model.Value;
                var result = await _userHelper.UpdateUserAsync(user);

                if (!result.Succeeded)
                {
                    throw new Exception("Cannot process this operation at the moment. Please try again later.");
                }

                var response = await _transactionRepository.AddTransanctionAsync(trans);

                if (!response.Success)
                {
                    //TODO enviar notificação para superuser ou admin para introduzir a transacção à mão
                    throw new Exception("Culpa do utilizador");
                }

                return(Json("Purchase successfull"));
            }
            catch (Exception e)
            {
                return(Json(e.Message));
            }
        }
Exemplo n.º 7
0
        public ActionResult AccountDetails(int id)
        {
            BankDB.DataRepository db = new BankDB.DataRepository();

            var transaction = db.GetTransactionsForAccount(id);
            var account     = db.GetAccount(id);

            var viewModel = new TransactionViewModel
            {
                Account     = account,
                Transaction = transaction
            };

            return(PartialView(viewModel));
        }
Exemplo n.º 8
0
 public IHttpActionResult PutTransaction(TransactionViewModel entity)
 {
     return(TryResult(
                ResponseMessage(
                    Request
                    .CreateResponse(HttpStatusCode.OK,
                                    entity != null &&
                                    entity.TransactionModel != null &&
                                    entity.TransactionDetailModel != null &&
                                    _TransactionCRUDService.Update(entity.TransactionModel) &&
                                    _TransactionDetailCRUDService.Update(entity.TransactionDetailModel) &&
                                    _TransactionDetailCRUDService.Save())
                    )
                ));
 }
Exemplo n.º 9
0
        public ActionResult Create(TransactionViewModel transactionModel)
        {
            transactionModel.CreatedDate = DateTime.UtcNow;
            transactionModel.UpdatedDate = DateTime.UtcNow;


            var model = _mapper.Map <TransactionModel>(transactionModel);

            if (ModelState.IsValid)
            {
                _transactionService.Create(model);
                return(RedirectToAction("Index"));
            }
            return(View());
        }
Exemplo n.º 10
0
        public ActionResult CreateSellTransaction()
        {
            var coins  = _context.Coins.ToList();
            var userID = User.Identity.GetUserId();

            var portfolios = _context.Portfolios.Where(x => x.UserID == userID);

            var ViewModel = new TransactionViewModel
            {
                Coins      = coins,
                Portfolios = portfolios
            };

            return(View(ViewModel));
        }
Exemplo n.º 11
0
        public IActionResult Settle(Int64 Id)
        {
            TransactionViewModel viewModel = new TransactionViewModel();

            if (Id > 0)
            {
                Transaction transaction = _unitOfWork.MerchantTransactionRepo.GetById(Id);
                if (transaction != null)
                {
                    viewModel = ModelAdapter.ModelMap(viewModel, transaction);
                }
            }

            return(View(viewModel));
        }
Exemplo n.º 12
0
        public void WithdrawalErrorTest(int amount, int from)
        {
            BankRepository.BankAccounts.Add(new Account()
            {
                AccountNumber = 1, Balance = 100
            });
            var model = new TransactionViewModel {
                Amount = amount, From = from
            };


            var result1 = BankRepository.Withdraw(model);

            Assert.False(result1);
        }
        public ActionResult TransactionDetails(int id)
        {
            var transaction = BLL.TransactionServices.GetById(id);

            var transactionViewModel = new TransactionViewModel()
            {
                Descripcion = transaction.Description,
                Fecha       = transaction.TransactionDate,
                Monto       = transaction.Amount.ToString(),
                Notas       = transaction.Notes,
                Transaccion = transaction.TransactionCode.ToString()
            };

            return(PartialView("TransactionDetails", transactionViewModel));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Throw an exception if name is exist.
        /// </summary>
        /// <param name="model">Transaction view model</param>
        public void ThrowExceptionIfExist(TransactionViewModel model)
        {
            ConditionFilter <Transaction, long> condition = new ConditionFilter <Transaction, long>
            {
                Query = (entity =>
                         //entity.Name == model.Name &&
                         entity.Id != model.Id)
            };
            var existEntity = this._TransactionsRepository.Get(condition).FirstOrDefault();

            if (existEntity != null)
            {
                throw new ItemAlreadyExistException();
            }
        }
Exemplo n.º 15
0
        public SearchDashBoardViewModel(TransactionViewModel transactionDetails, TransferViewModel transferDetails)
            : base(transactionDetails, transferDetails)
        {
            Icon = new MagnifyIcon();

            TransactionRecords.CollectionChanged += (sender, args) => NotifyOfPropertyChange(() => Name);
            Translator.CultureChanged            += delegate
            {
                StartDate = DateTime.Now;
                EndDate   = StartDate;
                NotifyOfPropertyChange(() => Name);
                SearchStatus = Resources.Strings.PostingViewModelBase_SearchStatus_Search;
            };
            sourceAccountsViewSource.Source = accountsRepository.Entities;
        }
Exemplo n.º 16
0
        public ActionResult Index()
        {
            TransactionViewModel    model = new TransactionViewModel();
            List <TransactionModel> list  = this.SelectListModel();

            if (list != null)
            {
                model.WalletModel = this.SelectWalletModel();
                model.TransactionListModel.ListModel.AddRange(list);
                model.TransactionListModel.PageSize = BaseController.pageSize;
                model.TransactionListModel.Total    = SelectTransactionCount();
            }

            return(View(model));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Update an entity.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public TransactionViewModel Update(TransactionViewModel model)
        {
            this.ThrowExceptionIfExist(model);

            var entity = model.ToEntity();

            entity = this._TransactionsRepository.Update(entity);

            #region Commit Changes
            this._unitOfWork.Commit();
            #endregion

            model = entity.ToModel();
            return(model);
        }
Exemplo n.º 18
0
        public async Task <IActionResult> MakeIncome(int id)
        {
            var wallet = await walletWebService.Get(id);

            var categories = await transactionWebService.GetIncomeCategories();

            var transaction = new TransactionViewModel
            {
                TargetWalletId = (int)wallet.Id,
                TargetWallet   = wallet.Description
            };

            ViewBag.Categories = categories;
            return(View(transaction));
        }
Exemplo n.º 19
0
        public IActionResult Delete(Guid id, TransactionViewModel model)
        {
            try
            {
                _commandDispatcher.Execute(new TransactionRemoveCommand(id, model.OriginalVersion));

                return(RedirectToAction("Index"));
            }
            catch (DomainValidationException validationException)
            {
                ModelState.AddModelError(validationException.Property, validationException.Message);
            }

            return(View(model));
        }
        public ActionResult Index(DateTime?startDate, DateTime?endDate)
        {
            var userName = this.User.Identity.Name;

            var transactionViewModel = new TransactionViewModel()
            {
                UserName  = userName,
                StartDate = startDate,
                EndDate   = endDate
            };

            var allTrransactions = this.transactionService.GetClientTransactionsFromDateToDate(transactionViewModel);

            return(this.View(allTrransactions));
        }
        public ActionResult Edit(int id, TransactionViewModel transaction)
        {
            try
            {
                //Updating transaction isfraud value
                TransactionRepository transacRep = new TransactionRepository();
                transacRep.SetIsFraud(transaction.Id, transaction.IsFraud);

                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                return(View());
            }
        }
Exemplo n.º 22
0
        public async Task <TransactionViewModel> SaveTransactionAsync(int accountId, double amount)
        {
            TransactionViewModel newTransaction = null;
            //mock asynchronous data saving to data source - only for exercise purposes!
            await Task.Factory.StartNew(() =>
            {
                var transaction = new Transaction {
                    AccountId = accountId, Amount = amount
                };
                _data.Add(transaction);
                newTransaction = AutoMapper.Mapper.Map <TransactionViewModel>(transaction);
            });

            return(newTransaction);
        }
Exemplo n.º 23
0
        public string CreateTransaction(TransactionViewModel model)
        {
            var newTrans = new Transaction()
            {
                UsersTransaction = model.User,
                TakerCompany     = model.TakerCompany,
                ReasonForPayment = model.ReasonForPaymont,
                Date             = model.Data,
                Cash             = model.Cash
            };

            db.Transactions.Add(newTrans);
            db.SaveChanges();
            return("You successful pay ");
        }
Exemplo n.º 24
0
        public ActionResult Delete(TransactionViewModel model)
        {
            var deleteModel = _mapper.Map <TransactionModel>(model);

            try
            {
                _transactionService.Delete(deleteModel);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 25
0
        public ActionResult AddRecurringPayment(int id, TransactionViewModel model)
        {
            if (ModelState.IsValid)
            {
                var recurringTransaction = new RecurringTransaction
                {
                    Name      = model.Name,
                    StartDate = (DateTime)model.StartDate,
                    EndDate   = model.EndDate,
                    PeriodId  = (int)model.PeriodId,
                };
                db.RecurringTransactions.Add(recurringTransaction);

                var transaction = new Transaction
                {
                    Name      = model.Name,
                    Amount    = model.Amount,
                    Date      = (DateTime)model.StartDate,
                    TrackerId = id,
                    PersonId  = currentPersonId,
                    RecurringTransactionId = recurringTransaction.Id
                };
                db.Transactions.Add(transaction);

                if (model.TagIds != null)
                {
                    foreach (int t in model.TagIds)
                    {
                        var tag = new Transaction_Tag
                        {
                            TransactionId = transaction.Id,
                            TagId         = t,
                        };
                        db.TransactionTags.Add(tag);
                    }
                }

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            else
            {
                model.TagCollection    = from t in db.Tags where t.PersonId == currentPersonId select t;
                model.PeriodCollection = db.Periods.ToList <Period>();
                model.Tracker          = (from t in db.Trackers where t.Id == id select t).First();
                return(PartialView(model));
            }
        }
        public async Task <IActionResult> TransferMiles()
        {
            var user = await GetCurrentUser();

            if (user == null)
            {
                return(RedirectToAction(nameof(AccountController.LoginClient), "Account"));
            }

            var model = new TransactionViewModel
            {
                Values = GetBlocks()
            };

            return(PartialView("_TransferMiles", model));
        }
Exemplo n.º 27
0
        public TransactionViewModel ToTransactionViewModel(Transaction transaction, User user)
        {
            var model = new TransactionViewModel
            {
                Id         = transaction.Id,
                EndBalance = transaction.EndBalance,
                //Todo PremiumOffer = transaction.Product.Title,
                Price        = transaction.Price,
                StartBalance = transaction.StartBalance,
                TransferTo   = transaction.TransferTo,
                Type         = transaction.TransactionType,
                Value        = transaction.Value
            };

            return(model);
        }
Exemplo n.º 28
0
        public ActionResult <Models.Transaction> Post([FromBody] TransactionViewModel transaction)
        {
            var user           = rocketDbContext.Users.Find(transaction.UserId);
            var newTransaction = new Models.Transaction {
                Id      = transaction.Id,
                Type    = transaction.Type,
                Amount  = transaction.Amount,
                Comment = transaction.Comment,
                User    = user
            };

            rocketDbContext.Transactions.Add(newTransaction);
            rocketDbContext.SaveChanges();

            return(CreatedAtAction(nameof(Post), new { id = newTransaction.Id }, newTransaction));
        }
Exemplo n.º 29
0
        public IActionResult TransferMoney(int accountId)
        {
            var account  = _accountService.GetAccountById(accountId);
            var customer = _customerService.GetCustomerByAccountId(account.AccountId);

            var transactionModel = new TransactionViewModel
            {
                AccountId     = account.AccountId,
                CustomerId    = customer.CustomerId,
                Balance       = account.Balance,
                Name          = customer.Givenname + " " + customer.Surname,
                OperationList = LoadOperations(),
            };

            return(View(transactionModel));
        }
Exemplo n.º 30
0
        public IActionResult Transfer(long id)
        {
            Transaction          transaction = transactionRepository.GetTransaction(id);
            TransactionViewModel model       = new TransactionViewModel
            {
                transDate   = transaction.transDate,
                transAmount = transaction.transAmount,
                fromAccount = transaction.fromAccount,
                toAccount   = transaction.toAccount,
                typeId      = transaction.typeId
            };

            transactionRepository.SaveTransaction(model);

            return(View("Transfer"));
        }
        public async void PostValidTransactionReturnsSavedTransaction()
        {
            var user = UserHelper.BuildUser();
            var catTypeOne = new CategoryType { Name = "Test" };
            var catTypeTwo = new CategoryType { Name = "Test" };
            var from = new Category { Name = "FromCategory", AccountingUser = user, CategoryType = catTypeTwo };
            var to = new Category { Name = "ToCategory", AccountingUser = user, CategoryType = catTypeOne };
            var transType = new TransactionType { Name = "Category", To = catTypeOne, From = catTypeTwo };
            var server = StartupServer.Create();
            server.Setup = async (context) =>
            {
                await UserHelper.CreateUser(context, user);
                var dbCtx = context.RequestServices.GetRequiredService<AccountingContext>();
                dbCtx.CategoryTypes.Add(catTypeOne);
                dbCtx.CategoryTypes.Add(catTypeTwo);
                dbCtx.Categories.Add(from);
                dbCtx.Categories.Add(to);
                dbCtx.TransactionTypes.Add(transType);
                dbCtx.SaveChanges();
            };
            await server.RunSetup();

            var transaction = new TransactionViewModel
            {
                FromId = from.Id,
                ToId = to.Id,
                TransactionTypeId = transType.Id,
                DateTime = DateTime.UtcNow,
                Total = 250
            };

            var cookies = await UserHelper.SignIn(server, user);

            var result = await TestServerHelper.SendAsync(server, $"{TestServerHelper.BaseUrl}/{transactionUrl}", cookieHeader: cookies, method: HttpMethod.Post, body: transaction, tokens: true);
            result.StatusCode.Should().Be(HttpStatusCode.Created, "because it created a resource");
            result.ResponseText.Should().NotBeNullOrWhiteSpace("because it returns the created transaction");
            var transResult = JsonConvert.DeserializeObject<TransactionViewModel>(result.ResponseText);
            transResult.Total.Should().Be(transaction.Total, "because it should have the same total");
            transResult.Id.Should().NotBe(0, "because the database should assign it a new id");

            result = await TestServerHelper.SendAsync(server, $"{TestServerHelper.BaseUrl}/{transactionUrl}/{transResult.Id}", cookieHeader: cookies);
            transResult = JsonConvert.DeserializeObject<TransactionViewModel>(result.ResponseText);
            transResult.Should().NotBeNull("because it should've persisted");
            transResult.Total.Should().Be(transaction.Total, "because it should have the same total");
        }
        public async void PostValidTransactionSavesForUser()
        {
            var user = UserHelper.BuildUser();
            var otherUser = UserHelper.BuildUser(username: "******", email: "*****@*****.**");
            var catTypeOne = new CategoryType { Name = "Test" };
            var catTypeTwo = new CategoryType { Name = "Test" };
            var from = new Category { Name = "FromCategory", AccountingUser = user, CategoryType = catTypeTwo };
            var to = new Category { Name = "ToCategory", AccountingUser = user, CategoryType = catTypeOne };
            var transType = new TransactionType { Name = "Category", To = catTypeOne, From = catTypeTwo };
            var server = StartupServer.Create();
            server.Setup = async (context) =>
            {
                await UserHelper.CreateUser(context, user);
                await UserHelper.CreateUser(context, otherUser);
                var dbCtx = context.RequestServices.GetRequiredService<AccountingContext>();
                dbCtx.CategoryTypes.Add(catTypeOne);
                dbCtx.CategoryTypes.Add(catTypeTwo);
                dbCtx.Categories.Add(from);
                dbCtx.Categories.Add(to);
                dbCtx.TransactionTypes.Add(transType);
                dbCtx.SaveChanges();
            };
            await server.RunSetup();

            var transaction = new TransactionViewModel
            {
                FromId = from.Id,
                ToId = to.Id,
                TransactionTypeId = transType.Id,
                DateTime = DateTime.UtcNow,
                Total = 250
            };

            var cookies = await UserHelper.SignIn(server, user);

            var result = await TestServerHelper.SendAsync(server, $"{TestServerHelper.BaseUrl}/{transactionUrl}", cookieHeader: cookies, method: HttpMethod.Post, body: transaction, tokens: true);
            result.StatusCode.Should().Be(HttpStatusCode.Created, "because it created a resource");
            result = await TestServerHelper.SendAsync(server, $"{TestServerHelper.BaseUrl}/{transactionUrl}", cookieHeader: cookies);
            var transactions = JsonConvert.DeserializeObject<List<TransactionViewModel>>(result.ResponseText);
            transactions.Count.Should().Be(1, "because the created transaction should be associated with this user");

            await UserHelper.SignOut(server, cookies);
            cookies = await UserHelper.SignIn(server, otherUser);
            result = await TestServerHelper.SendAsync(server, $"{TestServerHelper.BaseUrl}/{transactionUrl}", cookieHeader: cookies);
            transactions = JsonConvert.DeserializeObject<List<TransactionViewModel>>(result.ResponseText);
            transactions.Count.Should().Be(0, "because the created transaction shouldn't be associated with this user");
        }
        public async void PostInvalidTransactionWithoutTransactionTypeReturns400()
        {
            var user = UserHelper.BuildUser();
            var from = new Category { Name = "FromCategory", AccountingUser = user };
            var to = new Category { Name = "ToCategory", AccountingUser = user };
            var server = StartupServer.Create();
            server.Setup = async (context) =>
            {
                await UserHelper.CreateUser(context, user);
                var dbCtx = context.RequestServices.GetRequiredService<AccountingContext>();
                dbCtx.Categories.Add(from);
                dbCtx.Categories.Add(to);
                dbCtx.SaveChanges();
            };
            await server.RunSetup();

            var transaction = new TransactionViewModel
            {
                FromId = from.Id,
                ToId = to.Id,
                TransactionTypeId = 0,
                DateTime = DateTime.UtcNow,
                Total = 700
            };

            var cookies = await UserHelper.SignIn(server, user);

            var result = await TestServerHelper.SendAsync(server, $"{TestServerHelper.BaseUrl}/{transactionUrl}", cookieHeader: cookies, method: HttpMethod.Post, body: transaction, tokens: true);
            result.StatusCode.Should().Be(HttpStatusCode.BadRequest, "because it was invalid");
            result.ResponseText.Should().NotBeNullOrWhiteSpace("because it returns an error");
            var error = JsonConvert.DeserializeObject<ErrorViewModel>(result.ResponseText);
            error.Error.Should().ContainEquivalentOf(string.Format(TransactionErrors.ValidationErrors.TransactionTypeNotFoundError, transaction.TransactionTypeId), "because the transaction type doesn't exist");
        }
        public async void PostInvalidTransactionSameFromAndToCategoryReturns400()
        {
            var user = UserHelper.BuildUser();
            var catTypeOne = new CategoryType { Name = "Test" };
            var to = new Category { Name = "ToCategory", AccountingUser = user, CategoryType = catTypeOne };
            var transType = new TransactionType { Name = "Category", To = catTypeOne, From = catTypeOne };
            var server = StartupServer.Create();
            server.Setup = async (context) =>
            {
                await UserHelper.CreateUser(context, user);
                var dbCtx = context.RequestServices.GetRequiredService<AccountingContext>();
                dbCtx.CategoryTypes.Add(catTypeOne);
                dbCtx.Categories.Add(to);
                dbCtx.TransactionTypes.Add(transType);
                dbCtx.SaveChanges();
            };
            await server.RunSetup();

            var transaction = new TransactionViewModel
            {
                FromId = to.Id,
                ToId = to.Id,
                TransactionTypeId = transType.Id,
                DateTime = DateTime.UtcNow,
                Total = 250
            };

            var cookies = await UserHelper.SignIn(server, user);

            var result = await TestServerHelper.SendAsync(server, $"{TestServerHelper.BaseUrl}/{transactionUrl}", cookieHeader: cookies, method: HttpMethod.Post, body: transaction, tokens: true);
            result.StatusCode.Should().Be(HttpStatusCode.BadRequest, "because it was invalid");
            result.ResponseText.Should().NotBeNullOrWhiteSpace("because it returns an error");
            var error = JsonConvert.DeserializeObject<ErrorViewModel>(result.ResponseText);
            error.Error.Should().ContainEquivalentOf(TransactionErrors.ValidationErrors.TransactionToSameCategoryError);
        }
Exemplo n.º 35
0
        public bool ValidateAndMapCreateTransaction(TransactionViewModel vm, Controller controller, string userId, out Transaction transaction, out ErrorViewModel errors)
        {
            var modelState = controller.ModelState;
            transaction = null;
            errors = null;

            if (vm.Total == null || vm.Total <= 0)
            {
                errors = new ErrorViewModel { Error = TransactionErrors.ValidationErrors.TransactionInvalidTotalError };
                return false;
            }

            var transactionType = this.transTypeRepo.FindById(vm.TransactionTypeId, tt => tt.From, tt => tt.To);
            if (transactionType == null)
            {
                errors = new ErrorViewModel { Error = string.Format(TransactionErrors.ValidationErrors.TransactionTypeNotFoundError, vm.TransactionTypeId) };
                return false;
            }

            if (vm.FromId == vm.ToId)
            {
                errors = new ErrorViewModel { Error = TransactionErrors.ValidationErrors.TransactionToSameCategoryError };
                return false;
            }

            var fromCategory = this.categoryRepo.FindById(vm.FromId, c => c.CategoryType);
            if (fromCategory == null || !string.Equals(fromCategory.AccountingUserId, userId))
            {
                errors = new ErrorViewModel { Error = string.Format(TransactionErrors.ValidationErrors.TransactionFromCategoryNotFoundError, vm.FromId) };
                return false;
            }

            var toCategory = this.categoryRepo.FindById(vm.ToId, c => c.CategoryType);
            if (toCategory == null || !string.Equals(toCategory.AccountingUserId, userId))
            {
                errors = new ErrorViewModel { Error = string.Format(TransactionErrors.ValidationErrors.TransactionToCategoryNotFoundError, vm.ToId) };
                return false;
            }

            if (toCategory.CategoryType.Id != transactionType.To.Id || fromCategory.CategoryType.Id != transactionType.From.Id)
            {
                errors = new ErrorViewModel { Error = TransactionErrors.ValidationErrors.TransactionTypeCategoryTypeMismatchError };
                return false;
            }

            if (!modelState.IsValid)
            {
                modelState.Clear();
                controller.TryValidateModel(vm);
            }

            if (!modelState.IsValid)
            {
                errors = new ErrorViewModel
                {
                    Error = TransactionErrors.ValidationErrors.TransactionInvalidError,
                    Errors = modelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList()
                };

                this.logger.LogWarning("Invalid transaction model:" + string.Join(";",
                    modelState.Values.SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)));
                return false;
            }

            transaction = Mapper.Map<Transaction>(vm);
            transaction.Id = 0;
            transaction.Total = Math.Round(transaction.Total, 2);
            transaction.From = fromCategory;
            transaction.To = toCategory;
            transaction.TransactionType = transactionType;
            transaction.AccountingUserId = userId;

            return true;
        }
        public async void PostValidTransactionWithoutTokensFails()
        {
            var user = UserHelper.BuildUser();
            var from = new Category { Name = "FromCategory", AccountingUser = user };
            var to = new Category { Name = "ToCategory", AccountingUser = user };
            var transType = new TransactionType { Name = "Category" };
            var server = StartupServer.Create();
            server.Setup = async (context) =>
            {
                await UserHelper.CreateUser(context, user);
                var dbCtx = context.RequestServices.GetRequiredService<AccountingContext>();
                dbCtx.Categories.Add(from);
                dbCtx.Categories.Add(to);
                dbCtx.TransactionTypes.Add(transType);
                dbCtx.SaveChanges();
            };
            await server.RunSetup();

            var transaction = new TransactionViewModel
            {
                FromId = from.Id,
                ToId = to.Id,
                TransactionTypeId = transType.Id,
                DateTime = DateTime.UtcNow,
                Total = 250
            };

            var cookies = await UserHelper.SignIn(server, user);

            Func<Task> action = async () =>
            {
                await TestServerHelper.SendAsync(server, $"{TestServerHelper.BaseUrl}/{transactionUrl}", cookieHeader: cookies, method: HttpMethod.Post, body: transaction);
            };
            await Assert.ThrowsAsync<InvalidOperationException>(action);
        }