Ejemplo n.º 1
0
 public void SetUp()
 {
     _facade     = new LoanPaymentFacade();
     _calculator = new LoanScheduleCalculator();
     _loan       = new Loan();
     _startDate  = new DateTime(2012, 10, 10);
     _schedule   = _calculator.Calculate(3000m, _loan, _startDate);
 }
Ejemplo n.º 2
0
        private void RebatePayment(decimal?amount, Loan loan, string transId, DateTime now)
        {
            if (amount == null || amount <= 0)
            {
                return;
            }
            var f = new LoanPaymentFacade();

            f.PayLoan(loan, transId, amount.Value, Request.UserHostAddress, now, "system-repay");
        }
Ejemplo n.º 3
0
		public void PayPoiinApiGetAmountToPay() {
			try {
				ILoanRepository loanRep = ObjectFactory.GetInstance<LoanRepository>();
				var loan = loanRep.Get(2070);
				var facade = new LoanPaymentFacade();
				var installment = loan.Schedule.FirstOrDefault(s => s.Id == 3773);
				var state = facade.GetStateAt(loan, DateTime.Now);
				m_oLog.Debug("Amount to charge is: {0}", state.AmountDue);
			} catch (Exception ex) {
				m_oLog.Debug(ex);
			}
		}
Ejemplo n.º 4
0
        public void Init()
        {
            Assert.AreEqual(0, GetAmountToChargeFrom());

            _loan = new Loan();
            // _configurationVariablesRepository = config.Object;
            _facade     = new LoanPaymentFacade(new Mock <ILoanHistoryRepository>().Object, new Mock <ILoanTransactionMethodRepository>().Object, 0);
            _calculator = new LoanScheduleCalculator()
            {
                Interest = 0.06M
            };

            _customer = new Customer();

            SetUp();
        }
        public void SetUp()
        {
            _historyRepoMock = new Mock <ILoanHistoryRepository>();
            _loanTransatioMethodReporsitory = new Mock <ILoanTransactionMethodRepository>();
            _loan = new Loan()
            {
                Id = 1, Status = LoanStatus.Live
            };
            var calculator = new LoanScheduleCalculator();

            _startDate = new DateTime(2012, 1, 1);
            calculator.Calculate(_takenMoney, _loan, _startDate);
            _facade   = new LoanPaymentFacade(_historyRepoMock.Object, _loanTransatioMethodReporsitory.Object, 0);
            _customer = new Customer();
            _customer.Loans.Add(_loan);
            _loan.Customer = _customer;
        }
Ejemplo n.º 6
0
		public void TestPaymentFacade() {
			try {
				ILoanRepository loanRep = ObjectFactory.GetInstance<LoanRepository>();
				var loan = loanRep.Get(3117);
				NL_Payments nlPayment = new NL_Payments() {
					LoanID = 1,
					Amount = 1000,
					CreatedByUserID = 1, //this._context.UserId,
					CreationTime = DateTime.UtcNow,
					PaymentMethodID = (int)NLLoanTransactionMethods.SystemRepay
				};
				var f = new LoanPaymentFacade();
				f.PayLoan(loan, "111", 1000, "11.11.11.11", DateTime.UtcNow, "system-repay", false, null, nlPayment);
			} catch (Exception ex) {
				m_oLog.Debug(ex);
			}
		}
Ejemplo n.º 7
0
        public bool ApplyLateCharge(Loan loan, decimal amount, int loanChargesTypeId, DateTime date)
        {
            var charge = new LoanCharge {
                Amount      = amount,
                ChargesType = new ConfigurationVariable(CurrentValues.Instance.GetByID(loanChargesTypeId)),
                Date        = date,
                Loan        = loan
            };

            var res = loan.TryAddCharge(charge);

            var facade = new LoanPaymentFacade();

            facade.Recalculate(loan, date);

            _loans.Update(loan);

            //Log.Debug(string.Format("updated loan: {0}", loan));

            return(res);
        }
Ejemplo n.º 8
0
        private bool AddPayPointCardToCustomer(string transactionid, string cardno, EZBob.DatabaseLib.Model.Database.Customer customer, string expiry, decimal?amount, PayPointAccount account)
        {
            bool paymentAdded = false;

            customer.TryAddPayPointCard(transactionid, cardno, expiry, customer.PersonalInfo.Fullname, account);

            bool hasOpenLoans = customer.Loans.Any(x => x.Status != LoanStatus.PaidOff);

            if (amount > 0 && hasOpenLoans)
            {
                Loan loan = customer.Loans.First(x => x.Status != LoanStatus.PaidOff);

                var nlPayment = new NL_Payments()
                {
                    Amount          = amount.Value,
                    CreatedByUserID = this.context.UserId,
                    //CreationTime = DateTime.UtcNow,
                    //	LoanID = nlLoanId,
                    //PaymentTime = DateTime.UtcNow,
                    Notes = "Add paypoint card",
                    //PaymentStatusID = (int)NLPaymentStatuses.Active,
                    PaymentMethodID   = (int)NLLoanTransactionMethods.SystemRepay,
                    PaymentSystemType = NLPaymentSystemTypes.Paypoint
                };

                var f = new LoanPaymentFacade();
                f.PayLoan(loan, transactionid, amount.Value, Request.UserHostAddress, DateTime.UtcNow, "system-repay", false, null, nlPayment);

                paymentAdded = true;
            }

            if (amount > 0 && !hasOpenLoans)
            {
                this.serviceClient.Instance.PayPointAddedWithoutOpenLoan(customer.Id, this.context.UserId, amount.Value, transactionid);
            }

            this.serviceClient.Instance.PayPointAddedByUnderwriter(customer.Id, cardno, this.context.User.FullName, this.context.User.Id);

            return(paymentAdded);
        }
Ejemplo n.º 9
0
        public decimal GetAmountToPay(int installmentId)
        {
            try {
                Log.InfoFormat("Calculating payment for installment {0}", installmentId);

                var installments = ObjectFactory.GetInstance <ILoanScheduleRepository>();
                var facade       = new LoanPaymentFacade();

                var installment = installments.Get(installmentId);
                var loan        = installment.Loan;

                var state = facade.GetStateAt(loan, DateTime.Now);

                _loans.Update(loan);

                Log.InfoFormat("Amount to charge is: {0}", state.AmountDue);
                return(state.AmountDue);
            } catch (Exception ex) {
                Log.Error(ex);
                return(0);
            }
        }
Ejemplo n.º 10
0
        private static void MakeEarlyPayment(Loan loan, decimal amount, DateTime startDate)
        {
            var facade = new LoanPaymentFacade();

            facade.PayLoan(loan, "", amount, "", startDate);
        }
Ejemplo n.º 11
0
 public void SetUp()
 {
     _customer            = new Customer();
     _calculator          = new LoanScheduleCalculator();
     _loanRepaymentFacade = new LoanPaymentFacade();
 }
Ejemplo n.º 12
0
        public ActionResult Callback(
            bool valid,
            string trans_id,
            string code,
            string auth_code,
            decimal?amount,
            string ip,
            string test_status,
            string hash,
            string message,
            string type,
            int loanId,
            string card_no,
            string customer,
            string expiry
            )
        {
            if (test_status == "true")
            {
                // Use last 4 random digits as card number (to enable useful tests)
                string random4Digits = string.Format("{0}{1}", DateTime.UtcNow.Second, DateTime.UtcNow.Millisecond);

                if (random4Digits.Length > 4)
                {
                    random4Digits = random4Digits.Substring(random4Digits.Length - 4);
                }

                card_no = random4Digits;

                expiry = string.Format(
                    "{0}{1}",
                    "01",
                    DateTime.UtcNow.AddYears(2).Year.ToString().Substring(2, 2)
                    );
            }             // if

            var customerContext = this.context.Customer;

            PayPointFacade payPointFacade = new PayPointFacade(
                customerContext.MinOpenLoanDate(),
                customerContext.CustomerOrigin.Name
                );

            if (!payPointFacade.CheckHash(hash, Request.Url))
            {
                log.Alert("Paypoint callback is not authenticated for user {0}", customerContext.Id);

                this.logRepository.Log(
                    this.context.UserId,
                    DateTime.UtcNow,
                    "Paypoint Pay Redirect to ",
                    "Failed",
                    String.Format("Paypoint callback is not authenticated for user {0}", customerContext.Id)
                    );

                return(View("Error"));
            }             // if

            var statusDescription = PayPointStatusTranslator.TranslateStatusCode(code);

            if (!valid || code != "A")
            {
                if (code == "N")
                {
                    log.Warn(
                        "Paypoint result code is : {0} ({1}). Message: {2}",
                        code,
                        string.Join(", ", statusDescription.ToArray()),
                        message
                        );
                }
                else
                {
                    log.Alert(
                        "Paypoint result code is : {0} ({1}). Message: {2}",
                        code,
                        string.Join(", ", statusDescription.ToArray()),
                        message
                        );
                }                 // if

                this.logRepository.Log(
                    this.context.UserId,
                    DateTime.UtcNow,
                    "Paypoint Pay Redirect to ",
                    "Failed",
                    string.Format(
                        "Paypoint result code is : {0} ({1}). Message: {2}",
                        code,
                        string.Join(", ", statusDescription.ToArray()),
                        message
                        )
                    );

                return(View("Error"));
            }             // if

            if (!amount.HasValue)
            {
                log.Alert("Paypoint amount is null. Message: {0}", message);

                this.logRepository.Log(
                    this.context.UserId,
                    DateTime.UtcNow,
                    "Paypoint Pay Redirect to ",
                    "Failed",
                    String.Format("Paypoint amount is null. Message: {0}", message)
                    );

                return(View("Error"));
            }             // if

            // If there is transaction with such id in database,
            // it means that customer refreshes page
            // show in this case cashed result
            if (this.paypointTransactionRepository.ByGuid(trans_id).Any())
            {
                var data = TempData.Get <PaymentConfirmationModel>();

                if (data == null)
                {
                    return(RedirectToAction("Index", "Profile", new { Area = "Customer" }));
                }

                return(View(TempData.Get <PaymentConfirmationModel>()));
            }             // if

            NL_Payments nlPayment = new NL_Payments()
            {
                CreatedByUserID   = this.context.UserId,
                Amount            = amount.Value,
                PaymentMethodID   = (int)NLLoanTransactionMethods.CustomerAuto,
                PaymentSystemType = NLPaymentSystemTypes.Paypoint
            };

            log.Debug("Callback: Sending nlPayment: {0} for customer {1}, oldloanId {2}", nlPayment, this.context.UserId, loanId);

            LoanPaymentFacade loanRepaymentFacade = new LoanPaymentFacade();
            PaymentResult     res = loanRepaymentFacade.MakePayment(trans_id, amount.Value, ip, type, loanId, customerContext, null, "payment from customer", null, null, nlPayment);

            SendEmails(loanId, amount.Value, customerContext);

            this.logRepository.Log(this.context.UserId, DateTime.UtcNow, "Paypoint Pay Callback", "Successful", "");

            var refNumber = "";

            bool isEarly = false;

            if (loanId > 0)
            {
                var loan = customerContext.GetLoan(loanId);

                if (loan != null)
                {
                    refNumber = loan.RefNumber;

                    if (loan.Schedule != null)
                    {
                        List <LoanScheduleItem> scheduledPayments = loan.Schedule
                                                                    .Where(
                            x => x.Status == LoanScheduleStatus.StillToPay ||
                            x.Status == LoanScheduleStatus.Late ||
                            x.Status == LoanScheduleStatus.AlmostPaid
                            ).ToList();

                        if (scheduledPayments.Any())
                        {
                            DateTime earliestSchedule = scheduledPayments.Min(x => x.Date);

                            bool scheduleIsEarly = earliestSchedule.Date >= DateTime.UtcNow && (
                                earliestSchedule.Date.Year != DateTime.UtcNow.Year ||
                                earliestSchedule.Date.Month != DateTime.UtcNow.Month ||
                                earliestSchedule.Date.Day != DateTime.UtcNow.Day
                                );

                            if (scheduleIsEarly)
                            {
                                isEarly = true;
                            }
                        } // if
                    }     // if has schedule
                }         // if loan
            }             // if loan id

            if (string.IsNullOrEmpty(customer))
            {
                customer = customerContext.PersonalInfo.Fullname;
            }

            customerContext.TryAddPayPointCard(trans_id, card_no, expiry, customer, payPointFacade.PayPointAccount);

            var confirmation = new PaymentConfirmationModel {
                amount         = amount.Value.ToString(CultureInfo.InvariantCulture),
                saved          = res.Saved,
                savedPounds    = res.SavedPounds,
                card_no        = card_no,
                email          = customerContext.Name,
                surname        = customerContext.PersonalInfo.Surname,
                name           = customerContext.PersonalInfo.FirstName,
                refnum         = refNumber,
                transRefnums   = res.TransactionRefNumbersFormatted,
                hasLateLoans   = customerContext.HasLateLoans,
                isRolloverPaid = res.RolloverWasPaid,
                IsEarly        = isEarly
            };

            TempData.Put(confirmation);
            return(View(confirmation));
        }         // Callback
Ejemplo n.º 13
0
        public ActionResult PayPointCallback(
            bool valid,
            string trans_id,
            string code,
            string auth_code,
            decimal?amount,
            string ip,
            string test_status,
            string hash,
            string message,
            string card_no,
            string customer,
            string expiry,
            int customerId
            )
        {
            ms_oLog.Debug(
                "PayPointCallback with args:" +
                "\n\tvalid: '{0}'" +
                "\n\ttrans_id: '{1}'" +
                "\n\tcode: '{2}'" +
                "\n\tauth_code: '{3}'" +
                "\n\tamount: '{4}'" +
                "\n\tip: '{5}'" +
                "\n\ttest_status: '{6}'" +
                "\n\thash: '{7}'" +
                "\n\tmessage: '{8}'" +
                "\n\tcard_no: '{9}'" +
                "\n\tcustomer: '{10}'" +
                "\n\texpiry: '{11}'" +
                "\n\tcustomer id: '{12}'",
                valid,
                trans_id,
                code,
                auth_code,
                amount,
                ip,
                test_status,
                hash,
                message,
                card_no,
                customer,
                expiry,
                customerId
                );

            if (test_status == "true")
            {
                // Use last 4 random digits as card number (to enable useful tests)
                string random4Digits = string.Format("{0}{1}", DateTime.UtcNow.Second, DateTime.UtcNow.Millisecond);

                if (random4Digits.Length > 4)
                {
                    random4Digits = random4Digits.Substring(random4Digits.Length - 4);
                }

                card_no = random4Digits;
                expiry  = string.Format("{0}{1}", "01", DateTime.Now.AddYears(2).Year.ToString().Substring(2, 2));
            }             // if

            if (!valid || code != "A")
            {
                ms_oLog.Debug("Failed to add debit card: invalid or code ain't no 'A'.");

                TempData["code"]    = code;
                TempData["message"] = message;
                return(View(new { error = "Failed to add debit card" }));
            }             // if

            var cust = m_oContext.Customer;

            PayPointFacade payPointFacade = new PayPointFacade(cust.MinOpenLoanDate(), cust.CustomerOrigin.Name);

            if (!payPointFacade.CheckHash(hash, Request.Url))
            {
                ms_oLog.Debug("Failed to add debit card: failed to CheckHash(\n\t hash: '{0}',\n\t Url: '{1}'\n).", hash, Request.Url);

                return(View(new { error = "Failed to add debit card" }));
            }             // if

            cust.TryAddPayPointCard(
                trans_id,
                card_no,
                expiry,
                cust.PersonalInfo.Fullname,
                payPointFacade.PayPointAccount
                );

            bool hasOpenLoans = cust.Loans.Any(x => x.Status != LoanStatus.PaidOff);

            if (amount > 0 && hasOpenLoans)
            {
                Loan loan = cust.Loans.First(x => x.Status != LoanStatus.PaidOff);

                NL_Payments nlPayment = new NL_Payments()
                {
                    Amount          = amount.Value,
                    CreatedByUserID = this.m_oContext.UserId,
                    //	LoanID = nlLoanId,
                    //PaymentStatusID = (int)NLPaymentStatuses.Active,
                    PaymentSystemType = NLPaymentSystemTypes.Paypoint,
                    PaymentMethodID   = (int)NLLoanTransactionMethods.SystemRepay,
                    PaymentTime       = DateTime.UtcNow,
                    Notes             = "add payPoint card",
                    CreationTime      = DateTime.UtcNow
                };

                var f = new LoanPaymentFacade();
                f.PayLoan(loan, trans_id, amount.Value, Request.UserHostAddress, DateTime.UtcNow, "system-repay", false, null, nlPayment);
            }

            if (amount > 0 && !hasOpenLoans)
            {
                this.m_oServiceClient.Instance.PayPointAddedWithoutOpenLoan(cust.Id, cust.Id, amount.Value, trans_id);
            }
            return(View(new { success = true }));
        }         // PayPointCallback
Ejemplo n.º 14
0
        public JsonResult PayFast(string amount, string type, string paymentType, int loanId, int cardId)
        {
            try {
                decimal realAmount = decimal.Parse(amount, CultureInfo.InvariantCulture);

                var customer = this.context.Customer;

                log.Msg("Payment request for customer id {0}, amount {1}", customer.Id, realAmount);

                // TotalEarlyPayment
                realAmount = CalculateRealAmount(type, loanId, realAmount);

                if (realAmount < 0)
                {
                    return(Json(new { error = "amount is too small" }));
                }

                PayPointCard card = cardId == -1
                                        ? customer.PayPointCards.FirstOrDefault(c => c.IsDefaultCard)
                                        : customer.PayPointCards.FirstOrDefault(c => c.Id == cardId);

                if (card == null)
                {
                    throw new Exception("Card not found");
                }

                this.paypointApi.RepeatTransactionEx(card.PayPointAccount, card.TransactionId, realAmount);

                NL_Payments nlPayment = new NL_Payments()
                {
                    CreatedByUserID   = this.context.UserId,
                    Amount            = realAmount,
                    PaymentMethodID   = (int)NLLoanTransactionMethods.CustomerAuto,
                    PaymentSystemType = NLPaymentSystemTypes.Paypoint
                };

                log.Debug("PayFast: Sending nlPayment: {0} for customer {1}", nlPayment, customer.Id);

                LoanPaymentFacade loanRepaymentFacade = new LoanPaymentFacade();

                PaymentResult payFastModel = loanRepaymentFacade.MakePayment(
                    card.TransactionId,
                    realAmount,
                    null,
                    type,
                    loanId,
                    customer,
                    DateTime.UtcNow,
                    "manual payment from customer",
                    paymentType,
                    "CustomerAuto",
                    nlPayment
                    );

                payFastModel.CardNo = card.CardNo;

                SendEmails(loanId, realAmount, customer);

                this.logRepository.Log(
                    this.context.UserId,
                    DateTime.UtcNow,
                    "Paypoint Pay Early Fast Callback",
                    "Successful",
                    ""
                    );

                return(Json(payFastModel));
            } catch (PayPointException e) {
                this.logRepository.Log(
                    this.context.UserId,
                    DateTime.UtcNow,
                    "Paypoint Pay Early Fast Callback",
                    "Failed",
                    e.ToString()
                    );

                return(Json(new { error = "Error occurred while making payment" }));
            } catch (Exception e) {
                this.logRepository.Log(
                    this.context.UserId,
                    DateTime.UtcNow,
                    "Paypoint Pay Early Fast Callback",
                    "Failed",
                    e.ToString()
                    );

                return(Json(new { error = e.Message }));
            }     // try
        }         // PayFast
Ejemplo n.º 15
0
 public void SetUp()
 {
     _calculator = new LoanScheduleCalculator();
     _facade     = new LoanPaymentFacade();
 }
Ejemplo n.º 16
0
 public void SetUp()
 {
     _calculator = new LoanScheduleCalculator();
     _facade     = new LoanPaymentFacade();
     _term       = DateTime.UtcNow;
 }
Ejemplo n.º 17
0
        public void ManualPayment(ManualPaymentModel model)
        {
            var realAmount = model.TotalSumPaid;
            var customer   = this.customerRepository.Get(model.CustomerId);

            try {
                Log.InfoFormat("Manual payment request for customer id {0}, amount {1}", customer.Id, realAmount);

                if (realAmount < 0)
                {
                    throw new Exception("Amount is too small");
                }

                var date = FormattingUtils.ParseDateWithoutTime(model.PaymentDate);

                if (date > DateTime.UtcNow)
                {
                    throw new Exception("The date is more than now");
                }

                if (date < DateTime.UtcNow.AddDays(-7))
                {
                    throw new Exception("The date is less than a week ago");
                }

                string payPointTransactionId = PaypointTransaction.Manual;

                if (model.ChargeClient)
                {
                    var paypointCard = customer.PayPointCards.FirstOrDefault(x => x.IsDefaultCard);
                    if (paypointCard == null && customer.PayPointCards.Any())
                    {
                        paypointCard = customer.PayPointCards.First();
                    }

                    if (paypointCard == null)
                    {
                        throw new Exception("No Debit card found");
                    }

                    payPointTransactionId = paypointCard.TransactionId;

                    this.paypoint.RepeatTransactionEx(paypointCard.PayPointAccount, payPointTransactionId, realAmount);
                }

                string description = string.Format("UW Manual payment method: {0}, description: {2}{2}{1}", model.PaymentMethod,
                                                   model.Description, Environment.NewLine);

                string nlMethod = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(model.PaymentMethod).Replace(" ", "").Replace("-", "");
                NLLoanTransactionMethods nlPaymentMethod = (NLLoanTransactionMethods)Enum.Parse(typeof(NLLoanTransactionMethods), nlMethod);
                var nlPayment = new NL_Payments()
                {
                    CreatedByUserID   = this.context.UserId,
                    Amount            = realAmount,
                    PaymentMethodID   = (int)nlPaymentMethod,
                    PaymentSystemType = NLPaymentSystemTypes.None,
                };

                Log.InfoFormat("ManualPayment: Sending nlPayment: {0} for customer {1}", nlPayment, customer.Id);

                var facade = new LoanPaymentFacade();
                facade.MakePayment(payPointTransactionId, realAmount, null,
                                   "other", model.LoanId, customer,
                                   date, description, null, model.PaymentMethod, nlPayment);

                Log.InfoFormat("add payment to new payment table customer {0}", customer.Id);
                var loan = customer.GetLoan(model.LoanId);
                facade.Recalculate(loan, DateTime.Now);

                if (model.SendEmail)
                {
                    this.serviceClient.Instance.PayEarly(customer.Id, realAmount, customer.GetLoan(model.LoanId).RefNumber);
                }

                this.serviceClient.Instance.LoanStatusAfterPayment(
                    this.context.UserId,
                    customer.Id,
                    customer.Name,
                    model.LoanId,
                    realAmount,
                    model.SendEmail,
                    loan.Balance,
                    loan.Status == LoanStatus.PaidOff
                    );

                string requestType = string.Format("UW Manual payment for customer {0}, amount {1}",
                                                   customer.PersonalInfo.Fullname, realAmount);

                Log.InfoFormat("Successful. userID {0} at {1}. requestType: {2}", this.context.UserId, date, requestType);
            } catch (PayPointException ex) {
                Log.ErrorFormat("Paypoint Manual Payment for customer {0}, at {1} failed with error {2}", customer.Id, DateTime.UtcNow, ex);
            } catch (Exception exx) {
                Log.ErrorFormat("Paypoint Manual Payment for customer {0}, at {1} failed with error {2}", customer.Id, DateTime.UtcNow, exx);
            }
        }
Ejemplo n.º 18
0
        //-----------------------------------------------------------------------------------
        /// <summary>
        /// Make automatic payment for given installment
        /// Called from PaypointCharger job
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="loanId"></param>
        /// <param name="loanScheduleId">Installment Id</param>
        /// <param name="amount">Amount to pay</param>
        /// <returns>PayPointReturnData as a result of call to paypoint API</returns>
        public PayPointReturnData MakeAutomaticPayment(
            int customerId,
            int loanId,
            int loanScheduleId,
            decimal amount
            )
        {
            LoanScheduleRepository installments = (LoanScheduleRepository)ObjectFactory.GetInstance <ILoanScheduleRepository>();
            var loanPaymentFacade = new LoanPaymentFacade();

            PayPointReturnData payPointReturnData = null;

            installments.BeginTransaction();

            try {
                var installment = installments.Get(loanScheduleId);
                var loan        = installment.Loan;
                var customer    = loan.Customer;
                var now         = DateTime.UtcNow;

                NL_Payments nlPayment = new NL_Payments()
                {
                    Amount            = amount,
                    PaymentMethodID   = (int)NLLoanTransactionMethods.Auto,
                    PaymentStatusID   = (int)NLPaymentStatuses.Active,
                    PaymentSystemType = NLPaymentSystemTypes.Paypoint,
                    CreationTime      = now,
                    CreatedByUserID   = 1,
                    Notes             = "autocharger"
                };

                Log.InfoFormat("Making automatic repayment for customer {0}(#{1}) for amount {2} for loan# {3}({4})", customer.PersonalInfo.Fullname, customer.RefNumber, amount, loan.RefNumber, loan.Id);

                PayPointCard defaultCard = customer.PayPointCards.FirstOrDefault(x => x.IsDefaultCard);
                if (defaultCard == null && customer.PayPointCards.Any())
                {
                    defaultCard = customer.PayPointCards.First();
                }
                if (defaultCard == null)
                {
                    // ReSharper disable once ThrowingSystemException
                    throw new Exception("Debit card not found");
                }

                var payPointTransactionId = defaultCard.TransactionId;

                try {
                    payPointReturnData = RepeatTransactionEx(defaultCard.PayPointAccount, payPointTransactionId, amount);

                    // set real charged amount
                    nlPayment.Amount = amount;
                } catch (PayPointException ex) {
                    loan.Transactions.Add(new PaypointTransaction {
                        Amount                = amount,
                        Description           = ex.PaypointData.Message ?? "Exception:" + ex.Message,
                        PostDate              = now,
                        Status                = LoanTransactionStatus.Error,
                        PaypointId            = payPointTransactionId,
                        IP                    = "",
                        Balance               = loan.Balance,
                        Principal             = loan.Principal,
                        Loan                  = loan,
                        LoanTransactionMethod = ObjectFactory.GetInstance <DatabaseDataHelper>().LoanTransactionMethodRepository.FindOrDefault("Auto")
                    });

                    installments.CommitTransaction();

                    // save failed NL payment + PP transaction
                    long nlLoanId = ObjectFactory.GetInstance <IEzServiceAccessor>().GetLoanByOldID(loanId, customerId);

                    if (nlLoanId > 0)
                    {
                        nlPayment.Amount          = 0;
                        nlPayment.PaymentStatusID = (int)NLPaymentStatuses.Error;
                        nlPayment.PaypointTransactions.Clear();
                        nlPayment.PaypointTransactions.Add(new NL_PaypointTransactions()
                        {
                            TransactionTime             = now,
                            Amount                      = amount,        // in the case of Exception amount should be 0 ????
                            Notes                       = ex.PaypointData.Message ?? "Exception:" + ex.Message,
                            PaypointTransactionStatusID = (int)NLPaypointTransactionStatuses.Error,
                            IP = string.Empty,
                            PaypointUniqueID = payPointTransactionId,
                            PaypointCardID   = defaultCard.Id
                        });

                        Log.InfoFormat("Failed Paypoint transaction: customerId={0} loanID = {1}, loanScheduleId={2} amount={3}; nlPayment={4}", customerId, loanId, loanScheduleId, amount, nlPayment);

                        ObjectFactory.GetInstance <IEzServiceAccessor>().AddPayment(loan.Customer.Id, nlPayment);
                    }

                    return(ex.PaypointData);
                }
                installments.CommitTransaction();

                loanPaymentFacade.PayLoan(loan, payPointReturnData.NewTransId, amount, null, now, "auto-charge", false, null, nlPayment);
            } catch (Exception e) {
                if (!(e is PayPointException))
                {
                    Log.Error(e);
                }
                if (payPointReturnData == null)
                {
                    payPointReturnData = new PayPointReturnData {
                        Error = e.Message
                    }
                }
                ;
                installments.RollbackTransaction();
            }

            return(payPointReturnData);
        }