Example #1
0
        private OCurrency RecalculateInterestForFirstNotPaidInstallment(Installment installment, OCurrency remainingOlb, TrancheOptions to)
        {
            OCurrency newInterest = 0;

            if (installment.ExpectedDate > _previousSchedule[installment.Number - 1].ExpectedDate)
            {
                if (installment.Number == 1)
                {
                    int daysBeforeTranche = (to.TrancheDate - _currentLoan.StartDate).Days;
                    int oldQuantityOfDays =
                        (_previousSchedule[installment.Number - 1].ExpectedDate - _currentLoan.StartDate).Days;
                    newInterest = remainingOlb * _currentLoan.GivenTranches[to.Number - 1].InterestRate / oldQuantityOfDays * daysBeforeTranche
                                  + _previousSchedule[installment.Number - 1].InterestsRepayment;
                }
                else
                {
                    int daysBeforeTranche =
                        (to.TrancheDate - _previousSchedule[installment.Number - 2].ExpectedDate).Days;
                    int oldQuantityOfDays =
                        (_previousSchedule[installment.Number - 1].ExpectedDate -
                         _previousSchedule[installment.Number - 2].ExpectedDate).Days;
                    newInterest = remainingOlb * _currentLoan.GivenTranches[to.Number - 1].InterestRate / oldQuantityOfDays * daysBeforeTranche
                                  + _previousSchedule[installment.Number - 1].InterestsRepayment;
                }
            }
            else
            {
                newInterest = remainingOlb * _currentLoan.GivenTranches[to.Number - 1].InterestRate;
            }
            newInterest = RoundResult(_currentLoan.UseCents, newInterest);
            return(newInterest);
        }
        private OCurrency CalculateLateAndAnticipatedFees(DateTime pDate, int pInstallmentNumber)
        {
            OCurrency fees     = 0;
            Loan      contract = _contract.Copy();

            new Repayment.RepayLateInstallments.CalculateInstallments(_cCo, contract, _user, _generalSettings, _nWds).CalculateNewInstallmentsWithLateFees(pDate);

            for (int i = 0; i < contract.NbOfInstallments; i++)
            {
                Installment installment = contract.GetInstallment(i);
                if (!installment.IsRepaid && installment.ExpectedDate <= pDate && installment.Number != pInstallmentNumber) //late
                {
                    fees += installment.FeesUnpaid;
                    installment.PaidCapital   = installment.CapitalRepayment;
                    installment.PaidInterests = installment.InterestsRepayment;
                }
                else if (!installment.IsRepaid && installment.ExpectedDate <= pDate && installment.Number == pInstallmentNumber) //late
                {
                    fees += installment.FeesUnpaid;
                    break;
                }
                else if (!installment.IsRepaid && installment.ExpectedDate > pDate && installment.Number != pInstallmentNumber)
                {
                    if (!_cCo.KeepExpectedInstallments)
                    {
                        fees += new CalculationBaseForAnticipatedFees(_cCo, contract).CalculateFees(pDate);
                    }
                    break;
                }
            }
            return(fees);
        }
        public CMSResult Update(Installment oldInstallment)
        {
            CMSResult result = new CMSResult();

            var isExists = _repository.Project <Installment, bool>(
                installments => (from installment in installments
                                 where installment.InstallmentId != oldInstallment.InstallmentId &&
                                 installment.ReceiptBookNumber == oldInstallment.ReceiptBookNumber &&
                                 installment.ReceiptNumber == oldInstallment.ReceiptNumber
                                 select installment).Any());


            if (isExists)
            {
                result.Results.Add(new Result {
                    IsSuccessful = false, Message = string.Format("Receipt Number already exists!")
                });
            }
            else
            {
                var installment = _repository.Load <Installment>(x => x.InstallmentId == oldInstallment.InstallmentId);
                installment.Payment           = oldInstallment.Payment;
                installment.ReceiptNumber     = oldInstallment.ReceiptNumber;
                installment.ReceiptBookNumber = oldInstallment.ReceiptBookNumber;
                installment.ReceivedFee       = oldInstallment.ReceivedFee;
                _repository.Update(installment);
                result.Results.Add(new Result {
                    IsSuccessful = true, Message = string.Format("Payment updated successfully!")
                });
            }
            return(result);
        }
        public void Test_Equals_IfNumberNotEqual_ReturnsFalse()
        {
            Installment i2 = _installment.Copy();

            i2.Number = 2;
            Assert.AreEqual(_installment.Equals(i2), false);
        }
Example #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter contract data");
            Console.Write("Contract number: ");
            int contractNumber = int.Parse(Console.ReadLine());

            Console.Write("Contract Date (dd/MM/yyyy): ");
            DateTime contractDate = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy", CultureInfo.InvariantCulture);

            Console.Write("Contract Value: $ ");
            double contractValue = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);

            Contract contract = new Contract(contractNumber, contractDate, contractValue, new PayPalPayment());

            Console.Write("Enter number of installments: ");
            int numberOfInstallments = int.Parse(Console.ReadLine());

            for (int i = 0; i < numberOfInstallments; i++)
            {
                double baseInstallment = contractValue / numberOfInstallments;
                double monthlyAmount   = contract.Payment.ProcessPayment(baseInstallment, i + 1);

                DateTime dueDate = contractDate.AddMonths(i + 1);

                Installment installment = new Installment(dueDate, monthlyAmount);

                contract.Installments.Add(installment);
            }
            Console.WriteLine();
            Console.WriteLine("installments:");
            foreach (Installment i in contract.Installments)
            {
                Console.WriteLine(i);
            }
        }
        private void _CalculateInstallments(int pStartInstallment, OCurrency pStartAmount, int pNumberOfInstallmentsToPay)
        {
            OCurrency olb               = pStartAmount;
            OCurrency sumOfPrincipal    = 0;
            int       installmentNumber = 0;

            for (int number = pStartInstallment; number <= _contract.NbOfInstallments; number++)
            {
                Installment installment = _contract.GetInstallment(number - 1);
                installment.InterestsRepayment = Math.Ceiling(pStartAmount.Value * Convert.ToDecimal(_contract.InterestRate));

                if (installment.Number <= _contract.GracePeriod)
                {
                    installment.CapitalRepayment = 0;
                    installment.OLB = olb;
                }
                else
                {
                    installment.CapitalRepayment = decimal.Round((pStartAmount.Value - sumOfPrincipal.Value) / (pNumberOfInstallmentsToPay - installmentNumber), 0);
                    sumOfPrincipal += installment.CapitalRepayment;
                    installmentNumber++;
                }

                installment.OLB = olb;
                olb            -= installment.CapitalRepayment;
            }
        }
        public ActionResult Create([Bind(Include = "Id, RefundableProduct, SubNumber, DueDate, DueCapital, DueProfit, Notes")] Installment installment)
        {
            Db db = new Db(DbServices.ConnectionString);

            if (ModelState.IsValid)
            {
                try
                {
                    InstallmentServices.Insert(CurrentUser.Id, installment, db);
                    TempData["Success"] = ResourceServices.GetString(Cf.Data.Resources.ResourceBase.Culture, "UI", "InsertConfirmed");
                    return(RedirectToAction("Index"));
                }
                catch (CfException cfex)
                {
                    TempData["Failure"] = cfex.ErrorDefinition.LocalizedMessage;
                }
                catch (Exception ex)
                {
                    TempData["Failure"] = ex.Message;
                }
            }

            ViewBag.RefundableProductList = new SelectList(RefundableProductServices.List(db), "Product", "Name");
            return(View(installment));
        }
        public void Test_Equals_IfPrincipalNotEqual_ReturnsFalse()
        {
            Installment i2 = _installment.Copy();

            i2.CapitalRepayment = 2000m;
            Assert.AreEqual(_installment.Equals(i2), false);
        }
        public void Calculate(Installment installment, IScheduleConfiguration configuration)
        {
            var annuity = configuration.RoundingPolicy.Round(FindAnnuity(configuration));

            installment.InterestsRepayment = CalculateInterest(installment, configuration, installment.OLB.Value);
            installment.CapitalRepayment   = annuity - installment.InterestsRepayment;
        }
Example #10
0
        public void Test_Equals_IfDateNotEqual_ReturnsFalse()
        {
            Installment i2 = _installment.Copy();

            i2.ExpectedDate = new DateTime(2009, 7, 20);
            Assert.AreEqual(_installment.Equals(i2), false);
        }
Example #11
0
        public void Test_Equals_IfInterestNotEqual_ReturnsFalse()
        {
            Installment i2 = _installment.Copy();

            i2.InterestsRepayment = 200m;
            Assert.AreEqual(_installment.Equals(i2), false);
        }
Example #12
0
        public IActionResult Edit(Installment data)
        {
            try
            {
                var context = new RRRoadwaysDBContext();

                var dbEntry = context.Entry(data);
                dbEntry.Property("VehicleId").IsModified         = true;
                dbEntry.Property("InstallmentsMonth").IsModified = true;
                dbEntry.Property("InstallmentDate").IsModified   = true;
                dbEntry.Property("InstallmentDetail").IsModified = true;
                dbEntry.Property("Amount").IsModified            = true;

                context.SaveChanges();
                ViewBag.vehicleId = new SelectList(context.Vehicle.Where(x => x.IsDeleted == false).ToList(), "Id", "VehicleNumber");

                ViewBag.result = "Record Updated Successfully!";
            }
            catch (Exception e)
            {
                var error = e;
                ViewBag.error = e.Message;
            }
            return(RedirectToAction("Index"));
        }
Example #13
0
        private OCurrency CalculateCapitalRepayment(TrancheOptions to, Installment installment)
        {
            OCurrency result = to.TrancheAmount / to.CountOfNewInstallments + _previousSchedule[installment.Number - 1].CapitalRepayment;

            result = RoundResult(_currentLoan.UseCents, result);
            return(result);
        }
Example #14
0
        private void InitiateTransaction()
        {
            // Limpa o log:
            this.uxLog.Items.Clear();

            // Cria uma transação:
            // Tipo da transação inválido significa que o pinpad vai perguntar ao usuário o tipo da transação.
            AccountType AccountType;
            Installment installment = this.GetInstallment(out AccountType);

            // Pega o valor da transação
            decimal amount;

            decimal.TryParse(this.uxTbxTransactionAmount.Text, out amount);
            if (amount == 0)
            {
                this.Log("Valor da transaçào inválido.");
                return;
            }

            // Cria e configura a transação:
            TransactionEntry transaction = new TransactionEntry(AccountType, amount);

            transaction.Installment             = installment;
            transaction.InitiatorTransactionKey = this.uxTbxItk.Text;
            transaction.CaptureTransaction      = true;

            // Envia para o autorizador:
            IAuthorizationReport report = this.SendRequest(transaction);

            this.UpdateTransactions();
        }
Example #15
0
        /// <summary>
        /// Pega o tipo de parcelamento e o tipo de transação (débito, crédito).
        /// </summary>
        /// <param name="transactionType">Tipo da transação.</param>
        /// <returns>Opções de parcelmamento.</returns>
        private Installment GetInstallment(out AccountType accountType)
        {
            Installment installment = new Installment();

            if (this.uxCbbxTransactionType.Text == "Debito")
            {
                accountType = AccountType.Debit;

                // É débito, então não possui parcelamento:
                installment.TotalNumberOfPayments = 1;
                installment.Type = InstallmentType.None;
            }
            else if (this.uxCbbxTransactionType.Text == "Credito")
            {
                accountType = AccountType.Credit;

                // Cria o parcelamento:
                short number = 0;
                Int16.TryParse(this.uxTbxInstallmentNumber.Text, out number);
                installment.TotalNumberOfPayments = number;
                installment.Type = (this.uxOptionIssuerInstallment.IsChecked == true) ? InstallmentType.Issuer : InstallmentType.Merchant;
            }
            else
            {
                accountType = AccountType.Undefined;
            }

            return(installment);
        }
        public double Calculate(Installment model)
        {
            double total = (model.TotalValue * model.Installments);

            total += total * (percentage / 100d);
            return(total);
        }
        public void ProcessPayment(Contract contract, IOnlinePaymentService paymentService)
        {
            double baseValue = contract.TotalValue / contract.Months;


            for (int i = 1; i <= contract.Months; i++)
            {
                DateTime dueDate = contract.Date.AddMonths(i);

                double intermediateValue = baseValue + paymentService.Interest(baseValue, i);

                double FinalValue = intermediateValue + paymentService.PaymentFee(intermediateValue);

                Installment install = new Installment(dueDate, FinalValue);

                contract.addInstallments(install);
            }

            Console.WriteLine("INSTALLMENTS: ");

            foreach (Installment item in contract.list)
            {
                Console.WriteLine(item.DueDate.ToString("dd/MM/yyyy") + " - " + item.Amount);
            }
        }
Example #18
0
        public InstallmentDto MapWithAccount(Installment entity)
        {
            var dto = Map(entity);

            dto.Account = entity.Account != null ? new AccountDtoMapper().Map(entity.Account) : null;
            return(dto);
        }
        private void _CalculateDecliningFixedPrincipalWithCents(int pStartInstallment, OCurrency pStartAmount, int pNumberOfInstallmentsToPay)
        {
            OCurrency olb       = pStartAmount;
            OCurrency principal = olb.Value / pNumberOfInstallmentsToPay;

            for (int number = pStartInstallment; number <= _contract.NbOfInstallments; number++)
            {
                Installment installment = _contract.GetInstallment(number - 1);

                installment.InterestsRepayment = Math.Round(olb.Value * Convert.ToDecimal(_contract.InterestRate), 2);

                if (installment.Number <= _contract.GracePeriod)
                {
                    installment.CapitalRepayment = 0;
                    installment.OLB = olb;
                }
                else
                {
                    installment.CapitalRepayment = Math.Round(principal.Value, 2);
                }

                installment.OLB = olb;
                olb            -= installment.CapitalRepayment;
            }
        }
Example #20
0
        private static Installment GetInstallment(OpenCbsReader r)
        {
            var installment = new Installment
            {
                Number             = r.GetInt("number"),
                ExpectedDate       = r.GetDateTime("expected_date"),
                InterestsRepayment = r.GetMoney("interest_repayment"),
                CapitalRepayment   = r.GetMoney("capital_repayment"),
                PaidDate           = r.GetNullDateTime("paid_date"),
                PaidCapital        = r.GetMoney("paid_capital"),
                FeesUnpaid         = r.GetMoney("fees_unpaid"),
                PaidInterests      = r.GetMoney("paid_interest"),
                PaidFees           = r.GetMoney("paid_fees"),
                Comment            = r.GetString("comment"),
                IsPending          = r.GetBool("pending"),
                StartDate          = r.GetDateTime("start_date"),
                OLB                     = r.GetMoney("olb"),
                Commission              = r.GetMoney("commission"),
                PaidCommissions         = r.GetMoney("paid_commission"),
                LastInterestAccrualDate = r.GetDateTime("last_interest_accrual_date"),
                ExtraAmount1            = r.GetMoney("extra_amount_1"),
                ExtraAmount2            = r.GetMoney("extra_amount_2")
            };

            return(installment);
        }
        private void _CalculateDecliningFixedInstallmentsWithCents(int startInstallment, OCurrency startAmount, int numberOfInstallmentsToPay)
        {
            OCurrency olb = startAmount;
            OCurrency fixedTotalAmount = _contract.VPM(startAmount, numberOfInstallmentsToPay).Value;

            for (int number = startInstallment; number <= _contract.NbOfInstallments; number++)
            {
                Installment installment = _contract.GetInstallment(number - 1);
                OCurrency   interest    = olb.Value * Convert.ToDecimal(_contract.InterestRate);

                if (installment.PaidInterests == 0)
                {
                    installment.InterestsRepayment = Math.Round(interest.Value, 2);
                }
                else
                {
                    installment.InterestsRepayment = installment.PaidInterests;
                }

                if (installment.Number <= _contract.GracePeriod)
                {
                    installment.CapitalRepayment = 0;
                    installment.OLB = olb;
                }
                else
                {
                    installment.CapitalRepayment = Math.Round(fixedTotalAmount.Value - interest.Value, 2);
                }

                installment.OLB = olb;
                olb            -= installment.CapitalRepayment;
            }
        }
        private void _CalculateInstallments(int pStartInstallment, OCurrency pStartAmount, int pNumberOfInstallmentsToPay)
        {
            OCurrency olb               = pStartAmount;
            OCurrency sumOfPrincipal    = 0;
            int       installmentNumber = 0;

            for (int number = pStartInstallment; number <= _contract.NbOfInstallments; number++)
            {
                Installment installment = _contract.GetInstallment(number - 1);

                installment.InterestsRepayment = Math.Round(pStartAmount.Value * Convert.ToDecimal(_contract.InterestRate), 2);
                //in case TotalAnticipatedRepaymentFormerPrepaymentDayBeforeFlatCash
                if ((pStartAmount == 0) && (installment.PaidInterests != 0))
                {
                    installment.InterestsRepayment = installment.PaidInterests;
                }

                if (installment.Number <= _contract.GracePeriod)
                {
                    installment.CapitalRepayment = 0;
                    installment.OLB = olb;
                }
                else
                {
                    installment.CapitalRepayment = decimal.Round((pStartAmount.Value - sumOfPrincipal.Value) / (pNumberOfInstallmentsToPay - installmentNumber), 2);
                    sumOfPrincipal += installment.CapitalRepayment;
                    installmentNumber++;
                }

                installment.OLB = olb;
                olb            -= installment.CapitalRepayment;
            }
        }
Example #23
0
        /// <summary>
        /// Include installments according to the number set before post it all
        /// and also verify data annotations
        /// </summary>
        /// <param name="Contract model"></param>
        /// <returns> Create and post all contracts with installments
        public async Task <ActionResult <Contract> > InsertInstallments(
            [FromBody] Contract model)
        {
            var dividedAmount = model.AmountFinanced / model.NumberInstallments;

            for (var i = 1; i < model.NumberInstallments; i++)
            {
                var installment = new Installment();
                model.Installments.Add(installment);
            }
            _context.Contracts.Add(model);

            var expirationDate = model.ContractDate;

            foreach (var installmentItem in model.Installments)
            {
                expirationDate                 = expirationDate.AddDays(30);
                installmentItem.Amount         = dividedAmount;
                installmentItem.PaymentDate    = null;
                installmentItem.ExpirationDate = expirationDate;
                installmentItem.Status         = SetStatus(installmentItem);
            }
            await _context.SaveChangesAsync();

            return(model);
        }
        public void Calculate(Installment installment, IScheduleConfiguration configuration)
        {
            var number = configuration.NumberOfInstallments - configuration.GracePeriod;

            installment.CapitalRepayment   = configuration.RoundingPolicy.Round(configuration.Amount / number);
            installment.InterestsRepayment = CalculateInterest(installment, configuration, installment.OLB.Value);
        }
Example #25
0
        private void InitTotal()
        {
            decimal totalInterest      = 0,
                    totalExtra         = 0,
                    totalPrincipal     = 0,
                    totalPaidInterests = 0,
                    totalPaidExtra     = 0,
                    totalPaidCapital   = 0;

            foreach (var installment in Loan.InstallmentList)
            {
                totalInterest      += installment.InterestsRepayment.Value;
                totalExtra         += installment.Commission.Value;
                totalPrincipal     += installment.CapitalRepayment.Value;
                totalPaidCapital   += installment.PaidCapital.Value;
                totalPaidInterests += installment.PaidInterests.Value;
                totalPaidExtra     += installment.PaidCommissions.Value;
            }
            var empty = new OCurrency();
            var date  = new DateTime();

            _total = new Installment(
                date,
                totalInterest,
                totalPrincipal,
                totalPaidCapital,
                totalPaidInterests,
                empty,
                null,
                -1)
            {
                Commission = totalExtra, PaidCommissions = totalPaidExtra
            };
        }
Example #26
0
 public void Repay(Installment pInstallment, ref OCurrency pAmountPaid, ref OCurrency pFeesEvent)
 {
     //Nothing to modify
     pInstallment.PaidFees += pFeesEvent;
     pAmountPaid           -= pFeesEvent;
     pFeesEvent             = 0;
 }
Example #27
0
        private Dictionary <string, List <Installment> > GetInstallments(InstallmentRequest installmentRequest)
        {
            Dictionary <string, List <Installment> > all = new Dictionary <string, List <Installment> >();
            double totalAmount = MoneyUtils.ToDouble(installmentRequest.totalAmount);

            foreach (BinAndBank binAndBank in installmentRequest.BinAndBanks())
            {
                string             bankCode     = binAndBank.bankCode;
                int                count        = Convert.ToInt32(bankCode.Substring(3)) + 3;//+3 extension time :D
                List <Installment> installments = new List <Installment>();
                for (int i = 1; i <= count; i++)
                {
                    Installment installment = new Installment
                    {
                        numberOfInstallment = Convert.ToString(i),
                        installmentAmount   = MoneyUtils.FormatTurkishLira(totalAmount / (ulong)i),
                        totalAmount         = MoneyUtils.FormatTurkishLira(totalAmount),
                        vposConfig          = PrepareVposConfig(bankCode)
                    };
                    installments.Add(installment);
                }
                all.Add(binAndBank.bin, installments);
            }
            return(all);
        }
        /// <summary>
        /// Get installment
        /// </summary>
        /// <param name="processPaymentRequest">Process Payment Request</param>
        /// <param name="paymentCard">Payment Card</param>
        /// <param name="options">Iyzipay Options</param>
        /// <returns>installment</returns>
        private Installment GetInstallment(ProcessPaymentRequest processPaymentRequest, PaymentCard paymentCard, Armut.Iyzipay.Options options)
        {
            int.TryParse((string)processPaymentRequest.CustomValues.GetValueOrDefault(_localizationService.GetResource("Plugins.Payments.Iyzico.Installment")), out int formInstallment);

            var retrieveInstallmentInfoRequest = new RetrieveInstallmentInfoRequest()
            {
                BinNumber      = paymentCard.CardNumber.ToString(),
                Locale         = Locale.TR.ToString(),
                Price          = _priceCalculationService.RoundPrice(processPaymentRequest.OrderTotal).ToString("f8", CultureInfo.InvariantCulture),
                ConversationId = string.Empty
            };
            var installmentInfo = InstallmentInfo.Retrieve(retrieveInstallmentInfoRequest, options);

            var installment = new Installment()
            {
                InstallmentNumber = 1,
                TotalPrice        = _priceCalculationService.RoundPrice(processPaymentRequest.OrderTotal).ToString("f8", CultureInfo.InvariantCulture)
            };

            if (installmentInfo.Status == "success" && installmentInfo.InstallmentDetails.Count > 0)
            {
                var installmentDetail = installmentInfo.InstallmentDetails.FirstOrDefault().InstallmentPrices.FirstOrDefault(x => x.InstallmentNumber == formInstallment);

                installment.InstallmentNumber = installmentDetail.InstallmentNumber ?? 1;
                installment.TotalPrice        = installmentDetail.TotalPrice.Replace(".", ",");
            }

            return(installment);
        }
 private static void AssertSpecifiedInstallment(Installment pInstallment, OCurrency pInterestRepayment, OCurrency pCapitalRepayment, OCurrency pPaidCapital, OCurrency pPaidInterest)
 {
     Assert.AreEqual(pInterestRepayment.Value, pInstallment.InterestsRepayment.Value);
     Assert.AreEqual(pCapitalRepayment.Value, pInstallment.CapitalRepayment.Value);
     Assert.AreEqual(pPaidCapital.Value, pInstallment.PaidCapital.Value);
     Assert.AreEqual(pPaidInterest.Value, pInstallment.PaidInterests.Value);
 }
Example #30
0
        private string Validate(string propertyName)
        {
            // Return error message if there is error on else return empty or null string
            string validationMessage = string.Empty;

            if (_firstLoad)
            {
                return(validationMessage);
            }
            switch (propertyName)
            {
            case "Collection":
                if (!double.TryParse(Collection.ToString(), out uselessParse))
                {
                    validationMessage = "Only Digits Are Allowed";
                }
                break;

            case "Installment":
                if (!double.TryParse(Installment.ToString(), out uselessParse))
                {
                    validationMessage = "Only Digits Are Allowed";
                }
                break;

            case "ID":
                break;
            }

            return(validationMessage);
        }
Example #31
0
        public List<Installment> BuildTranche(IEnumerable<Installment> schedule, IScheduleBuilder scheduleBuilder, IScheduleConfiguration scheduleConfiguration, ITrancheConfiguration trancheConfiguration)
        {
            var rhc = (IScheduleConfiguration)scheduleConfiguration.Clone();
            rhc.Amount = trancheConfiguration.Amount;
            rhc.NumberOfInstallments = trancheConfiguration.NumberOfInstallments;
            rhc.GracePeriod = trancheConfiguration.GracePeriod;
            rhc.InterestRate = trancheConfiguration.InterestRate;
            rhc.StartDate = trancheConfiguration.StartDate;
            rhc.PreferredFirstInstallmentDate = trancheConfiguration.PreferredFirstInstallmentDate;

            var lhc = (IScheduleConfiguration)rhc.Clone();
            lhc.Amount = schedule.Sum(i => i.CapitalRepayment.Value - i.PaidCapital.Value);
            if (!trancheConfiguration.ApplyNewInterestRateToOlb)
            {
                lhc.InterestRate = scheduleConfiguration.InterestRate;
            }

            var lhs = scheduleBuilder.BuildSchedule(lhc);
            var rhs = scheduleBuilder.BuildSchedule(rhc);

            var result = new List<Installment>();

            // Merge the two schedules
            var max = Math.Max(lhs.Count, rhs.Count);
            for (var i = 0; i < max; i++)
            {
                var lhi = i >= lhs.Count ? null : lhs[i];
                var rhi = i >= rhs.Count ? null : rhs[i];

                Installment installment;

                if (lhi == null)
                {
                    installment = rhi;
                }
                else if (rhi == null)
                {
                    installment = lhi;
                }
                else
                {
                    installment = new Installment
                    {
                        Number = lhi.Number,
                        StartDate = lhi.StartDate,
                        ExpectedDate = lhi.ExpectedDate,
                        //RepaymentDate = lhi.RepaymentDate,
                        CapitalRepayment = lhi.CapitalRepayment + rhi.CapitalRepayment,
                        InterestsRepayment = lhi.InterestsRepayment + rhi.InterestsRepayment,
                        OLB = lhi.OLB + rhi.OLB,
                    };
                }
                result.Add(installment);
            }

            result[0].InterestsRepayment += GetExtraInterest(schedule, scheduleConfiguration, trancheConfiguration);
            return result;
        }
 public InstallmentDto Map(Installment entity)
 {
     return new InstallmentDto
                {
                    Id = entity.Id,
                    DueDate = entity.DueDate,
                    Amount = entity.Amount,
                    Paid = entity.Paid,
                    Status = entity.Status
                };
 }
Example #33
0
        /// <summary>
        /// Read a direct payment session request result
        /// </summary>
        /// <param name="streamReader"></param>
        /// <param name="installments"></param>
        internal static void Read(XmlReader reader, Installment installment)
        {
            if (reader.IsEmptyElement)
            {
                XMLParserUtils.SkipNode(reader);
                return;
            }

            reader.ReadStartElement(SerializerHelper.Installment);
            reader.MoveToContent();

            while (!reader.EOF)
            {
                if (XMLParserUtils.IsEndElement(reader, SerializerHelper.Installment))
                {
                    XMLParserUtils.SkipNode(reader);
                    break;
                }

                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case SerializerHelper.CreditCardBrand:
                            installment.cardBrand = reader.ReadElementContentAsString();
                            break;

                        case SerializerHelper.Quantity:
                            installment.quantity = reader.ReadElementContentAsInt();
                            break;

                        case SerializerHelper.Amount:
                            installment.amount = reader.ReadElementContentAsDecimal();
                            break;

                        case SerializerHelper.TotalAmount:
                            installment.totalAmount = reader.ReadElementContentAsDecimal();
                            break;

                        case SerializerHelper.InterestFree:
                            installment.interestFree = reader.ReadElementContentAsBoolean();
                            break;

                        default:
                            XMLParserUtils.SkipElement(reader);
                            break;
                    }
                }
                else
                {
                    XMLParserUtils.SkipNode(reader);
                }
            }
        }
Example #34
0
        public bool SetInstallmentAsPending(Installment installment, OPaymentMethods pPaymentMethod)
        {
            ClientServices clientServices = new ClientServices(_user);
            LoanServices loanServices = new LoanServices(_user);

            var client = clientServices.FindTiers(installment.ClientId, Octopus.Enums.OClientTypes.Person);
            var loan = loanServices.SelectLoan(installment.ContractId, true, true, true);

            loanServices.Repay(loan, client, installment.InstallmentNumber, installment.InstallmentDate, installment.InstallmentAmount,
                false, 0, 0, false, 0, true, pPaymentMethod, "", true);

            return true;
        }
Example #35
0
        private static Installment BuildFirst(IScheduleConfiguration configuration)
        {
            var installment = new Installment
            {
                Number = 1,
                StartDate = configuration.StartDate,
                ExpectedDate = configuration.PreferredFirstInstallmentDate,
                OLB = configuration.Amount,
                CapitalRepayment = 0m,
                InterestsRepayment =  0m,
                FeesUnpaid = 0
            };
            if (configuration.GracePeriod == 0)
            {
                configuration.CalculationPolicy.Calculate(installment, configuration);
            }

            return installment;
        }
        /// <summary>
        /// Finding total for all Annuity policy (30/360, Fact/360, Fact/Fact)
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns>total annuity</returns>
        private decimal FindAnnuity(IScheduleConfiguration configuration)
        {
            var number = configuration.NumberOfInstallments - configuration.GracePeriod;
            var numberOfPeriods = configuration.PeriodPolicy.GetNumberOfPeriodsInYear(configuration.PreferredFirstInstallmentDate, configuration.YearPolicy);
            var interestRate = (double)configuration.InterestRate / 100 / numberOfPeriods;

            // at first we are trying to calculate standard annuity for 30/360 using standard formula.
            var numerator = (decimal)interestRate * configuration.Amount;
            var denominator = 1 - 1 / Math.Pow(1 + interestRate, number);
            var annuity = numerator / (decimal)denominator;
            // In order to define the annuity amount for the other types Period and Year policy
            // we need to increase the standard annuity, build schedule according defined amount
            // and if scheduled is not balanced, repeat the procedure again
            // remainder it is surplus amount, which is left after building schedule using calculated annuity
            // remainder = remainder/numberOfInstallemnts * interestRate/100
            // left remainder // should be divided by number of installments in order to proportionally spread between installments
            // but because we need to count interest also that amount should be multiplied by interest rate / 100
            var remainder = 0m;
            var counter = 0;
            var installment = new Installment {Olb = configuration.Amount};
            do
            {
                // loop is only for building schedule and determining the remainder
                for (var i = 1; i <= configuration.NumberOfInstallments; ++i)
                {
                    installment.Number = i;
                    installment.StartDate = i != 1 ? installment.EndDate : configuration.StartDate;
                    installment.EndDate = i != 1
                        ? configuration.PeriodPolicy.GetNextDate(installment.StartDate)
                        : configuration.PreferredFirstInstallmentDate;
                    if (i <= configuration.GracePeriod) continue;
                    installment.Interest = CalculateInterest(installment, configuration, installment.Olb);
                    installment.Principal = annuity - installment.Interest;
                    installment.Olb -= installment.Principal;
                }
                remainder = installment.Olb;
                installment.Olb = configuration.Amount;
                ++counter;
                annuity += (remainder * configuration.InterestRate / 100 / number);
            } while (Math.Abs(remainder) > 0.01m && counter < 1000);
            return annuity;
        }
Example #37
0
        private static Installment BuildNext(Installment previous, IScheduleConfiguration configuration)
        {
            if (previous == null) throw new ArgumentException("Previous installment cannot be null.");

            if (previous.Number == configuration.NumberOfInstallments) return null;
            var installment = new Installment
            {
                Number = previous.Number + 1,
                StartDate = previous.ExpectedDate,
                ExpectedDate = configuration.PeriodPolicy.GetNextDate(previous.ExpectedDate),
                InterestsRepayment = 0m,
                CapitalRepayment = 0m,
                OLB = previous.OLB - previous.CapitalRepayment,
                FeesUnpaid = 0
            };
            if (configuration.GracePeriod < installment.Number)
            {
                configuration.CalculationPolicy.Calculate(installment, configuration);
            }
            return installment;
        }
Example #38
0
        /// <summary>
        /// Read a direct payment session request result
        /// </summary>
        /// <param name="streamReader"></param>
        /// <param name="installments"></param>
        internal static void Read(XmlReader reader, Installments installments)
        {
            if (reader.IsEmptyElement)
            {
                XMLParserUtils.SkipNode(reader);
                return;
            }

            reader.ReadStartElement(SerializerHelper.Installments);
            reader.MoveToContent();

            while (!reader.EOF)
            {
                if (XMLParserUtils.IsEndElement(reader, SerializerHelper.Installments))
                {
                    XMLParserUtils.SkipNode(reader);
                    break;
                }

                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case SerializerHelper.Installment:
                            Installment installment = new Installment();
                            InstallmentSerializer.Read(reader, installment);
                            installments.Add(installment);
                            break;

                        default:
                            XMLParserUtils.SkipElement(reader);
                            break;
                    }
                }
                else
                {
                    XMLParserUtils.SkipNode(reader);
                }
            }
        }
Example #39
0
 public void Add(Installment installment)
 {
     this.installments.Add(installment);
 }
 public InstallmentDto[] Map(Installment[] entities)
 {
     return entities.Select(Map).ToArray();
 }
 public InstallmentDto MapWithAccount(Installment entity)
 {
     var dto = Map(entity);
     dto.Account = entity.Account != null ? new AccountDtoMapper().Map(entity.Account) : null;
     return dto;
 }
 public InstallmentDto[] MapWithAccount(Installment[] entities)
 {
     return entities.Select(MapWithAccount).ToArray();
 }
Example #43
0
        private static decimal CalculateFirstInstallmentInterest(Installment installment,
            IScheduleConfiguration configuration)
        {
            var daysInPeriod = configuration.PeriodPolicy.GetNumberOfDays(installment, configuration.DateShiftPolicy);
            var daysInYear = configuration.YearPolicy.GetNumberOfDays(installment.ExpectedDate);
            var interest = installment.OLB * configuration.InterestRate / 100 * daysInPeriod / daysInYear;
            //if schedule is flat
            if (configuration.CalculationPolicy.GetType() == typeof(FlatInstallmentCalculationPolicy))
            {
                var numberOfPeriods =
                    (decimal)
                    (configuration.PeriodPolicy.GetNumberOfPeriodsInYear(
                        configuration.PreferredFirstInstallmentDate, configuration.YearPolicy));
                interest = configuration.Amount*configuration.InterestRate/numberOfPeriods/100;

                if (configuration.ChargeActualInterestForFirstInstallment)
                {
                    var nextDate = configuration.PeriodPolicy.GetNextDate(configuration.StartDate);
                    var numerator = (installment.ExpectedDate - configuration.StartDate).Days;
                    var denominator = (nextDate - configuration.StartDate).Days;
                    interest = interest*numerator/denominator;
                }
            }
            return configuration.RoundingPolicy.Round(interest.Value);
        }
Example #44
0
 private static decimal CalculateInterest(Installment installment, IScheduleConfiguration configuration)
 {
     var daysInPeriod = configuration.PeriodPolicy.GetNumberOfDays(installment.ExpectedDate);//, configuration.DateShiftPolicy);
     var daysInYear = configuration.YearPolicy.GetNumberOfDays(installment.ExpectedDate);
     var interest = installment.OLB*configuration.InterestRate / 100 * daysInPeriod / daysInYear;
     //if schedule is flat
     if (configuration.CalculationPolicy.GetType() == typeof(FlatInstallmentCalculationPolicy))
     {
         var numberOfPeriods =
             (decimal)
                 (configuration.PeriodPolicy.GetNumberOfPeriodsInYear(
                     configuration.PreferredFirstInstallmentDate, configuration.YearPolicy));
         interest = configuration.Amount*configuration.InterestRate/numberOfPeriods/100;
     }
     return configuration.RoundingPolicy.Round(interest.Value);
 }