Ejemplo n.º 1
0
        public async Task <IActionResult> PostAccountAsync([FromBody] Account account)
        {
            await _accountService.AddAccount(account);

            var newAccount = await _accountService.GetAccount(account.Email);

            return(StatusCode(201, newAccount));
        }
Ejemplo n.º 2
0
        private async Task CreateAccount(CreateApplicationCommand request)
        {
            var accountData = await _accountsService.GetAccount(request.EncodedAccountId);

            await _levyTransferMatchingService.CreateAccount(new CreateAccountRequest(request.EmployerAccountId,
                                                                                      accountData.DasAccountName));
        }
Ejemplo n.º 3
0
        private async Task attachUserToContext(HttpContext context, IAccountsService accountService, string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                var email    = jwtToken.Claims.First(x => x.Type == "email").Value;

                // attach user to context on successful jwt validation
                context.Items["Account"] = await accountService.GetAccount(email);
            }
            catch
            {
                // do nothing if jwt validation fails
                // user is not attached to context so request won't have access to secure routes
            }
        }
        public async Task <GetAccountResult> Handle(GetAccountQuery request, CancellationToken cancellationToken)
        {
            var account = await _accountsService.GetAccount(request.EncodedAccountId);

            return(new GetAccountResult()
            {
                Account = account,
            });
        }
Ejemplo n.º 5
0
        public async Task <IViewComponentResult> InvokeAsync(string selectedTab)
        {
            var account = await _accountsService.GetAccount(AccountIdentification.ByGlobalUserId(((ClaimsPrincipal)User).GetUserId()));

            return(View(new SideBarViewModel
            {
                SelectedTab = selectedTab,
                Amount = account?.CurrentBalance ?? 0
            }));
        }
        public async Task <GetAmountQueryResult> Handle(GetAmountQuery request, CancellationToken cancellationToken)
        {
            var account = await _accountsService.GetAccount(request.EncodedAccountId);

            return(new GetAmountQueryResult
            {
                RemainingTransferAllowance = account.RemainingTransferAllowance,
                DasAccountName = account.DasAccountName
            });
        }
Ejemplo n.º 7
0
        public async Task ProcessTransaction(Transaction transaction)
        {
            ValidateTransactionAmount(transaction);
            ValidateTransactionAccounts(transaction);

            Console.WriteLine("TransactionsService: Started processing transaction.");

            var fromAccount = await _accountsService.GetAccount(transaction.FromAccountId);

            ValidateAccountHasEnoughMoney(fromAccount.Balance, transaction.Amount);

            var toAccount = await _accountsService.GetAccount(transaction.ToAccountId);

            await _transactionSemaphore.WaitAsync();

            try
            {
                fromAccount = await _accountsService.GetAccount(transaction.FromAccountId);

                ValidateAccountHasEnoughMoney(fromAccount.Balance, transaction.Amount);

                toAccount = await _accountsService.GetAccount(transaction.ToAccountId);

                fromAccount.Balance -= transaction.Amount;
                await _accountsService.UpdateAccount(fromAccount);

                toAccount.Balance += transaction.Amount;
                await _accountsService.UpdateAccount(toAccount);

                var transactionEntity = _mapper.Map <TransactionEntity>(transaction);
                await _transactionsRepository.AddTransaction(transactionEntity);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Transaction failed ({ex.Message})");
                throw;
            }
            finally
            {
                _transactionSemaphore.Release();
            }
        }
Ejemplo n.º 8
0
        public IEnumerable <Group> ListGroups(long?accountId)
        {
            if (accountId.HasValue)
            {
                var account = _accountsService.GetAccount(accountId.Value);
                return(account.Groups);
            }
            var accounts = _accountsService.ListAccounts();

            return(accounts.SelectMany(a => a.Groups).ToArray());
        }
Ejemplo n.º 9
0
        public IHttpActionResult GetAccount(int id)
        {
            Account account = accountsService.GetAccount(id);

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

            return(Ok(account));
        }
Ejemplo n.º 10
0
        protected async override void OnPublished(object data)
        {
            if (isOpen)
            {
                return;
            }

            IsBusy = true;

            if (Messages != null &&
                Messages.Any())
            {
                ClearMessages();
            }

            accountViewModel.Dispatcher = ViewModelContext.UiDispatcher;
            symbolsViewModel.Dispatcher = ViewModelContext.UiDispatcher;
            tradeViewModel.Dispatcher   = ViewModelContext.UiDispatcher;
            ordersViewModel.Dispatcher  = ViewModelContext.UiDispatcher;

            Account = new Account(new Interface.AccountInfo {
                User = new Interface.User()
            });

            try
            {
                userAccount = await accountsService.GetAccount(Title);

                var json = JsonConvert.SerializeObject(userAccount, Formatting.Indented);
                Logger.Log(json, Category.Info, Priority.Medium);
            }
            catch (Exception ex)
            {
                TradeViewModelException(ex.ToString(), ex);
            }

            if (userAccount != null &&
                userAccount.Preferences != null)
            {
                if (!string.IsNullOrWhiteSpace(userAccount.ApiKey))
                {
                    Account.ApiKey    = userAccount.ApiKey;
                    Account.ApiSecret = userAccount.ApiSecret;
                }
            }

            SymbolsViewModel.SetAccount(userAccount);
            AccountViewModel.SetAccount(account);

            isOpen = true;

            IsBusy = false;
        }
Ejemplo n.º 11
0
        public async Task <ActionResult <PagedResults <AccountResponse> > > GetAccount([FromQuery] PagingRequest request)
        {
            int brandId = Convert.ToInt32(User.FindFirst("BrandId")?.Value != "" ? User.FindFirst("BrandId")?.Value : "0");
            int role    = Convert.ToInt32(User.FindFirst(ClaimTypes.Role)?.Value != "" ? User.FindFirst(ClaimTypes.Role)?.Value : "0");

            if (role == 0)
            {
                brandId = 0;
            }
            var rs = await _accountService.GetAccount(request, brandId);

            return(Ok(rs));
        }
        public async Task GetAccount_Valid()
        {
            // Act
            var account = await _accountsService.GetAccount(Guid.Parse("bdca4f88-5868-4998-b5b1-6d7b77918c9b"));

            // Assert
            Assert.IsNotNull(account);
            Assert.IsInstanceOf <CustomerAccountDetailVm>(account);
            Assert.AreEqual(account.Address, _stubAccounts[0].Address);
            Assert.AreEqual(account.CanPurchase, _stubAccounts[0].CanPurchase);
            Assert.AreEqual(account.DOB, _stubAccounts[0].DOB);
            Assert.AreEqual(account.Email, _stubAccounts[0].Email);
            Assert.AreEqual(account.FirstName, _stubAccounts[0].FirstName);
            Assert.AreEqual(account.LastName, _stubAccounts[0].LastName);
            Assert.AreEqual(account.Id, _stubAccounts[0].Id);
            Assert.AreEqual(account.IsActive, _stubAccounts[0].IsActive);
            Assert.AreEqual(account.IsDeleteRequested, _stubAccounts[0].IsDeleteRequested);
            Assert.AreEqual(account.LoggedOnAt, _stubAccounts[0].LoggedOnAt);
            Assert.AreEqual(account.PhoneNumber, _stubAccounts[0].PhoneNumber);
            Assert.AreEqual(account.Postcode, _stubAccounts[0].Postcode);
        }
Ejemplo n.º 13
0
        public async Task <ActionResult> Index()
        {
            var vm      = new ActivityViewModel();
            var account = await _accountsService.GetAccount(User);

            if (account == null)
            {
                vm.Transactions = new List <Transaction>();
            }
            else
            {
                vm.Transactions = await _transactionsService.GetTransactions(account.Id);
            }

            return(View(vm));
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Details(Guid id)
        {
            string lowellReference = ApplicationSessionState.GetLowellReferenceFromSurrogate(id);

            Account account = await _accountsService.GetAccount(LoggedInUserId, lowellReference);

            MyAccountsDetailVm vm = _mapper.Map <Account, MyAccountsDetailVm>(account);

            vm.LoggedInUserId              = LoggedInUserId;
            vm.LoggedInLowellRef           = ApplicationSessionState.GetLoggedInLowellRef();
            vm.LowellReferenceSurrogateKey = id;

            _gtmService.RaiseAccountDetailsViewedEvent(vm, LoggedInUserId, "Regular Account");
            await _webActivityService.LogAccountDetailsViewed(vm.AccountReferenceText, LoggedInUserId);

            return(View(vm));
        }
        public async Task <IActionResult> GetAccount(Guid accountId)
        {
            _logger.LogInformation("Getting all custome account with id: " + accountId);
            if (accountId == null || accountId == Guid.Empty)
            {
                _logger.LogError("Failed to get account due to invalid or no account id");
                throw new ArgumentNullException(nameof(accountId));
            }
            var account = await _accountsService.GetAccount(accountId);

            if (account != null)
            {
                _logger.LogInformation("Successfully got account with account id: " + accountId);
                return(Ok(account));
            }
            _logger.LogError("Failed to get account with account id: " + accountId);
            return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
        }
Ejemplo n.º 16
0
        private bool IsReadingDuplicate(MeterReading reading)
        {
            var account  = _AccountsService.GetAccount(reading.AccountId);
            var readings = _MetersRepository.GetMeterReadingsByAccount(account);

            if (null != readings)
            {
                foreach (var accountReading in readings)
                {
                    if (accountReading.Reading == reading.Reading &&
                        accountReading.Recorded.Equals(reading.Recorded))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 17
0
        protected override async void OnPublished(object data)
        {
            if (isOpen)
            {
                return;
            }

            IsBusy = true;

            if (Messages != null &&
                Messages.Any())
            {
                ClearMessages();
            }

            accountViewModel.Dispatcher = ViewModelContext.UiDispatcher;
            symbolsViewModel.Dispatcher = ViewModelContext.UiDispatcher;
            tradeViewModel.Dispatcher   = ViewModelContext.UiDispatcher;
            ordersViewModel.Dispatcher  = ViewModelContext.UiDispatcher;

            Account = new Account(new Interface.AccountInfo {
                User = new Interface.User()
            });

            userAccount = accountsService.GetAccount(Title);

            if (userAccount != null &&
                userAccount.Preferences != null)
            {
                if (!string.IsNullOrWhiteSpace(userAccount.ApiKey))
                {
                    Account.ApiKey    = userAccount.ApiKey;
                    Account.ApiSecret = userAccount.ApiSecret;
                }
            }

            SymbolsViewModel.SetAccount(userAccount);
            AccountViewModel.SetAccount(account);

            isOpen = true;

            IsBusy = false;
        }
        public async Task <GetAccountResult> Handle(GetAccountQuery request, CancellationToken cancellationToken)
        {
            var validationResult = await _validator.ValidateAsync(request);

            if (!validationResult.IsValid())
            {
                throw new ArgumentException("The following parameters have failed validation", validationResult.ValidationDictionary.Select(c => c.Key).Aggregate((item1, item2) => item1 + ", " + item2));
            }

            var result = await _service.GetAccount(request.Id);

            if (result == null)
            {
                throw new EntityNotFoundException <Domain.Entities.Account>();
            }

            return(new GetAccountResult {
                Account = result
            });
        }
Ejemplo n.º 19
0
 public ActionResult GetPMReport(int id, int year)
 {
     try
     {
         XLWorkbook   Report      = ReportGenerator.CreatePMReport(id, year);
         MemoryStream excelStream = new MemoryStream();
         Report.SaveAs(excelStream);
         excelStream.Position = 0;
         AccountsModel account  = Account.GetAccount(id);
         string        filename = "KraReport_" + account.Name + "_" + year.ToString() + ".xlsx";
         return(File(excelStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename));
     }
     catch (Exception ex)
     {
         logger.Error(ex.InnerException);
         logger.Error(ex.Message);
         logger.Error(ex.Source);
         return(View("Something Went Wrong"));
     }
 }
Ejemplo n.º 20
0
 public ActionResult <AccountDTO> GetAccount(int accountId)
 {
     return(accountsService.GetAccount(accountId));
 }
Ejemplo n.º 21
0
        public static Task <Account> GetAccount(this IAccountsService accountsService, ClaimsPrincipal user)
        {
            var userId = user.GetUserId();

            return(accountsService.GetAccount(AccountIdentification.ByGlobalUserId(userId)));
        }
        public async Task <IActionResult> Transactions(
            TransactionsVm transactionsVm,
            int pageNumber = 1)
        {
            var value = RouteData.Values["id"];

            if (value == null)
            {
                return(RedirectToAction("Index", "MyAccounts"));
            }

            Guid.TryParse(value.ToString(), out var id);

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

            string lowellReference = ApplicationSessionState.GetLowellReferenceFromSurrogate(id);

            if (string.IsNullOrEmpty(lowellReference))
            {
                throw new Exception("No lowell reference found in cache");
            }

            Account account = ApplicationSessionState.GetAccount(lowellReference);

            if (account == null)
            {
                account = await _accountsService.GetAccount(LoggedInUserId, lowellReference);

                ApplicationSessionState.SaveAccount(account, lowellReference);
            }

            List <Transaction> transactions = ApplicationSessionState.GetTransactions(lowellReference);

            if (transactions == null)
            {
                transactions = await _transactionsService.GetTransactions(account.AccountReference);

                ApplicationSessionState.SaveTransactions(transactions, lowellReference);
            }

            if (transactions == null)
            {
                transactions = new List <Transaction>();
            }

            transactionsVm.AccountName      = account.OriginalCompany;
            transactionsVm.AccountBalance   = account.OutstandingBalance;
            transactionsVm.AccountReference = account.AccountReference;

            _gtmService.RaiseTransactionsViewedEvent(transactionsVm, LoggedInUserId, "Regular Account");
            await _webActivityService.LogAllTransactionsViewed(transactionsVm.AccountReference, LoggedInUserId);

            if (transactionsVm.FilterTransactions.DateFrom != null)
            {
                transactions = transactions.Where(x => x.Date >= transactionsVm.FilterTransactions.DateFrom).ToList();
            }

            if (transactionsVm.FilterTransactions.DateTo != null)
            {
                transactions = transactions.Where(x => x.Date <= transactionsVm.FilterTransactions.DateTo).ToList();
            }

            if (!string.IsNullOrEmpty(transactionsVm.FilterTransactions.KeyWord))
            {
                transactions = transactions.Where(x => x.Description.ToLower().Contains(transactionsVm.FilterTransactions.KeyWord.ToLower())).ToList();
            }

            transactions = transactions.OrderByDescending(x => x.Date).ToList();

            if (!transactions.Any())
            {
                transactionsVm.FilterTransactions.DateMessage = "No Results Found";
            }

            transactionsVm.PagedList =
                _mapper.Map <List <Transaction>, List <TransactionVm> >(transactions).ToPagedList(pageNumber, _pageSize);

            transactionsVm.LoggedInUserID    = LoggedInUserId;
            transactionsVm.LoggedInLowellRef = ApplicationSessionState.GetLoggedInLowellRef();

            return(View(transactionsVm));
        }
Ejemplo n.º 23
0
        public async Task <PaymentOptionsVm> Build(IUserIdentity loggedInUser, IApplicationSessionState applicationSessionState, Guid lowellReferenceSurrogateKey, string caseflowUserId)
        {
            string lowellReference = applicationSessionState.GetLowellReferenceFromSurrogate(lowellReferenceSurrogateKey);
            AccountReferenceDto accountReferenceDto = new AccountReferenceDto()
            {
                LowellReference = lowellReference
            };
            PaymentOptionsDto paymentOptionsDto = await _apiGatewayProxy.GetPaymentOptions(accountReferenceDto);

            IncomeAndExpenditureApiModel incomeAndExpenditureDto = await _apiGatewayProxy.GetIncomeAndExpenditure(lowellReference);

            List <AccountSummary> accounts;

            if (caseflowUserId != null)
            {
                accounts = await _accountsService.GetAccounts(caseflowUserId);
            }
            else
            {
                accounts = await _accountsService.GetMyAccountsSummary(lowellReference);
            }

            var workingAccounts = accounts.Count(a => !a.AccountStatusIsClosed);

            if (workingAccounts == 0)
            {
                workingAccounts = 1;
            }

            var accountDetails = await _accountsService.GetAccount(caseflowUserId, lowellReference);

            string[] planMessages = accountDetails.PlanMessages;

            var paymentOptionsVm = new PaymentOptionsVm()
            {
                OutstandingBalance                  = paymentOptionsDto.OutstandingBalance,
                LowellReference                     = paymentOptionsDto.LowellReference,
                ClientName                          = paymentOptionsDto.ClientName,
                ExcludedAccountMessage              = paymentOptionsDto.ExcludedAccountMessage,
                PlanInPlace                         = paymentOptionsDto.PlanInPlace,
                PlanIsDirectDebit                   = paymentOptionsDto.PaymentPlanIsDirectDebit,
                WithLowellSolicitors                = paymentOptionsDto.WithLowellSolicitors,
                PaymentOptions                      = new List <PaymentOptionsSelectionsVm>(),
                DiscountPercentage                  = paymentOptionsDto.DiscountPercentage,
                DiscountAmount                      = paymentOptionsDto.DiscountAmount,
                DiscountExpiryDate                  = paymentOptionsDto.DiscountExpiryDate,
                DiscountedBalance                   = paymentOptionsDto.DiscountedBalance,
                DiscountBalanceAvailable            = paymentOptionsDto.DiscountBalanceAvailable,
                ProposedDiscountedBalanceIfAccepted = paymentOptionsDto.ProposedDiscountedBalanceIfAccepted,
                DiscountedBalancePreviouslyAccepted = paymentOptionsDto.DiscountedBalancePreviouslyAccepted,
                ArrearsMessage                      = _arrearsDescriptionProcess.DeriveArrearsDetail(paymentOptionsDto.PaymentPlanArrearsAmount,
                                                                                                     paymentOptionsDto.PaymentPlanIsAutomated),
                StandingOrder           = paymentOptionsDto.StandingOrder,
                StandingOrderMessage    = paymentOptionsDto.StandingOrderMessage,
                VerifoneTransactionGuid = $"{paymentOptionsDto.LowellReference}_{Guid.NewGuid()}",
                DiscountAccepted        = paymentOptionsDto.DiscountedBalancePreviouslyAccepted,
                PlanMessage             = planMessages != null && planMessages.Length > 0? planMessages[0]:string.Empty
            };

            if (loggedInUser.IsLoggedInUser)
            {
                paymentOptionsVm.DirectDebitEmailAddress = loggedInUser.EmailAddress;
            }
            else
            {
                paymentOptionsVm.DirectDebitIsEmailAddressFieldVisible = true;
            }

            // Logged in user has accept T&C defaulted and will be hidden.
            // Anon user has tick box displayed. Must be ticked.
            if (loggedInUser.IsLoggedInUser)
            {
                paymentOptionsVm.AcceptTermsAndConditions = true;
            }
            else
            {
                paymentOptionsVm.IsAcceptTermsAndConditionsFieldVisible = true;
            }

            // Work out amount that needs to be paid to clear balance
            if (paymentOptionsVm.DiscountedBalancePreviouslyAccepted)
            {
                paymentOptionsVm.FullPaymentBalance = paymentOptionsVm.DiscountedBalance;
            }
            else
            {
                paymentOptionsVm.FullPaymentBalance = paymentOptionsVm.OutstandingBalance;
            }

            // Customer has a plan but it isn't direct debit.
            // Used to display a message informing customer that they can change to a DD online.
            if (paymentOptionsDto.PlanInPlace && !paymentOptionsDto.PaymentPlanIsDirectDebit)
            {
                paymentOptionsVm.HasNonDirectDebitPlanInPlace = true;
            }

            if (paymentOptionsDto.WithLowellSolicitors)
            {
                paymentOptionsVm.LowellSolicitorsRedirectLink = _portalSetting.SolicitorsRedirectDataProtectionUrl;
            }

            // Shared list of options for partial / full
            paymentOptionsVm.SourceOfFunds = BuildSourceOfFundsSelections(paymentOptionsDto);

            // Direct Debit
            paymentOptionsVm.DirectDebitFrequency         = BuildFrequencyList(paymentOptionsDto.DirectDebitFrequencies);
            paymentOptionsVm.DirectDebitStartDateEarliest = paymentOptionsDto.DirectDebitStartDateEarliest;
            paymentOptionsVm.DirectDebitStartDateLatest   = paymentOptionsDto.DirectDebitStartDateLatest;

            // TODO: Wrap the code below in a strategy pattern
            if (paymentOptionsDto.CanMakeFullPayment)
            {
                paymentOptionsVm.PaymentOptions.Add(new PaymentOptionsSelectionsVm()
                {
                    DisplayedText = "Card payment (Pay in Full)",
                    Value         = PaymentOptionsSelectionsVm.Values.FullPayment,
                    DataFormValue = PaymentOptionsSelectionsVm.Values.FullPayment
                });
            }
            if (paymentOptionsDto.CanMakePartialPayment)
            {
                paymentOptionsVm.PaymentOptions.Add(new PaymentOptionsSelectionsVm()
                {
                    DisplayedText = "Card payment (Partial amount)",
                    Value         = PaymentOptionsSelectionsVm.Values.PartialPayment,
                    DataFormValue = PaymentOptionsSelectionsVm.Values.PartialPayment,
                    ClassValue    = "js-hide-option"        // script hides this
                });
            }
            if (paymentOptionsDto.CanSetupDirectDebit)
            {
                paymentOptionsVm.PaymentOptions.Add(new PaymentOptionsSelectionsVm()
                {
                    DisplayedText = "Direct Debit plan",
                    Value         = PaymentOptionsSelectionsVm.Values.DirectDebit,
                    DataFormValue = PaymentOptionsSelectionsVm.Values.DirectDebit
                });
            }

            // Only add 'please select' if there are options
            // Required because view checks for availability of payment options
            if (paymentOptionsVm.PaymentOptions.Count > 0)
            {
                paymentOptionsVm.PaymentOptions.Insert(0, new PaymentOptionsSelectionsVm()
                {
                    DisplayedText = "Please Select",
                    Value         = PaymentOptionsSelectionsVm.Values.PleaseSelect,
                    DataFormValue = PaymentOptionsSelectionsVm.Values.PleaseSelect
                });
            }

            paymentOptionsVm.LowellReferenceSurrogate = lowellReferenceSurrogateKey;

            paymentOptionsVm.IandENotAvailable = incomeAndExpenditureDto == null;

            paymentOptionsVm.IandELessThanOrIs12MonthsOld =
                (incomeAndExpenditureDto != null && incomeAndExpenditureDto.Created.AddMonths(12).Date >= DateTime.Now.Date);
            paymentOptionsVm.AverageMonthlyPayment   = _portalSetting.AverageMonthlyPaymentAmount;
            paymentOptionsVm.MonthlyDisposableIncome =
                (incomeAndExpenditureDto == null ? 0 : (incomeAndExpenditureDto.DisposableIncome * (_portalSetting.MonthlyDisposableIncomePlanSetupPercentage / 100)));

            paymentOptionsVm.AccountCount = workingAccounts;
            paymentOptionsVm.MonthlyDisposableIncomePerAccount = paymentOptionsVm.MonthlyDisposableIncome / workingAccounts;

            return(paymentOptionsVm);
        }
Ejemplo n.º 24
0
        private async Task <int?> GetReservationLimit(long accountId)
        {
            var account = await _accountService.GetAccount(accountId);

            return(account.ReservationLimit);
        }
Ejemplo n.º 25
0
        public async Task <PayPalOrder> CreatePendingOrder(Guid accountId, decimal amount)
        {
            // TODO: Make this range configurable.
            if (amount <= 0 || amount > 500)
            {
                throw new Exception("Invalid amount.");
            }

            _logger.LogInformation("Creating pending paypal order for {AccountId} for {Amount}", accountId, amount);

            var account = await _accountsService.GetAccount(AccountIdentification.ById(accountId));

            account.NotNull();

            var    potentialOrderId = Guid.NewGuid();
            string paypalOrderId;

            {
                var client  = _payPalClientProvider.BuildHttpClient();
                var request = new OrdersCreateRequest();
                request.Prefer("return=representation");
                request.RequestBody(new OrderRequest
                {
                    CheckoutPaymentIntent = "CAPTURE",
                    PurchaseUnits         = new List <PurchaseUnitRequest>
                    {
                        new PurchaseUnitRequest
                        {
                            ReferenceId         = potentialOrderId.ToString(),
                            AmountWithBreakdown = new AmountWithBreakdown
                            {
                                Value        = amount.ToString(CultureInfo.InvariantCulture),
                                CurrencyCode = "USD"
                            }
                        }
                    }
                });

                var response = await client.Execute(request);

                if (response.StatusCode != HttpStatusCode.Created)
                {
                    _logger.LogError("Invalid status code from PayPal order create: status: {Status} response: {Response}", response.StatusCode, SerializePayPalType(response.Result <object>()));
                    throw new Exception("Invalid PayPal response");
                }

                paypalOrderId = response.Result <Order>().Id;
            }

            // Great, we created a PayPal order, let's add the record into the database.
            using (var con = new ConScope(_dataService))
            {
                var pendingOrder = new PayPalOrder
                {
                    Id            = potentialOrderId,
                    OrderStatus   = PayPalOrderStatus.Pending,
                    PayPalOrderId = paypalOrderId,
                    AccountId     = account.Id,
                    Amount        = amount
                };

                await con.Connection.InsertAsync(pendingOrder);

                return(pendingOrder);
            }
        }
Ejemplo n.º 26
0
 public AccountModel GetAccount(int accountId)
 {
     return(_accountsService.GetAccount(accountId)?.ToModel());
 }
Ejemplo n.º 27
0
        public void Can_Create_Delete_Account()
        {
            var servicePackages    = _lookupService.GetServicePackages();
            var contactTypes       = _lookupService.GetContactTypes().ToList();
            var contactMethods     = _lookupService.GetContactMethods().ToList();
            var paymentMethods     = _lookupService.GetPaymentMethods().ToList();
            var nvralertTypes      = _lookupService.GetNvrAlertTypes().ToList();
            var eventGroups        = _lookupService.GetEventGroups().ToList();
            var analyticAlgorithms = _lookupService.GetAnalyticAlgorithmTypes().ToList();


            //step 1 - create account
            var accountDto = new AccountDto
            {
                AccountNumber    = "123456789",
                Name             = "Test_Account",
                ServicePackageId = servicePackages.ToList().SingleOrDefault(sp => sp.Name == "Silver").ServicePackageId,
                WebSiteURL       = "http://2020Imaging.com",
                Email            = "*****@*****.**",
                Description      = "Test_Account_Description",
                TimeZoneId       = _lookupService.GetTimeZones().First().TimeZoneId,
                AccountTypeId    = _lookupService.GetAccountTypes().Single(at => at.AccoutTypeId == 2).AccoutTypeId,
                AccountBilling   = null,
            };

            var accountId = _accountService.AddAccount(accountDto);

            Assert.IsTrue(accountId > 0);

            var getAccount = _accountService.GetAccount(accountId);

            Assert.IsNotNull(getAccount);

            // step 2 - create person
            var personDto = new PersonDto
            {
                Title     = "Msr.",
                FirstName = "Victor",
                LastName  = "Lungu",
                JobTitle  = "WPF Developer",
                Password  = "******",
                PrimaryAccountAdministratorPassword = "******",
            };

            var preferedContact1 = new PersonContactTypeDto {
                ContactTypeId = contactTypes[0].ContactTypeId
            };
            var preferedContact2 = new PersonContactTypeDto {
                ContactTypeId = contactTypes[1].ContactTypeId
            };

            personDto.PreferedContactTypes = new List <PersonContactTypeDto> {
                preferedContact1, preferedContact2
            };
            var savedPerson = _accountService.SaveAccountPerson(personDto, getAccount.AccountId);

            Assert.IsNotNull(savedPerson);

            // step 3 - create contact
            var contactDto = new ContactDto
            {
                TelephoneNumber = "37379604494",
                EmailAddress    = "*****@*****.**",
                MobileNumber    = "37379604494",
                LyncName        = "Lync Name",
                FaxNumber       = "37379604494",
            };

            var preferedContatMethod1 = new PreferedContatMethodDto
            {
                ContactMethodId = contactMethods[0].ContactMethodId
            };

            var preferedContatMethod2 = new PreferedContatMethodDto
            {
                ContactMethodId = contactMethods[1].ContactMethodId
            };

            contactDto.PreferedContatMethods.Add(preferedContatMethod1);
            contactDto.PreferedContatMethods.Add(preferedContatMethod2);

            var savedContact = _accountService.SaveAccountContact(contactDto, savedPerson.PersonId);

            Assert.IsNotNull(savedContact);

            //step 4 - create accounnt address
            var addressDto = new AddressDto
            {
                AddressNumber   = 3343,
                AddressTypeCode = 22,
                City            = "Chisinau",
                Country         = "Moldova, Republic of",
                County          = "municipiiul Chisinau",
                Fax             = "37379604494",
                Latitude        = 100.22233,
                Line1           = "str. Iazului 6",
                Line2           = "ap. 53",
                Longitude       = 444332,
                Name            = "Main Address",
                PostOfficeBox   = "443332",
                PostalCode      = "PC5543"
            };

            var accountAddress = _accountService.SaveAccountAddress(addressDto, accountId);

            Assert.IsNotNull(accountAddress);

            //step 5 Billing address
            var billingAddress = new AddressDto
            {
                AddressNumber   = 3343,
                AddressTypeCode = 22,
                City            = "Chisinau",
                Country         = "Moldova, Republic of",
                County          = "municipiiul Chisinau",
                Fax             = "37379604494",
                Latitude        = 100.22233,
                Line1           = "str. Iazului 6",
                Line2           = "ap. 53",
                Longitude       = 444332,
                Name            = "Main Address",
                PostOfficeBox   = "443332",
                PostalCode      = "PC5543"
            };

            var accountBilling = new AccountBillingDto
            {
                PaymentMethodId = paymentMethods.First().PaymentMethodId,
                Address         = billingAddress
            };

            var accountBillig = _accountService.SaveAccountBilling(accountBilling, accountId);

            Assert.IsNotNull(accountBillig);

            var accountNvrAlertTypeDto1 = new AccountNvrAlertTypeDto
            {
                NvrAlertTypeId = nvralertTypes.First().NvrAlertTypeId
            };
            var accountNvrAlertTypeDto2 = new AccountNvrAlertTypeDto
            {
                NvrAlertTypeId = nvralertTypes.Last().NvrAlertTypeId
            };

            _accountService.SaveAccountNvrAlertType(
                new List <AccountNvrAlertTypeDto>()
            {
                accountNvrAlertTypeDto1, accountNvrAlertTypeDto2
            }, accountId);

            var accountAlarmPanel1 = new AccountAlarmPanelDto()
            {
                EventGroupId = eventGroups.First().EventGroupId
            };
            var accountAlarmPanel2 = new AccountAlarmPanelDto()
            {
                EventGroupId = eventGroups.Last().EventGroupId
            };

            _accountService.SaveAccountAlarmPanel(
                new List <AccountAlarmPanelDto>()
            {
                accountAlarmPanel1, accountAlarmPanel2
            }, accountId);

            var analyticAlgorithm1 = new AccountAnalyticsAlgorithmTypeDto()
            {
                AnalyticsAlgorithTypeId = analyticAlgorithms.First().AnalyticAlgorithmId
            };
            var analyticAlgorithm2 = new AccountAnalyticsAlgorithmTypeDto()
            {
                AnalyticsAlgorithTypeId = analyticAlgorithms.Last().AnalyticAlgorithmId
            };

            _accountService.SaveAccountAnalyticsAlgorithms(
                new List <AccountAnalyticsAlgorithmTypeDto>()
            {
                analyticAlgorithm1, analyticAlgorithm2
            }, accountId);

            var deleteContact = _accountService.DeleteContact(savedContact.ContactId);

            Assert.IsTrue(deleteContact);

            _accountService.DeletePerson(savedPerson.PersonId);
            var accountDeleted = _accountService.DeleteAccount(getAccount.AccountId);

            Assert.IsTrue(accountDeleted);
        }
 public ActionResult GetAccountById(string id)
 {
     return(RequireAuth(_accountService.GetAccount(id)));
 }