Ejemplo n.º 1
0
        /// <exception cref="NL_ExceptionInputDataInvalid">Condition. </exception>
        public void AddPayment(int customerID, NL_Payments payment, int userID)
        {
            var stra = new AddPayment(customerID, payment, userID);

            stra.Context.CustomerID = customerID;
            stra.Context.UserID     = userID;
            stra.Execute();
        }
Ejemplo n.º 2
0
        }         // CalculateSavings

        /// <summary>
        /// Оплатить все кредиты клиента.
        /// </summary>
        /// <exception cref="InvalidCastException"><paramref /> cannot be cast to the element type of the current <see cref="T:System.Array" />.</exception>
        public void PayAllLoansForCustomer(
            Customer customer,
            decimal amount,
            string transId,
            DateTime?term                   = null,
            string description              = null,
            string sManualPaymentMethod     = null,
            NL_Payments nlPaymentCommomData = null)
        {
            var date = term ?? DateTime.Now;

            var loans = customer.Loans.Where(x => x.Status != LoanStatus.PaidOff || x.Id != 0).ToList();

            var nlLoansList = serviceInstance.GetCustomerLoans(customer.Id).ToList();

            foreach (var loan in loans)
            {
                if (amount <= 0)
                {
                    break;
                }

                var money = Math.Min(amount, loan.TotalEarlyPayment(term));

                NL_Payments nlPayment = null;

                // customer's nl loans
                if (nlLoansList.Count > 0)
                {
                    // current loan
                    var nlLoan = nlLoansList.FirstOrDefault(x => x.OldLoanID == loan.Id);

                    if (nlLoan != null)
                    {
                        var nlModel = serviceInstance.GetLoanState(customer.Id, nlLoan.LoanID, DateTime.UtcNow, 1);

                        Log.InfoFormat("<<< NL_Compare Loan: {0} NLModel: {1}.\n money={2}, nlModel.TotalEarlyPayment={3} >>>", loan, nlModel, money, nlModel.TotalEarlyPayment);

                        nlPayment = new NL_Payments()
                        {
                            Amount            = money,
                            CreatedByUserID   = 1,
                            CreationTime      = DateTime.UtcNow,
                            LoanID            = nlLoan.LoanID,
                            PaymentTime       = DateTime.UtcNow,
                            Notes             = "TotalEarlyPayment",
                            PaymentStatusID   = (int)NLPaymentStatuses.Active,
                            PaymentSystemType = nlPaymentCommomData != null ? nlPaymentCommomData.PaymentSystemType : NLPaymentSystemTypes.None,
                            PaymentMethodID   = nlPaymentCommomData != null ? nlPaymentCommomData.PaymentMethodID : (int)NLLoanTransactionMethods.Manual                           // put better check
                        };
                    }
                }

                PayLoan(loan, transId, money, null, date, description, false, sManualPaymentMethod, nlPayment);

                amount = amount - money;
            }     // for
        }         // PayAllLoansForCustomer
Ejemplo n.º 3
0
        public NLLongActionResult CancelPayment(int customerID, NL_Payments payment, int userID)
        {
            CancelPayment s;
            var           amd = ExecuteSync(out s, customerID, userID, customerID, payment, userID);

            return(new NLLongActionResult {
                MetaData = amd,
                Error = s.Error
            });
        }         // AddPayment
Ejemplo n.º 4
0
        private void DecoratePayment(NL_Model nlModel)
        {
            NL_Payments nlPayments = new NL_Payments()
            {
                LoanID       = 1,
                Amount       = 333,
                CreationTime = new DateTime(2015, 2, 15),
                PaymentTime  = new DateTime(2015, 2, 15),
                PaymentID    = 1
            };

            nlModel.Loan.Payments.Add(nlPayments);
        }
Ejemplo n.º 5
0
        }         // AddLoan

        public NLLongActionResult AddPayment(int customerID, NL_Payments payment, int userID)
        {
            AddPayment s = new AddPayment(customerID, payment, userID);

            s.Context.UserID     = userID;
            s.Context.CustomerID = customerID;
            var amd = ExecuteSync(out s, customerID, userID, customerID, payment, userID);

            return(new NLLongActionResult {
                MetaData = amd,
                Value = s.PaymentID,
                Error = s.Error
            });
        }         // AddPayment
Ejemplo n.º 6
0
		private void CopyRebateTransaction() {
			if (LoanID == 0)
				return;

			MigrateLoanTransaction.LoanTransactionModel rebateTransaction = DB.FillFirst<MigrateLoanTransaction.LoanTransactionModel>(
				"select t.PostDate,t.Amount,t.Description,t.IP,t.PaypointId,c.Id as CardID from LoanTransaction t " +
				"join PayPointCard c on c.TransactionId = t.PaypointId " +
				"where Description='system-repay' " +
				"and Status='Done' " +
				"and Type ='PaypointTransaction' " +
				"and LoanId = @loanID " +
				"and DateDiff(d, t.PostDate, @dd) = 0 " +
				 "and LoanTransactionMethodId = @methodId",
				CommandSpecies.Text, new QueryParameter("@loanID", model.Loan.OldLoanID), new QueryParameter("@dd", DateTime.UtcNow.Date), new QueryParameter("@methodId", (int)NLLoanTransactionMethods.Auto)
			 );

			if (rebateTransaction == null || rebateTransaction.Amount == 0) {
				Log.Debug("rebate transaction for oldLoanID {0} not found", model.Loan.OldLoanID);
				NL_AddLog(LogType.Info, string.Format("rebate transaction for oldLoanID {0} not found", model.Loan.OldLoanID), this.strategyArgs, null, Error, null);
				return;
			}

			NL_AddLog(LogType.Info, "Addloan:rebate", new object[] { rebateTransaction }, Error, null, null);

			// call AddPayment 
			NL_Payments rebatePayment = new NL_Payments() {
				Amount = rebateTransaction.Amount,
				CreatedByUserID = 1,
				LoanID = LoanID,
				PaymentStatusID = (int)NLPaymentStatuses.Active,
				PaymentMethodID = (int)NLLoanTransactionMethods.Auto,
				CreationTime = nowTime,
				PaymentTime = nowTime.AddMilliseconds(60), // workaround: guarantee that "setup offset" payment (with PaymentTime=nowTime) will be recorded before rebate //rebateTransaction.PostDate,
				Notes = "rebate"
			};
			rebatePayment.PaypointTransactions.Add(new NL_PaypointTransactions() {
				Amount = rebateTransaction.Amount,
				IP = rebateTransaction.IP,
				Notes = rebateTransaction.Description,
				PaypointTransactionStatusID = (int)NLPaypointTransactionStatuses.Done,
				PaypointUniqueID = rebateTransaction.PaypointId,
				PaypointCardID = rebateTransaction.CardID,
				TransactionTime = rebateTransaction.PostDate
			});

			AddPayment p = new AddPayment(model.CustomerID, rebatePayment, 1);
			p.Execute();
		}
Ejemplo n.º 7
0
        // payment
        public LoanEvent(DateTime date, NL_Payments payment, int priority = 0, bool chargeBackPayment = false, bool chargeBackPaymentRecorded = false)
            : this(new DateTime(date.Year, date.Month, date.Day, 23, 59, 58), priority)
        {
            if (chargeBackPayment)
            {
                if (chargeBackPaymentRecorded)
                {
                    ChargebackPaymentRecorded = payment;
                    return;
                }
                ChargebackPaymentCancelled = payment;
                return;
            }

            Payment = payment;
        }
Ejemplo n.º 8
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.º 9
0
		public void AddPaymentTest() {
			const int customerid = 390;
			const long loanID = 15;
			/*NL_Payments nlpayment = new NL_Payments() {
				Amount = 100m,
				CreatedByUserID = 357,
				PaymentTime = new DateTime(2015, 10, 25),
				LoanID = loanID,
				Notes = "offset",
				PaymentStatusID = (int)NLPaymentStatuses.Active,
				PaymentMethodID = (int)NLLoanTransactionMethods.SetupFeeOffset
			};*/
			/*	DateTime prebatedate = DateTime.UtcNow; // new DateTime(2015, 12, 6);
				NL_Payments nlpayment = new NL_Payments() {
					Amount = 5m,
					CreatedByUserID = customerid,
					CreationTime = prebatedate,
					LoanID = loanID,
					PaymentTime = prebatedate,
					Notes = "rebate",
					PaymentStatusID = (int)NLPaymentStatuses.Active,
					PaymentMethodID = (int)NLLoanTransactionMethods.SystemRepay
				};*/
			DateTime pdate = DateTime.Now; // new DateTime(2016, 1, 7);
			NL_Payments nlpayment = new NL_Payments() {
				Amount = 50m,
				CreatedByUserID = 357,
				CreationTime = DateTime.UtcNow,
				LoanID = loanID,
				PaymentTime = pdate,
				Notes = "payment3",
				PaymentStatusID = (int)NLPaymentStatuses.Active,
				PaymentMethodID = (int)NLLoanTransactionMethods.Manual
			};
			try {
				AddPayment pstrategy = new AddPayment(customerid, nlpayment, 357);
				pstrategy.Execute();
				m_oLog.Debug(pstrategy.Error);
			} catch (Exception ex) {
				m_oLog.Debug(ex);
			}
		}
Ejemplo n.º 10
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.º 11
0
		}//Execute

		// 11. if setup fee - add payment to offset it
		private void SetupOffsetPayment() {
			if (LoanID == 0)
				return;

			var setupFee = model.Loan.Fees.FirstOrDefault(f => f.LoanFeeTypeID == (int)NLFeeTypes.SetupFee);

			Log.Debug("setup fee for offset: {0}", setupFee);

			if (setupFee != null) {
				NL_Payments setupfeeOffsetpayment = new NL_Payments {
					PaymentMethodID = (int)NLLoanTransactionMethods.SetupFeeOffset,
					Amount = setupFee.Amount,
					CreatedByUserID = 1,
					CreationTime = setupFee.CreatedTime,
					Notes = "setup fee offsetting",
					PaymentTime = nowTime.Date,
					PaymentStatusID = (int)NLPaymentStatuses.Active,
					LoanID = LoanID
				};
				AddPayment p = new AddPayment(model.CustomerID, setupfeeOffsetpayment, 1);
				p.Execute();
			}
		}
Ejemplo n.º 12
0
		public AddPayment(int customerID, NL_Payments payment, int userID) {

			this.strategyArgs = new object[] { customerID, payment, userID };

			if (customerID == 0) {
				Error = NL_ExceptionCustomerNotFound.DefaultMessage;
				NL_AddLog(LogType.Error, "Strategy Faild", this.strategyArgs, null, Error, null);
				return;
			}

			if (payment == null || payment.LoanID == 0) {
				Error = NL_ExceptionLoanNotFound.DefaultMessage;
				NL_AddLog(LogType.Error, "Strategy Faild", this.strategyArgs, null, Error, null);
				return;
			}

			CustomerID = customerID;
			Payment = payment;
			UserID = userID;

			LoanDAL = new LoanDAL();

			this.strategyArgs = new object[] { CustomerID, Payment, UserID };
		}
Ejemplo n.º 13
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.º 14
0
        }         // constructor

        /// <summary>
        /// Заплатить за кредит. Платёж может быть произвольный. Early, On time, Late.
        /// Perform loan payment. Payment can be manual. Early, On time, Late.
        /// </summary>
        public virtual decimal PayLoan(
            Loan loan,
            string transId,
            decimal amount,
            string ip,
            DateTime?term               = null,
            string description          = "payment from customer",
            bool interestOnly           = false,
            string sManualPaymentMethod = null,
            NL_Payments nlPayment       = null)
        {
            int customerID = loan.Customer.Id;

            var paymentTime = term ?? DateTime.UtcNow;

            var oldLoan = loan.Clone();

            const string Manual      = "--- manual ---";
            string       otherMethod = transId == Manual ? "Manual" : "Auto";

            var loanTransactionMethod = this.loanTransactionMethodRepository.FindOrDefault(sManualPaymentMethod, otherMethod);
            var transaction           = this.session.BeginTransaction();

            var transactionItem = new PaypointTransaction {
                Amount                = amount,
                Description           = description,
                PostDate              = paymentTime,
                Status                = LoanTransactionStatus.Done,
                PaypointId            = transId,
                IP                    = ip,
                LoanRepayment         = oldLoan.Principal - loan.Principal,
                Interest              = loan.InterestPaid - oldLoan.InterestPaid,
                InterestOnly          = interestOnly,
                LoanTransactionMethod = loanTransactionMethod
            };

            try {
                loan.AddTransaction(transactionItem);

                List <InstallmentDelta> deltas = loan.Schedule.Select(inst => new InstallmentDelta(inst))
                                                 .ToList();

                var calculator = new LoanRepaymentScheduleCalculator(loan, paymentTime, this.amountToChargeFrom);
                calculator.RecalculateSchedule();

                if (this._historyRepository != null)
                {
                    var historyRecord = new LoanHistory(loan, paymentTime);
                    this._historyRepository.SaveOrUpdate(historyRecord);
                }                 // if

                loan.UpdateStatus(paymentTime);

                if (loan.Customer != null)
                {
                    loan.Customer.UpdateCreditResultStatus();
                }
                if (loan.Id > 0)
                {
                    foreach (InstallmentDelta dlt in deltas)
                    {
                        dlt.SetEndValues();

                        if (dlt.IsZero)
                        {
                            continue;
                        }

                        loan.ScheduleTransactions.Add(new LoanScheduleTransaction {
                            Date           = DateTime.UtcNow,
                            FeesDelta      = dlt.Fees.EndValue - dlt.Fees.StartValue,
                            InterestDelta  = dlt.Interest.EndValue - dlt.Interest.StartValue,
                            Loan           = loan,
                            PrincipalDelta = dlt.Principal.EndValue - dlt.Principal.StartValue,
                            Schedule       = dlt.Installment,
                            StatusAfter    = dlt.Status.EndValue,
                            StatusBefore   = dlt.Status.StartValue,
                            Transaction    = transactionItem
                        });
                    }             // for each delta
                }                 // if


                if (nlPayment != null)
                {
                    Log.InfoFormat("PayLoan: oldLoanID: {0} customer: {1} nlpayment {2}", loan.Id, customerID, nlPayment);

                    // override those for backword compatibility
                    nlPayment.PaymentMethodID = loanTransactionMethod.Id;
                    nlPayment.Notes           = description;
                    nlPayment.CreationTime    = DateTime.UtcNow;
                    nlPayment.PaymentTime     = paymentTime;
                    nlPayment.Amount          = amount;
                    nlPayment.PaymentStatusID = (int)NLPaymentStatuses.Active;

                    Log.InfoFormat("PayLoan: overriden nlpayment {0}", nlPayment);

                    long nlLoanId = serviceInstance.GetLoanByOldID(loan.Id, customerID);

                    if (nlLoanId == 0)
                    {
                        Log.InfoFormat("Failed to find nl loan for oldLoanID {0}, customer {1}", loan.Id, customerID);
                    }
                    else
                    {
                        nlPayment.LoanID = nlLoanId;

                        // use argument's nlPayment data: CreatedByUserID

                        if (nlPayment.PaymentSystemType == NLPaymentSystemTypes.Paypoint)
                        {
                            // workaround - from MakeAutomaticPayment sent transactionid with timestamp concated

                            var card = loan.Customer.PayPointCards.FirstOrDefault(x => transId.StartsWith(x.TransactionId));

                            if (card == null)
                            {
                                Log.InfoFormat("PayPointCard for customer {0}, transId={1}, oldLoanID={2}, nl loanID={3} not found. nl payment\n {4}{5}",
                                               customerID, transId, loan.Id, nlPayment.LoanID, AStringable.PrintHeadersLine(typeof(NL_Payments)), nlPayment.ToStringAsTable());
                            }
                            else
                            {
                                nlPayment.PaypointTransactions.Clear();
                                nlPayment.PaypointTransactions.Add(new NL_PaypointTransactions()
                                {
                                    TransactionTime             = paymentTime,
                                    Amount                      = amount,
                                    Notes                       = description,
                                    PaypointTransactionStatusID = (int)NLPaypointTransactionStatuses.Done,
                                    PaypointUniqueID            = transId,
                                    PaypointCardID              = card.Id,
                                    IP = ip
                                });
                            }
                        }

                        serviceInstance.AddPayment(customerID, nlPayment, nlPayment.CreatedByUserID);
                    }
                }

                transaction.Commit();
            } catch (Exception ex) {
                Log.ErrorFormat("Failed to pay {1} pounds for loan {0}, rollbacking \n {2}", loan.Id, amount, ex);
                transaction.Rollback();
            }

            Log.InfoFormat("LinkPaymentToInvestor {0} {1} {2} {3} {4} begin", transactionItem.Id, loan.Id, loan.Customer.Id, amount, paymentTime);
            serviceInstance.LinkPaymentToInvestor(1, transactionItem.Id, loan.Id, loan.Customer.Id, amount, paymentTime);             // modified by elinar at 9/02/2016 EZ-4678 bugfix

            return(amount);
        }         // PayLoan
Ejemplo n.º 15
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.º 16
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.º 17
0
		} //Execute


		public void CopyPaypointTransactions() {

			const string query = "select t.PostDate,t.Amount,t.[Description], t.IP, t.PaypointId, t.LoanTransactionMethodId, c.Id as CardID, nl.[LoanID], l.CustomerId " +
				"from NL_Loans nl join LoanTransaction t on t.LoanId=nl.OldLoanID " +
				"join Loan l on l.Id=t.LoanId " +
				"left join PayPointCard c on c.TransactionId = t.PaypointId " +
				"left join [dbo].[NL_Payments] p on p.LoanID=nl.LoanID " +
				"where t.[Status]='Done' and t.[Type]='PaypointTransaction' and p.PaymentID is null order by t.LoanId, t.PostDate";

			List<LoanTransactionModel> transactionsList = DB.Fill<LoanTransactionModel>(query, CommandSpecies.Text);

			foreach (LoanTransactionModel transaction in transactionsList) {

				bool savePayment = false;

				var args = new object[] {transaction, query};

				if (transaction == null || transaction.Amount == 0) {
					//Error = "transaction not found/or amount=0";
					//Log.Debug(Error);
					NL_AddLog(LogType.Info, "transaction not found or amount=0", args, null, null, null);
					continue;
				}
				
				//check the payment exists
				List<NL_Payments> nlPayments = DB.Fill<NL_Payments>("NL_PaymentsGet", CommandSpecies.StoredProcedure, new QueryParameter("LoanID", transaction.LoanID));

				NL_Payments payment = nlPayments.FirstOrDefault(p => p.Amount == transaction.Amount && transaction.PostDate.Date.Equals(p.PaymentTime.Date) && transaction.LoanTransactionMethodId==p.PaymentMethodID && p.CreationTime.Date.Equals(transaction.PostDate.Date));

				if (payment == null) {
					payment = new NL_Payments() {
						Amount = transaction.Amount,
						CreatedByUserID = 1,
						LoanID = transaction.LoanID,
						PaymentStatusID = (int)NLPaymentStatuses.Active,
						PaymentMethodID = transaction.LoanTransactionMethodId,
						CreationTime = transaction.PostDate,
						PaymentTime = transaction.PostDate,
						Notes = (transaction.Description.Equals("system-repay") && transaction.Amount == 5m) ? "rebate" : transaction.Description
					};
					savePayment = true;
				} else {
					NL_AddLog(LogType.Info, "Payment exists", args, payment, null, null);
				}

				if (!string.IsNullOrEmpty(transaction.CardID.ToString())) {

					var paypointTrans = payment.PaypointTransactions.FirstOrDefault(ppt => ppt.PaypointUniqueID == transaction.PaypointId && ppt.PaypointCardID == transaction.CardID && ppt.TransactionTime.Date.Equals(transaction.PostDate.Date));

					if (paypointTrans == null) {
						payment.PaypointTransactions.Add(new NL_PaypointTransactions() {
							Amount = transaction.Amount,
							IP = transaction.IP,
							Notes = transaction.Description,
							PaypointTransactionStatusID = (int)NLPaypointTransactionStatuses.Done,
							PaypointUniqueID = transaction.PaypointId,
							PaypointCardID = transaction.CardID,
							TransactionTime = transaction.PostDate
						});
						savePayment = true;
					} else {
						NL_AddLog(LogType.Info, "PPT exists", args, paypointTrans, null, null);
					}
				}

				if (savePayment) {

					NL_AddLog(LogType.Info, "Copying transaction", args, payment, null, null);

					try {
						AddPayment p = new AddPayment(transaction.CustomerId, payment, 1);
						p.Context.UserID = 1;
						p.Context.CustomerID = transaction.CustomerId;
						p.Execute();

						// ReSharper disable once CatchAllClause
					} catch (Exception ex) {
						Error = String.Format("failed to copy paypoint transaction {0}, err: {1}", transaction, ex.Message);
						Log.Debug(Error);
						NL_AddLog(LogType.Error, "Copying failed", new object[] {
							transaction, payment
						}, Error, ex.Message, ex.StackTrace);
					}
				}
			}
		}
Ejemplo n.º 18
0
		public CancelPayment(int customerID, NL_Payments payment, int userID) {
			CustomerID = customerID;
			UserID = userID;
			Payment = payment;
			this.strategyArgs = new object[] { CustomerID, UserID, Payment };
		}
Ejemplo n.º 19
0
        }         // PayAllLoansForCustomer

        /// <exception cref="OverflowException">The sum is larger than <see cref="F:System.Decimal.MaxValue" />.</exception>
        /// <exception cref="ArgumentNullException"><paramref /> or <paramref /> is null.</exception>
        /// <exception cref="InvalidCastException"><paramref /> cannot be cast to the element type of the current <see cref="T:System.Array" />.</exception>
        public void PayAllLateLoansForCustomer(
            Customer customer,
            decimal amount,
            string transId,
            DateTime?term                   = null,
            string description              = null,
            string sManualPaymentMethod     = null,
            NL_Payments nlPaymentCommomData = null)
        {
            DateTime date = term ?? DateTime.Now;

            IEnumerable <Loan> loans = customer.ActiveLoans.Where(l => l.Status == LoanStatus.Late);

            var nlLoansList = serviceInstance.GetCustomerLoans(customer.Id).ToList();

            if (nlLoansList.Count > 0)
            {
                nlLoansList.ForEach(l => Log.InfoFormat("PayAllLateLoansForCustomer NLLoanID={0}", l.LoanID));
            }

            foreach (var loan in loans)
            {
                if (amount <= 0)
                {
                    break;
                }

                LoanRepaymentScheduleCalculator c = new LoanRepaymentScheduleCalculator(loan, term, this.amountToChargeFrom);
                LoanScheduleItem state            = c.GetState();

                decimal late = loan.Schedule.Where(s => s.Status == LoanScheduleStatus.Late).Sum(s => s.LoanRepayment) + state.Interest + state.Fees + state.LateCharges;

                decimal money = Math.Min(amount, late);

                NL_Payments nlPayment = null;

                // customer's nl loans
                if (nlLoansList.Count > 0)
                {
                    // current loan
                    var nlLoan = nlLoansList.FirstOrDefault(x => x.OldLoanID == loan.Id);

                    if (nlLoan != null)
                    {
                        var nlModel = serviceInstance.GetLoanState(loan.Customer.Id, nlLoan.LoanID, DateTime.UtcNow, 1);

                        decimal nlLate = nlModel.Interest + nlModel.Fees;
                        nlModel.Loan.Histories.ForEach(h => h.Schedule.Where(s => s.LoanScheduleStatusID == (int)NLScheduleStatuses.Late).Sum(s => nlLate += s.Principal));
                        decimal nlMoney = Math.Min(amount, nlLate);

                        Log.InfoFormat("<<< NL_Compare: Loan:{0} NLModel:{1}.\n late={2}, nlLate={3}, amount={4}, money={5}, nlMoney={6} >>>", loan, nlModel, late, nlLate, amount, money, nlMoney);

                        nlPayment = new NL_Payments()
                        {
                            Amount          = money,
                            CreatedByUserID = 1,
                            CreationTime    = DateTime.UtcNow,
                            LoanID          = nlLoan.LoanID,
                            PaymentTime     = DateTime.UtcNow,
                            Notes           = "PayAllLateLoansForCustomer",
                            //PaymentMethodID = (int)NLLoanTransactionMethods.CustomerAuto,
                            PaymentStatusID   = (int)NLPaymentStatuses.Active,
                            PaymentSystemType = nlPaymentCommomData != null ? nlPaymentCommomData.PaymentSystemType : NLPaymentSystemTypes.None,
                            PaymentMethodID   = nlPaymentCommomData != null ? nlPaymentCommomData.PaymentMethodID : (int)NLLoanTransactionMethods.Manual                           // put better check
                        };
                    }
                }

                PayLoan(loan, transId, money, null, date, description, false, sManualPaymentMethod, nlPayment);

                amount = amount - money;
            }     // for
        }         // PayAllLateLoansForCustomer
Ejemplo n.º 20
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.º 21
0
        }         // PayAllLateLoansForCustomer

        /// <summary>
        /// Main method for making payments
        /// </summary>
        /// <param name="transId">pay point transaction id</param>
        /// <param name="amount"></param>
        /// <param name="ip"></param>
        /// <param name="type"></param>
        /// <param name="loanId"></param>
        /// <param name="customer"></param>
        /// <param name="date">payment date</param>
        /// <param name="description"></param>
        /// <param name="paymentType">If payment type is null - ordinary payment(reduces principal),
        /// if nextInterest then it is for Interest Only loans, and reduces interest in the future.</param>
        /// <param name="sManualPaymentMethod"></param>
        /// <param name="nlPayment"></param>
        /// <returns></returns>
        /// <exception cref="OverflowException">The sum is larger than <see cref="F:System.Decimal.MaxValue" />.</exception>
        /// <exception cref="InvalidCastException"><paramref /> cannot be cast to the element type of the current <see cref="T:System.Array" />.</exception>
        public PaymentResult MakePayment(
            string transId,
            decimal amount,
            string ip,
            string type,
            int loanId,
            Customer customer,
            DateTime?date               = null,
            string description          = "payment from customer",
            string paymentType          = null,
            string sManualPaymentMethod = null,
            NL_Payments nlPayment       = null)
        {
            Log.DebugFormat(
                "MakePayment transId: {0}, amount: {1}, ip: {2}, type: {3}, loanId: {4}, customer: {5}," +
                "date: {6}, description: {7}, paymentType: {8}, manualPaymentMethod: {9}, nlPayment: {10}",
                transId,
                amount,
                ip,
                type,
                loanId,
                customer.Id,
                date,
                description,
                paymentType,
                sManualPaymentMethod,
                nlPayment
                );

            decimal oldInterest;
            decimal newInterest;
            bool    rolloverWasPaid = false;

            description = string.Format("{0} {1} {2}", description, type, paymentType);

            SortedSet <int> openLoansBefore = new SortedSet <int>(
                customer.Loans.Where(l => l.Status != LoanStatus.PaidOff).Select(l => l.Id)
                );

            if (type == "total")
            {
                oldInterest = customer.Loans.Sum(l => l.Interest);

                rolloverWasPaid = (
                    from l in customer.Loans
                    from s in l.Schedule
                    from r in s.Rollovers
                    where r.Status == RolloverStatus.New
                    select r
                    ).Any();

                PayAllLoansForCustomer(
                    customer,
                    amount,
                    transId,
                    date,
                    description,
                    sManualPaymentMethod
                    , nlPayment
                    );

                newInterest = customer.Loans.Sum(l => l.Interest);
            }
            else if (type == "totalLate")
            {
                rolloverWasPaid = (
                    from l in customer.Loans
                    from s in l.Schedule
                    from r in s.Rollovers
                    where r.Status == RolloverStatus.New
                    select r
                    ).Any();

                oldInterest = customer.Loans.Sum(l => l.Interest);

                PayAllLateLoansForCustomer(
                    customer,
                    amount,
                    transId,
                    date,
                    description,
                    sManualPaymentMethod
                    );

                newInterest = customer.Loans.Sum(l => l.Interest);
            }
            else if (paymentType == "nextInterest")
            {
                oldInterest = 0;
                var loan = customer.GetLoan(loanId);

                if (nlPayment != null)
                {
                    var nlLoanId = serviceInstance.GetLoanByOldID(loanId, customer.Id);
                    if (nlLoanId > 0)
                    {
                        nlPayment.Amount          = amount;
                        nlPayment.CreationTime    = DateTime.UtcNow;
                        nlPayment.LoanID          = nlLoanId;
                        nlPayment.PaymentTime     = DateTime.UtcNow;
                        nlPayment.Notes           = description;
                        nlPayment.PaymentStatusID = (int)NLPaymentStatuses.Active;
                        //CreatedByUserID = userId,
                        //PaymentMethodID = (int)NLLoanTransactionMethods.CustomerAuto,
                        //PaymentSystemType = (transId == PaypointTransaction.Manual ? NLPaymentSystemTypes.None : NLPaymentSystemTypes.Paypoint)
                    }
                }

                PayLoan(loan, transId, amount, ip, date, description, true, sManualPaymentMethod, nlPayment);
                newInterest = 0;
            }
            else
            {
                Loan loan = customer.GetLoan(loanId);

                oldInterest = loan.Interest;

                var rollover = (
                    from s in loan.Schedule
                    from r in s.Rollovers
                    where r.Status == RolloverStatus.New
                    select r
                    ).FirstOrDefault();

                long nlLoanId = 0;
                if (nlPayment != null)
                {
                    nlLoanId = serviceInstance.GetLoanByOldID(loanId, customer.Id);
                    if (nlLoanId > 0)
                    {
                        nlPayment.Amount             = amount;
                        nlPayment.CreationTime       = DateTime.UtcNow;
                        nlPayment.LoanID             = nlLoanId;
                        nlPayment.PaymentTime        = DateTime.UtcNow;
                        nlPayment.Notes              = description;
                        nlPayment.PaymentStatusID    = (int)NLPaymentStatuses.Active;
                        nlPayment.PaymentDestination = rollover != null?NLPaymentDestinations.Rollover.ToString() : null;

                        //CreatedByUserID = userId,
                        //PaymentMethodID = (int)NLLoanTransactionMethods.CustomerAuto,
                        //PaymentSystemType = (transId == PaypointTransaction.Manual ? NLPaymentSystemTypes.None : NLPaymentSystemTypes.Paypoint)
                    }
                }

                PayLoan(loan, transId, amount, ip, date, description, false, sManualPaymentMethod, nlPayment);

                newInterest = loan.Interest;

                rolloverWasPaid = rollover != null && rollover.Status == RolloverStatus.Paid;

                if (rolloverWasPaid && nlLoanId > 0)
                {
                    serviceInstance.AcceptRollover(customer.Id, nlLoanId);
                }
            }             // if

            SortedSet <int> openLoansAfter = new SortedSet <int>(
                customer.Loans.Where(l => l.Status != LoanStatus.PaidOff).Select(l => l.Id)
                );

            var loansClosedNow = new SortedSet <int>(openLoansBefore.Except(openLoansAfter));

            decimal savedSetupFee  = 0;
            string  setupFeeCharge = new ConfigurationVariable(CurrentValues.Instance.SpreadSetupFeeCharge).Name;

            customer.Loans.Where(l => loansClosedNow.Contains(l.Id)).ForEach(l => l.Charges
                                                                             .Where(c => (c.ChargesType.Name == setupFeeCharge) && (c.State == "Active"))
                                                                             .ForEach(c => savedSetupFee += c.Amount - c.AmountPaid)
                                                                             );

            var savedPounds = oldInterest - newInterest + savedSetupFee;

            var transactionRefNumbers =
                from l in customer.Loans
                from t in l.TransactionsWithPaypoint
                where t.Id == 0
                select t.RefNumber;

            var payFastModel = new PaymentResult {
                PaymentAmount         = amount,
                Saved                 = oldInterest + savedSetupFee > 0 ? Math.Round(savedPounds / (oldInterest + savedSetupFee) * 100) : 0,
                SavedPounds           = savedPounds,
                TransactionRefNumbers = transactionRefNumbers.ToList(),
                RolloverWasPaid       = rolloverWasPaid
            };

            customer.TotalPrincipalRepaid = customer.Loans
                                            .SelectMany(l => l.Transactions)
                                            .OfType <PaypointTransaction>()
                                            .Where(l => l.Status != LoanTransactionStatus.Error)
                                            .Sum(l => l.LoanRepayment);

            return(payFastModel);
        }         // MakePayment
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
0
 public void AddPayment(int customerID, NL_Payments payment, int userID)
 {
     this.m_oServiceClient.Instance.AddPayment(customerID, payment, userID);
 }