Exemplo n.º 1
0
        public async Task Transfer(TransferDto transferDto)
        {
            var uri             = "https://localhost:5001/banking";
            var transferContent = new StringContent(JsonConvert.SerializeObject(transferDto),
                                                    System.Text.Encoding.UTF8, "application/json");
            var response = await _apiClient.PostAsync(uri, transferContent);

            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 2
0
        public async Task Transfer(TransferDto transferDto)
        {
            var uri             = _configuration["MicroServices_API:BankingAPI"];
            var transferContent = new StringContent(JsonConvert.SerializeObject(transferDto), System.Text.Encoding.UTF8, "application/json");

            var response = await _httpClient.PostAsJsonAsync(uri, transferContent);

            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 3
0
        public ActionResult Transfer()
        {
            inject();
            TransferDto m = new TransferDto()
            {
                accountNo = accountNumber
            };

            return(View(m));
        }
        public ActionResult MakeTransfer([FromBody] TransferDto data)
        {
            var userId = userManager.GetUserId(User);
            var user   = context.Users.Include(x => x.Wallets).FirstOrDefault(x => x.Id == userId);

            if (!user.Wallets.Any(x => x.Currency == data.Currency))
            {
                return(BadRequest());
            }

            var source = user.Wallets.FirstOrDefault(x => x.Currency == data.Currency);

            if (source.Amount < data.Amount)
            {
                return(BadRequest());
            }

            var destinationUser = context.Users.Include(x => x.Wallets).FirstOrDefault(x => x.UserName == data.Username);

            if (destinationUser == null)
            {
                throw new NotFoundException();
            }

            var destination = destinationUser.Wallets.FirstOrDefault(x => x.Currency == data.Currency);

            if (destination == null)
            {
                destination = new Wallet
                {
                    Amount   = 0,
                    Currency = data.Currency
                };

                destinationUser.Wallets.Add(destination);
            }

            source.Amount      -= data.Amount;
            destination.Amount += data.Amount;

            var transaction = new Transaction
            {
                Amount = data.Amount,
                Date   = DateTime.Now,
                DestinationWalletId = destination.Id,
                SourceWalletId      = source.Id
            };

            context.Add(transaction);

            context.SaveChanges();

            return(Ok());
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Transfer([FromForm] TransferViewModel model)
        {
            var transferDto = new TransferDto {
                FromAccount    = model.FromAccount,
                ToAccount      = model.ToAccount,
                TransferAmount = model.TransferAmount
            };
            await _transferService.Transfer(transferDto);

            return(View());
        }
Exemplo n.º 6
0
        public async Task <ActionResult> Transfer([FromBody] TransferViewModel model)
        {
            var dto = new TransferDto
            {
                SourceAccountId = model.SourceAccountId,
                TargetAccountId = model.TargetAccountId,
                Amount          = model.Amount
            };
            await transferService.Transfer(dto);

            return(Ok());
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Transfer(TransferViewModel model)
        {
            TransferDto transferDto = new TransferDto();

            transferDto.FromAccount    = model.FromAccount;
            transferDto.ToAccount      = model.ToAccount;
            transferDto.TransferAmount = model.TransferAmount;

            await _transferService.Transfer(transferDto);

            return(View(nameof(Index)));
        }
Exemplo n.º 8
0
        public async Task Transfer(TransferDto transferDto)
        {
            // TODO: Add to appsettings.json
            const string uri = "https://localhost:5001/api/Banking";

            var transferContent = new StringContent(JsonConvert.SerializeObject(transferDto), Encoding.UTF8,
                                                    "application/json");

            var response = await _httpClient.PostAsync(uri, transferContent);

            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Transfer(TransferViewModel model)
        {
            TransferDto transferDto = new TransferDto()
            {
                FromAccount    = model.FromAccount,
                ToAccount      = model.ToAccount,
                TransferAmount = model.TransferAmount
            };
            await _transferService.Transfer(transferDto);

            return(View("Index"));
        }
Exemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <SystemUserGetRoleUsersOutput> GetChosenPrivilegeMasterUser(SystemUserGetChosenPrivilegeMasterUser input)
        {
            SystemUserGetRoleUsersOutput output = new SystemUserGetRoleUsersOutput();
            var chosenUserDtos = await _userInfoRepository.GetChosenUser(new FreezeInput { IsFreeze = false });

            var allOrgs = (await _organizationLogic.GetAllEnumerableAsync()).ToList();
            //获取所有的用户
            var permissions =
                (await
                 _permissionUserLogic.GetPermissionUsersByPrivilegeMasterAdnPrivilegeMasterValue(input.PrivilegeMaster,
                                                                                                 input.PrivilegeMasterValue)).ToList();
            IList <string>      haveUser = new List <string>();
            IList <TransferDto> allUser  = new List <TransferDto>();

            foreach (var user in chosenUserDtos)
            {
                var permission = permissions.Where(w => w.PrivilegeMasterUserId == user.UserId).FirstOrDefault();
                if (permission != null)
                {
                    haveUser.Add(user.UserId.ToString());
                }

                TransferDto dto = new TransferDto
                {
                    key   = user.UserId.ToString(),
                    label = user.Name
                };
                string description  = string.Empty;
                var    organization = allOrgs.FirstOrDefault(w => w.OrganizationId == user.OrganizationId);
                if (organization != null && !organization.ParentIds.IsNullOrEmpty())
                {
                    foreach (var parent in organization.ParentIds.Split(','))
                    {
                        //查找上级
                        var dicinfo = allOrgs.FirstOrDefault(w => w.OrganizationId.ToString() == parent);
                        if (dicinfo != null)
                        {
                            description += dicinfo.Name + ">";
                        }
                    }
                    if (!description.IsNullOrEmpty())
                    {
                        description = description.TrimEnd('>');
                    }
                }
                dto.description = description;
                allUser.Add(dto);
            }
            output.AllUser  = allUser;
            output.HaveUser = haveUser;
            return(output);
        }
        public async Task SecondAccountBalanceAfterTransferTest()
        {
            var dto = new TransferDto
            {
                AccountFromId = new Guid("bd877de3-d2c9-4237-b5ca-08bd3ba56cd8"),
                AccountToId   = new Guid("29222f0b-dd48-4589-921b-02eb8a4518f0"),
                Amount        = 500
            };

            await _controller.Transfer(dto);

            Assert.AreEqual(600, _fakeContext.BankAccounts.ElementAt(1).Balance);
        }
Exemplo n.º 12
0
        public async Task Transfer(TransferDto transferDto)
        {
            // HttpClientHandler clientHandler = new HttpClientHandler();
            // clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

            // HttpClient client = new HttpClient(clientHandler);

            var uri      = "https://localhost:5001/api/banking";
            var content  = new StringContent(JsonConvert.SerializeObject(transferDto), Encoding.UTF8, "application/json");
            var response = await _apiClient.PostAsync(uri, content);

            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Transfer(TransferViewModel transferViewModel)
        {
            var transferDto = new TransferDto()
            {
                AccountFrom     = transferViewModel.FromAccount,
                AccountTo       = transferViewModel.ToAccount,
                TransferAmmount = transferViewModel.TeansferAmmount
            };

            await _transferService.Transfer(transferDto);

            return(View("Index"));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Transfer(TransferViewModel model)
        {
            TransferDto transferDto = new TransferDto()
            {
                FromAccount   = model.FromAccount,
                ToAccount     = model.ToAccount,
                TransferAmout = model.TransferAmount
            };

            // transfer service was injected
            await _transferService.Transfer(transferDto); // I've turned the functionality we need into a service, in order to such functionality to be reusable (and injectable)

            return(View("Index"));
        }
Exemplo n.º 15
0
        /// <summary>
        /// 获取用户角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <SystemRoleChosenOutput> GetChosenRoles(IdInput input)
        {
            SystemRoleChosenOutput output = new SystemRoleChosenOutput();
            //获取所有角色
            IList <SystemRoleOutput> roleDtos = (await GetRolesByOrganizationId(new SystemRolesGetByOrganizationId())).ToList();
            //获取当前人员具有的角色
            IList <SystemRole> roles     = (await GetHaveUserRole(EnumPrivilegeMaster.角色, input.Id)).ToList();
            var                 allOrgs  = (await _organizationRepository.FindAllAsync()).ToList();
            IList <string>      haveUser = new List <string>();
            IList <TransferDto> allUser  = new List <TransferDto>();

            foreach (var role in roleDtos)
            {
                var permission = roles.Where(w => w.RoleId == role.RoleId).FirstOrDefault();
                if (permission != null)
                {
                    haveUser.Add(role.RoleId.ToString());
                }

                TransferDto dto = new TransferDto
                {
                    key   = role.RoleId.ToString(),
                    label = role.Name
                };
                string description  = string.Empty;
                var    organization = allOrgs.FirstOrDefault(w => w.OrganizationId == role.OrganizationId);
                if (organization != null && !organization.ParentIds.IsNullOrEmpty())
                {
                    foreach (var parent in organization.ParentIds.Split(','))
                    {
                        //查找上级
                        var dicinfo = allOrgs.FirstOrDefault(w => w.OrganizationId.ToString() == parent);
                        if (dicinfo != null)
                        {
                            description += dicinfo.Name + ">";
                        }
                    }
                    if (!description.IsNullOrEmpty())
                    {
                        description = description.TrimEnd('>');
                    }
                }
                dto.description = description;
                allUser.Add(dto);
            }
            output.AllRole  = allUser;
            output.HaveRole = haveUser;
            return(output);
        }
Exemplo n.º 16
0
        public static Transfer Map(TransferDto transferDto)
        {
            if (transferDto == null)
            {
                return(null);
            }
            Transfer transfer = new Transfer();

            transfer.AccountFromId = transferDto.AccountFromId;
            transfer.AccountToId   = transferDto.AccountToId;
            transfer.Amount        = transferDto.Amount;
            transfer.Name          = transferDto.Title;
            transfer.TransferDate  = transferDto.TransferDate.ToLocalTime();
            return(transfer);
        }
Exemplo n.º 17
0
        public void Error_WhenRestockAmount_Null()
        {
            var TransferDto = new TransferDto
            {
                TotalCansLeft        = 18,
                TotalCansSold        = 2,
                TotalCashCollected   = 4.5,
                TotalCreditCollected = 4.5,
                RestockNumber        = null
            };

            var ops    = new VendingMachineOperations();
            var answer = ops.Restock(TransferDto);

            Assert.True(answer.ErrorMessage == "Error: Please enter number of cans to restock and Try Again!!");
        }
Exemplo n.º 18
0
 public async Task Transfer(TransferDto transferDto)
 {
     try
     {
         readerWriterLock.EnterWriteLock();
         var uri = "http://localhost:6061/api/Banking";
         var transferContent = new StringContent(JsonConvert.SerializeObject(transferDto), encoding: Encoding.UTF8, "application/json");
         var response =  _httpClient.PostAsync(uri, transferContent).Result;
         response.EnsureSuccessStatusCode();
     }
     finally
     {
         readerWriterLock.ExitWriteLock();
     }
     
 }
Exemplo n.º 19
0
        public void ErrorMessage_When_Amount_Null()
        {
            var TransferDto = new TransferDto
            {
                TotalCansLeft        = 20,
                TotalCansSold        = 0,
                TotalCashCollected   = 0,
                TotalCreditCollected = 0,
                CashEntered          = null,
            };

            var ops    = new VendingMachineOperations();
            var answer = ops.TakeMoneyAndRefund(TransferDto);

            Assert.True(answer.ErrorMessage == "Please enter an amount to buy a can.");
        }
Exemplo n.º 20
0
        public IHttpActionResult CreateTransfer(TransferDto transferDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var transfer = Mapper.Map <TransferDto, Transfer>(transferDto);

            _context.Transfers.Add(transfer);

            _context.SaveChanges();

            transferDto.Id = transfer.Id;
            return(Created(new Uri(Request.RequestUri + "/" + transfer.Id), transferDto));
        }
Exemplo n.º 21
0
 /// <summary>
 /// Mapping a TransferDto to View model for display on View
 /// </summary>
 /// <param name="transferDto"></param>
 /// <returns></returns>
 private VendingMachineViewModel TransferDtoToModel(TransferDto transferDto)
 {
     return(new VendingMachineViewModel
     {
         TotalCansLeft = transferDto.TotalCansLeft,
         TotalCashCollected = transferDto.TotalCashCollected,
         TotalCreditCollected = transferDto.TotalCreditCollected,
         RefundMessage = transferDto.RefundMessage,
         RestockNumber = transferDto.RestockNumber,
         TotalCansSold = transferDto.TotalCansSold,
         CashEntered = transferDto.CashEntered,
         ErrorMessage = transferDto.ErrorMessage,
         Operations = transferDto.Operations,
         CashCredit = transferDto.CashCredit
     });
 }
Exemplo n.º 22
0
        public void ErrorMessage_When_Amountlessthan_Required()
        {
            var TransferDto = new TransferDto
            {
                TotalCansLeft        = 20,
                TotalCansSold        = 0,
                TotalCashCollected   = 0,
                TotalCreditCollected = 0,
                CashEntered          = 3,
            };

            var ops    = new VendingMachineOperations();
            var answer = ops.TakeMoneyAndRefund(TransferDto);

            Assert.True(answer.ErrorMessage == "Money entered was not enough. Please enter atleast 4.5$ in the machine. Please collect your change and try again!!");
        }
Exemplo n.º 23
0
        public void ErrorMessage_When_NoCansLeft()
        {
            var TransferDto = new TransferDto
            {
                TotalCansLeft        = 0,
                TotalCansSold        = 0,
                TotalCashCollected   = 0,
                TotalCreditCollected = 0,
                CashEntered          = 5,
            };

            var ops    = new VendingMachineOperations();
            var answer = ops.TakeMoneyAndRefund(TransferDto);

            Assert.True(answer.ErrorMessage == "Sorry for inconvenience!! We have no cans left in machine anymore.");
        }
Exemplo n.º 24
0
        public void Error_WhenRestockTotal_GreaterThan_20()
        {
            var TransferDto = new TransferDto
            {
                TotalCansLeft        = 18,
                TotalCansSold        = 2,
                TotalCashCollected   = 4.5,
                TotalCreditCollected = 4.5,
                RestockNumber        = 3
            };

            var ops    = new VendingMachineOperations();
            var answer = ops.Restock(TransferDto);

            Assert.True(answer.ErrorMessage == "Error: Only 20 cans can be inserted in vending machine at a time");
        }
        public async Task <IHttpActionResult> Transfer([FromBody] TransferDto transferDto)
        {
            var account1 = DbContext.BankAccounts.FirstOrDefault(a => a.Id == transferDto.AccountFromId);
            var account2 = DbContext.BankAccounts.FirstOrDefault(a => a.Id == transferDto.AccountToId);

            if (account1 == null || account2 == null)
            {
                return(BadRequest());
            }

            if (account1.Balance < transferDto.Amount)
            {
                return(BadRequest());
            }

            var transaction = new Transaction()
            {
                Id          = Guid.NewGuid(),
                AccountFrom = account1,
                AccountTo   = account2,
                Amount      = transferDto.Amount,
                Timestamp   = DateTime.Now
            };

            account1.Balance -= transferDto.Amount;
            account2.Balance += transferDto.Amount;
            DbContext.SetModified(account1);
            DbContext.SetModified(account2);
            DbContext.Transactions.Add(transaction);

            try
            {
                await DbContext.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (TransactionExists(transaction.Id))
                {
                    return(Conflict());
                }

                throw;
            }

            return(CreatedAtRoute("Transfer", new { id = transaction.Id }, transaction));
        }
        public async Task TransactionAddedToLogOnTransferTest()
        {
            var dto = new TransferDto
            {
                AccountFromId = new Guid("bd877de3-d2c9-4237-b5ca-08bd3ba56cd8"),
                AccountToId   = new Guid("29222f0b-dd48-4589-921b-02eb8a4518f0"),
                Amount        = 500
            };

            var result = await _controller.Transfer(dto);

            var contentResult = result as CreatedAtRouteNegotiatedContentResult <Transaction>;

            Assert.IsNotNull(contentResult);
            Assert.AreEqual(2, _fakeContext.Transactions.Count());
            Assert.AreEqual(_fakeContext.Transactions.ElementAt(1).AccountFrom.Id, dto.AccountFromId);
            Assert.AreEqual(_fakeContext.Transactions.ElementAt(1).AccountTo.Id, dto.AccountToId);
        }
Exemplo n.º 27
0
        public static TransferDto Map(Transfer transfer)
        {
            if (transfer == null)
            {
                return(null);
            }
            TransferDto transferDto = new TransferDto();

            transferDto.AccountFromId = transfer.AccountFromId;
            transferDto.AccountFrom   = transfer.AccountFrom.Name;
            transferDto.AccountToId   = transfer.AccountToId;
            transferDto.AccountTo     = transfer.AccountTo.Name;
            transferDto.Amount        = transfer.Amount;
            transferDto.Id            = transfer.Id;
            transferDto.Title         = transfer.Name;
            transferDto.TransferDate  = transfer.TransferDate.ToUniversalTime();
            return(transferDto);
        }
        public override async Task Invoke(CancellationToken token)
        {
            var accountRepository = GetRepository <Account>();

            var fromAccount = await accountRepository.FirstOrDefaultAsync(a => a.Id == Command.From && !a.IsDeleted, token)
                              ?? throw new ArgumentException($"Can't found account by {Command.From}");

            var toAccount = await accountRepository.FirstOrDefaultAsync(a => a.Id == Command.To && !a.IsDeleted, token)
                            ?? throw new ArgumentException($"Can't found account by {Command.To}");

            var operation = new TransferOperation
            {
                Amount        = Command.Amount,
                Type          = OperationType.Transfer,
                From          = Command.From,
                To            = Command.To,
                OperationDate = Command.OperationDate,
                CreatedOn     = Command.CreatedOn,
                Comment       = Command.Comment,
                CreatedBy     = Command.CreatedBy
            };

            fromAccount.ChangeBalance(-Command.Amount);
            toAccount.ChangeBalance(Command.Amount);

            accountRepository.UpdateRange(new[] { fromAccount, toAccount });

            var result = await GetRepository <TransferOperation>().AddAsync(operation, token);

            await SaveAsync();

            var entity = result.Entity;

            Result = new TransferDto
            {
                Id      = entity.Id,
                Amount  = entity.Amount,
                Comment = entity.Comment,
                Date    = entity.OperationDate,
                Type    = entity.Type,
                FromId  = entity.From,
                ToId    = entity.To
            };
        }
        public async Task <IActionResult> MakeTransfer([FromBody] TransferDto data)
        {
            var userId = userManager.GetUserId(User);

            var command = new MakeTransferCommand
            {
                UserId      = userId,
                Transaction = data
            };

            var commandResult = await mediator.Send(command);

            if (!commandResult.IsSuccessful)
            {
                return(BadRequest());
            }

            return(Ok());
        }
Exemplo n.º 30
0
 public TransferDto GetById(long id)
 {
     using (var context = new CashFlowContext())
     {
         DataAccess.EF.Transfer efTransfer = context.Transfer
                                             .Include(t => t.AccountFrom)
                                             .Include(t => t.AccountTo)
                                             .SingleOrDefault(t => t.Id == id);
         if (efTransfer != null)
         {
             TransferDto transfer = TransferMapper.Map(efTransfer);
             return(transfer);
         }
         else
         {
             return(null);
         }
     }
 }