public async Task <IActionResult> WalletNotified(string txid)
        {
            try
            {
                var existentTransaction = transactionService.FindInDatabase(txid);
                var transaction         = await transactionService.GetTransaction(txid);

                if (existentTransaction == null)
                {
                    transactionService.Add(transaction);
                }
                else
                {
                    transactionService.UpdateConfirmations(transaction.TxId, transaction.Confirmations);
                }

                if (walletService.GetWallet() == null)
                {
                    await walletService.CreateWalletIfNecessary();
                }
                else
                {
                    await walletService.UpdateWalletBalance();
                }

                await unitOfWork.SaveChanges();

                existentTransaction = transactionService.FindInDatabase(txid);
                return(Ok(existentTransaction.TxId));
            }
            catch (RpcErrorException ex)
            {
                return(BadRequest(ex.Error));
            }
        }
Exemplo n.º 2
0
 public IActionResult Add(string payerName, int points, DateTime timestamp)
 {
     _service.Add(new TransactionRecord {
         PayerName = payerName, Points = points, Timestamp = timestamp
     });
     return(Ok());
 }
Exemplo n.º 3
0
        private void SaveTransaction()
        {
            try
            {
                var deposit    = Convert.ToDecimal(txtQuantity.Text);
                var withdrawal = Convert.ToDecimal(txtWithDrawal.Text);



                var cardIdentifier = Convert.ToString(GetObjectFromCombobox(cmbCards));
                var account        = accountService.GetAccountForCardIdentifier(cardIdentifier);

                var transaction = new Transaction
                {
                    AccountId       = account.Id,
                    TransactionDate = DateTime.Now,
                    AssignedCard    = cardIdentifier,
                    Deposit         = deposit,
                    Withdrawal      = withdrawal
                };
                transactionService.Add(transaction);
            }
            catch (Exception ee)
            {
                throw;
            }
        }
        public ActionResult Add(TransactionsAddRequest request)
        {
            var userId = UserId;

            if (request.ContragentId == userId)
            {
                return(BadRequest(new { message = "Контрагент является текущим пользователем" }));
            }
            try {
                _transactionService.Add(userId, request.ContragentId, request.Amount);
            } catch (UserNotFoundException e) {
                switch (e.Name)
                {
                case "Payee": return(Unauthorized());

                case "Recepient": return(BadRequest(new { message = "Контрагент не найден" }));
                }
            } catch (ArgumentException e) {
                switch (e.ParamName)
                {
                case "amount":
                    return(BadRequest(new { message = "Недостаточно средств" }));
                }
                throw;
            }

            _unitOfWork.Complete();

            return(Ok());
        }
Exemplo n.º 5
0
        public IActionResult CreateMoneyTransaction(TransactionDto transaction)
        {
            var result = _transaction.Add(transaction);

            if (!result.IsError)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
Exemplo n.º 6
0
        public IActionResult Post(TransactionDataTransferObject transaction)
        {
            var transactionResult = _transactionService.Add(transaction);

            if (transactionResult.ResponseCode != ResponseCode.Success)
            {
                return(BadRequest(transactionResult.Error));
            }
            return(Ok(transactionResult.Result));
        }
        public void WhenAddIsCalled()
        {
            subject = new TransactionService(transactions);
            subject.Add(new TransactionRecord {
                PayerName = "Test", Points = 100, Timestamp = DateTime.Now
            });
            var response = subject.GetPayerBalance();

            response.Should().HaveCount(4, because: "a transaction with a new payer was added to the list");
        }
        public async Task <List <PaymentNotification> > Confirm(string reference, string hiDee)
        {
            var paymentNotification = await _context.PaymentNotifications.Where(x => x.Reference == reference).FirstOrDefaultAsync();

            if (paymentNotification == null)
            {
                throw new AppException("Payment notification is not found");
            }

            var user = await _context.Users.Where(x => x.Email == paymentNotification.Email).FirstOrDefaultAsync();

            if (user == null || ((user != null) && (!hiDee.Equals(GlobalVariables.BaseKey()))))
            {
                throw new AppException("User is not found");
            }

            if (paymentNotification.Confirmed == "Yes")
            {
                paymentNotification.Confirmed     = "No";
                paymentNotification.UpdateAllowed = true;
                await _transactionService.Delete(paymentNotification.Reference);

                if (paymentNotification.TransactionType == "Activation")
                {
                    user.ActivationRequested = true;
                    user.ActivationFeePaid   = false;
                }
            }
            else
            {
                paymentNotification.Confirmed     = "Yes";
                paymentNotification.UpdateAllowed = false;
                var transaction = new Transaction {
                    Reference       = paymentNotification.Reference,
                    TransactionType = paymentNotification.TransactionType,
                    Email           = paymentNotification.Email,
                    AmountPaid      = paymentNotification.AmountPaid,
                    PaymentChannel  = paymentNotification.PaymentChannel
                };
                await _transactionService.Add(transaction);

                if (paymentNotification.TransactionType == "Activation")
                {
                    user.ActivationRequested = true;
                    user.ActivationFeePaid   = true;
                }
            }

            _context.PaymentNotifications.Update(paymentNotification);
            _context.Users.Update(user);
            await _context.SaveChangesAsync();

            return(await _context.PaymentNotifications.OrderByDescending(x => x.DateAdded).ToListAsync());
        }
Exemplo n.º 9
0
        public IActionResult Post([FromBody] TransactionModel model)
        {
            if (model == null)
            {
                return(BadRequest());
            }

            transactionService.Add(model);

            return(Ok());
        }
Exemplo n.º 10
0
        public Task Handle(TransactionCreatedEvent @event)
        {
            _transactionService.Add(new TransactionInvoice()
            {
                Id_Transaccion = @event.Id_Transaction,
                Id_Invoice     = @event.Id_Invoice,
                Amount         = @event.Amount,
                Date           = @event.Date
            });

            return(Task.CompletedTask);
        }
        public IActionResult Add(Transaction transaction)
        {
            var AccountId = transactionService.AllAccounts().Where(a => a.Name == transaction.ToAccountName);

            foreach (var acc in AccountId)
            {
                transaction.ToAccountId = acc.Id;
            }
            transaction.FromAccountId = transaction.AccountId;
            transactionService.Add(transaction);
            return(RedirectToAction("add"));
        }
Exemplo n.º 12
0
        public HttpResponseMessage Create(HttpRequestMessage request, TransactionViewModel transactionVM)
        {
            return(CreateHttpResponse(request, () =>
            {
                if (!ModelState.IsValid)
                {
                    return request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
                else
                {
                    var transaction = new Transaction();
                    //var transactionDetails = transactionVM.TransactionDetails;
                    ICollection <TransactionDetail> transactionDetails = transactionVM.TransactionDetails;
                    var responseData = Mapper.Map <IEnumerable <TransactionDetail>, IEnumerable <TransactionDetailViewModel> >(transactionDetails);
                    //transactionVM.TransactionDetails = new List<TransactionDetail>();
                    if (transactionVM.UserId == null)
                    {
                        transactionVM.UserId = _userService.getByUserName(User.Identity.Name).Id;
                    }
                    transactionVM.CreatedBy = User.Identity.Name;
                    transaction.UpdateTransaction(transactionVM);
                    _transactionService.Add(transaction);
                    _transactionService.Save();
                    foreach (var item in responseData)
                    {
                        item.TransactionID = transaction.ID;
                        item.CreatedBy = User.Identity.Name;
                        item.CreatedDate = DateTime.Now;
                        var dbTransactionDetail = new TransactionDetail();
                        dbTransactionDetail.UpdateTransactionDetail(item);
                        _transactionDetailService.Add(dbTransactionDetail);
                        _transactionDetailService.Save();
                    }

                    //foreach (var item in transactionDetails)
                    //{
                    //    item.TransactionId = transactionVM.ID;
                    //    transactionVM.TransactionDetails.Add(item);
                    //}

                    //foreach (var item in responseData)
                    //{
                    //    var dbTransactionDetail = new TransactionDetail();
                    //    dbTransactionDetail.UpdateTransactionDetail(item);
                    //    dbTransactionDetail.TransactionId = item.ID;
                    //    //_transactionDetailService.Add(dbTransactionDetail);
                    //}

                    return request.CreateErrorResponse(HttpStatusCode.OK, transaction.ID.ToString());
                }
            }));
        }
        public ActionResult Create(TransactionEditModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Create", model));
            }

            model.Transaction.Updated = DateTime.Now;
            model.Transaction.ByUser  = User.Identity.Name;
            _transactionService.Add(model.Transaction);

            return(RedirectToAction("Index"));
        }
        public Task Handle(TransactionCreatedEvent @event)
        {
            _service.Add(new Model.Transaction()
            {
                TransactionId = @event.TransactionId,
                InvoiceId     = @event.InvoiceId,
                Amount        = @event.Amount,
                Date          = @event.Date
            });


            return(Task.CompletedTask);
        }
Exemplo n.º 15
0
        public static void Initialize(IUnitOfWork unitOfWork, IUserService userService, ITransactionService transactionService)
        {
            if (unitOfWork.Users.Any())
            {
                return;
            }

            void UserAdd(string name, string domain = "example.com", string password = "******", double balance = 500)
            {
                var login = $"{name.Replace(" ", "")}@{domain}";

                userService.Register(name, login, password, password, balance);
            }

            UserAdd("Kyle Porter");
            UserAdd("Tommy Stevens");
            UserAdd("Jordan Hart");
            UserAdd("Walter White", "bb.com", "C10h15N", 1000000);
            UserAdd("Samuel Knight");
            UserAdd("Tyler Dean");
            UserAdd("Jordan Briggs");
            UserAdd("Maddox Hewitt");
            UserAdd("Shawn Lindsey");
            UserAdd("Jaden Cote");
            UserAdd("Jett Benjamin");

            unitOfWork.Complete();

            var users = unitOfWork.Users.GetAll().ToDictionary(x => x.Name, x => x.Id);

            void TransactionAdd(string dtString, string payeeName, string recepientName, double amount)
            {
                var dt        = DateTime.Parse(dtString);
                var payee     = users[payeeName];
                var recepient = users[recepientName];

                transactionService.Add(dt, payee, recepient, amount);
            }

            TransactionAdd("2019.03.05 12:00:00", "Kyle Porter", "Tommy Stevens", 200);
            TransactionAdd("2019.03.05 12:30:00", "Kyle Porter", "Jordan Hart", 200);
            TransactionAdd("2019.03.08 09:30:00", "Walter White", "Kyle Porter", 1000);
            TransactionAdd("2019.03.09 12:00:00", "Kyle Porter", "Tyler Dean", 200);
            TransactionAdd("2019.03.09 12:30:00", "Kyle Porter", "Jordan Briggs", 200);
            TransactionAdd("2019.03.10 17:45:00", "Shawn Lindsey", "Walter White", 500);
            TransactionAdd("2019.03.10 17:45:01", "Jaden Cote", "Walter White", 500);
            TransactionAdd("2019.03.10 17:45:02", "Jett Benjamin", "Walter White", 500);
            TransactionAdd("2019.03.12 11:00:00", "Maddox Hewitt", "Tyler Dean", 50);

            unitOfWork.Complete();
        }
Exemplo n.º 16
0
        public IActionResult Post([FromBody] Transaction value)
        {
            if (value == null)
            {
                return(ResponseModel.Instance.ReturnResult(HttpStatusCode.NotAcceptable, "value cannot be null"));
            }

            if (!ModelState.IsValid)
            {
                return(ResponseModel.Instance.ReturnResult(HttpStatusCode.BadRequest, "model is not valid."));
            }
            _service.Add(value);
            return(ResponseModel.Instance.ReturnResult(HttpStatusCode.OK));
        }
Exemplo n.º 17
0
        public JsonResult Create(Transaction trans)
        {
            var userId = User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
                var user = userService.Get(userId);
                trans.UserId    = userId;
                trans.CompanyId = user.CompanyId;
                var result = transactionService.Add(trans);
                return(Json(result));
            }
            return(Json(true));
        }
Exemplo n.º 18
0
        public void No_EndTransaction_EventsRaisedTest()
        {
            var clientId = 101;

            _undoStackManager.CreateStackForClient(clientId);
            var undoStack = _undoStackManager.GetStackOfClient(clientId);

            int eventsRaised = 0;

            undoStack.ActiveStateChanged += (sender, changeSet) =>
            {
                eventsRaised++;
            };

            _transactionService.StartTransaction(clientId);

            _transactionService.Add(
                new Change(ChangeReason.InsertAt, 1, new TestObject())
                , clientId);


            Assert.AreEqual(0, eventsRaised);
        }
Exemplo n.º 19
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var result = await _transactionService.Add(Transaction);

            if (result.HasError)
            {
                Errors = string.Join(" /n ", result.ErrorMessages);
                return(Page());
            }

            return(RedirectToPage("./Success"));
        }
        public async Task <ActionResult> Post(
            [FromQuery] Guid transactionId,
            [FromQuery] Guid playerId,
            [FromQuery] TransactionType transactionType,
            [FromQuery] decimal amount)
        {
            var balance = await _playerService.GetBalance(playerId);

            if (!balance.HasValue)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Rejected."));
            }

            return(await _transactionService.Add(transactionId, playerId, transactionType, amount, balance.Value)
                ? Ok("Accepted")
                : StatusCode(StatusCodes.Status400BadRequest, "Rejected."));
        }
Exemplo n.º 21
0
 public ActionResult AddTransactions(TransactionCreateViewModel model)
 {
     try
     {
         transactionService.Add(model);
     }catch (Exception ex)
     {
         Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
         return(Json(new JsonMessage()
         {
             Status = JsonResultStatus.Fail, Message = "Adding failure"
         }, JsonRequestBehavior.AllowGet));
     }
     return(Json(new JsonMessage()
     {
         Status = JsonResultStatus.Success, Message = "Adding successfully"
     }, JsonRequestBehavior.AllowGet));
 }
 public ActionResult Create(TransactionModel model)
 {
     try
     {
         Transaction transaction = model;
         _transactionService.Add(transaction);
         return(RedirectToAction(nameof(Index), new TransactionsViewModel
         {
             transactions = _transactionService.GetListByCategoryId(transaction.CategoryId),
             categories = _categoryService.GetAll(),
             category = _categoryService.GetByCategoryId(transaction.CategoryId)
         }));
     }
     catch
     {
         return(View());
     }
 }
Exemplo n.º 23
0
        /// <inheritdoc />
        public Account AddAccount(int customerId, double initialCredit)
        {
            var response = IsValidCustomer(customerId);

            if (response.Equals(Response.Success))
            {
                var account = accountService.Add(customerId);
                if (!initialCredit.NearlyEqual(0))
                {
                    transactionService.Add(account.Id, initialCredit);
                }

                return(accountService.GetById(account.Id));
            }
            else
            {
                throw new MyBankException(response);
            }
        }
Exemplo n.º 24
0
        public ActionResult Confirm(int id, string note, bool status)
        {
            var         res         = false;
            Transaction transaction = new Transaction();

            transaction.OrderID = id;
            transaction.Note    = note;
            transaction.Status  = status;
            var idUser = userService.FindByUsername(User.Identity.Name).ID;

            transaction.CreateBy = idUser;
            res = transactionService.Add(transaction);
            // chuyển trạng thái order
            var order = orderService.FindById(id);

            order.Status = false;
            orderService.Update(order);
            transactionService.Save();
            return(Json(res, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 25
0
        public ActionResult <TransactionDto> Post(int accountId, [FromBody] TransactionDto transactionDto)
        {
            var transaction = new Transaction
            {
                Amount          = transactionDto.Amount,
                TransactionDate = transactionDto.Date,
                Description     = transactionDto.Description,
                AccountId       = accountId
            };

            var serviceResult = _transactionService.Add(transaction);

            if (serviceResult.ResponseCode != ResponseCode.Success)
            {
                return(BadRequest(serviceResult.Error));
            }

            transactionDto.Id = serviceResult.Result.Id;
            return(Ok(transactionDto));
        }
Exemplo n.º 26
0
        public IActionResult Add([FromBody] Transaction transaction)
        {
            Console.WriteLine(transaction.FromAccountName);
            Console.WriteLine(transaction.ToAccountName);
            transaction.Id = Guid.NewGuid();
            var AccountId = transactionService.AllAccounts().Where(a => a.Name == transaction.ToAccountName);

            foreach (var acc in AccountId)
            {
                transaction.ToAccountId = acc.Id;
            }
            var fromAccountId = transactionService.AllAccounts().Where(a => a.Name == transaction.FromAccountName);

            foreach (var frAcc in fromAccountId)
            {
                transaction.FromAccountId = frAcc.Id;
                transaction.AccountId     = frAcc.Id;
            }
            transactionService.Add(transaction);
            return(Ok(transaction));
        }
Exemplo n.º 27
0
        public BaseResponse <TransferResponse> Transfer(string userId, TransferRequest transferRequest)
        {
            var response = new BaseResponse <TransferResponse>();

            try
            {
                transferRequest.UserId = userId;
                TransferValidator transferValidator = new TransferValidator(_checkingAccountService);
                FluentValidation.Results.ValidationResult validationResult = transferValidator.Validate(transferRequest);

                if (!validationResult.IsValid)
                {
                    response.AddErrors(validationResult.Errors);
                    return(response);
                }

                var from = _checkingAccountService.UpdateBalance(transferRequest.NumberFrom, transferRequest.Amount * -1);
                var to   = _checkingAccountService.UpdateBalance(transferRequest.NumberTo, transferRequest.Amount);

                _transactionService.Add(new Transaction
                {
                    Amount = transferRequest.Amount,
                    FromCheckingAccountId = from.Id,
                    ToCheckingAccountId   = to.Id
                });

                _checkingAccountService.Commit();

                response.Data = new TransferResponse {
                    Balance = from.Balance
                };
            }
            catch (Exception ex)
            {
                _checkingAccountService.Rollback();
                response.AddError(1, "Erro inesperado");
            }
            return(response);
        }
Exemplo n.º 28
0
        public void Run()
        {
            while (IsContinue)
            {
                var transaction =
                    _loggerService.RunWithExceptionLogging(
                        () => _transactionGenerator.GenerateTransaction(_transactionValidators),
                        isSilent: true
                        );

                if (transaction == null)
                {
                    return;
                }

                _transactionService.Add(transaction);
                _loggerService.Info(
                    $"\n{transaction.Seller.FirstName} {transaction.Seller.SurName} -> {transaction.Buyer.FirstName} {transaction.Buyer.SurName},\nstock number = {transaction.StocksQuantity}, stock price = {transaction.Stock.Price}\n");
                Thread.Sleep(2000);
            }

            _repositoryClient.SaveChanges();
        }
        public static void AddTransactionService(this IBus bus, ITransactionService transactionService)
        {
            bus.Respond <TransactionAddMqRequest, TransactionAddMqResponse>(transactionAddMessageRequest =>
            {
                TransactionAddMqResponse transactionAddMessageResponse = transactionService.Add(transactionAddMessageRequest);

                return(transactionAddMessageResponse);
            });

            bus.Respond <TransactionGetByIdMqRequest, TransactionGetMqResponse>(transactionGetByIdMessageRequest =>
            {
                TransactionGetMqResponse transactionGetMessageResponse = transactionService.GetById(transactionGetByIdMessageRequest);

                return(transactionGetMessageResponse);
            });

            bus.Respond <TransactionGetAllByClientMqRequest, TransactionGetAllMqResponse>(transactionGetByClientMessageRequest =>
            {
                TransactionGetAllMqResponse transactionGetMessageResponse = transactionService.GetAllByClient(transactionGetByClientMessageRequest);

                return(transactionGetMessageResponse);
            });
        }
Exemplo n.º 30
0
        public void AddUpdate(IUndoable oldState, IUndoable newState, string description, int clientId)
        {
            var updateChange = new Change(oldState.Id, oldState, newState);

            _transactionService.Add(updateChange, clientId, description);
        }