public void paying_early_save_new_loan_to_history()
        {
            LoanHistory copy = null;

            _historyRepoMock.Setup(x => x.Save(It.IsAny <LoanHistory>())).Callback <LoanHistory>(lh =>
            {
                copy = lh;
            });

            _facade.MakePayment("transaction", 1000, "", "loan", _loan.Id, _customer, _startDate);

            _historyRepoMock.Verify(x => x.Save(It.IsAny <LoanHistory>()), Times.Exactly(1));

            Assert.That(copy.Balance, Is.EqualTo(_loan.Balance));
            Assert.That(copy.Interest, Is.EqualTo(_loan.Interest));
            Assert.That(copy.Principal, Is.EqualTo(_loan.Principal));
        }
        public void pay_all_loans_early2()
        {
            var date = new DateTime(2012, 1, 1);

            var loan1 = new Loan();

            _calculator.Calculate(1000, loan1, date);

            var loan2 = new Loan();

            _calculator.Calculate(3000, loan2, date);

            _customer.Loans.Add(loan1);
            _customer.Loans.Add(loan2);

            loan1.Status = LoanStatus.Live;
            loan2.Status = LoanStatus.Live;

            var amount = _customer.TotalEarlyPayment(date);

            _loanRepaymentFacade.MakePayment("transid", amount, "10:10:10:10", "total", 0, _customer, date);

            Assert.That(amount, Is.EqualTo(4000));

            Assert.That(loan1.Status, Is.EqualTo(LoanStatus.PaidOff));
            Assert.That(loan2.Status, Is.EqualTo(LoanStatus.PaidOff));

            Assert.That(loan1.Balance, Is.EqualTo(0));
            Assert.That(loan2.Balance, Is.EqualTo(0));

            Assert.That(loan1.Repayments, Is.EqualTo(1000));
            Assert.That(loan2.Repayments, Is.EqualTo(3000));

            Assert.That(loan1.TransactionsWithPaypoint.Count, Is.EqualTo(1));
            Assert.That(loan2.TransactionsWithPaypoint.Count, Is.EqualTo(1));
        }
Esempio n. 3
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
Esempio n. 4
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
Esempio n. 5
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);
            }
        }