Exemple #1
0
        public async Task ShouldInsert_LoanPymt_UsingLoanAgreementAggregate()
        {
            LoanAgreement agreement = await _loanAgreementRepo.GetByIdAsync(new Guid("0a7181c0-3ce9-4981-9559-157fd8e09cfb"));

            EconomicEvent economicEvent = new EconomicEvent(Guid.NewGuid(), EventType.CashDisbursementForLoanPayment);
            await _loanAgreementRepo.AddEconomicEventAsync(economicEvent);

            LoanPayment loanPayment = new LoanPayment
                                      (
                economicEvent,
                agreement,
                PaymentNumber.Create(1),
                PaymentDueDate.Create(new DateTime(2021, 12, 5)),
                LoanPrincipalAmount.Create(14135.13M),
                LoanInterestAmount.Create(984),
                LoanPrincipalRemaining.Create(160862.13M),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            agreement.AddLoanPayment(loanPayment);
            _loanAgreementRepo.Update(agreement);
            await _unitOfWork.Commit();

            LoanPayment result = agreement.LoanPayments.FirstOrDefault(p => p.Id == loanPayment.EconomicEvent.Id);

            Assert.NotNull(result);
        }
Exemple #2
0
        public async Task ShouldInsert_LoanAgreementAndLoanPymt_UsingLoanAgreementAggregate()
        {
            LoanAgreement agreement = new LoanAgreement
                                      (
                new EconomicEvent(Guid.NewGuid(), EventType.CashReceiptFromLoanAgreement),
                FinancierId.Create(new Guid("b49471a0-5c1e-4a4d-97e7-288fb0f6338a")),
                LoanAmount.Create(175000),
                InterestRate.Create(.0675),
                LoanDate.Create(new DateTime(2021, 11, 5)),
                MaturityDate.Create(new DateTime(2022, 11, 5)),
                PaymentsPerYear.Create(12),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            LoanPayment loanPayment = new LoanPayment
                                      (
                new EconomicEvent(Guid.NewGuid(), EventType.CashDisbursementForLoanPayment),
                agreement,
                PaymentNumber.Create(1),
                PaymentDueDate.Create(new DateTime(2021, 12, 5)),
                LoanPrincipalAmount.Create(14135),
                LoanInterestAmount.Create(984),
                LoanPrincipalRemaining.Create(160862),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            agreement.AddLoanPayment(loanPayment);
            await _loanAgreementRepo.AddAsync(agreement);

            await _unitOfWork.Commit();

            var result = await _loanAgreementRepo.Exists(agreement.Id);

            Assert.True(result);    //TODO Test navigation to LoanPayment
        }
Exemple #3
0
        public static async Task Execute
        (
            CreateLoanAgreementInfo model,
            ILoanAgreementAggregateRepository loanAgreementRepo,
            IFinancierAggregateRepository financierRepo,
            IUnitOfWork unitOfWork
        )
        {
            if (await loanAgreementRepo.Exists(model.Id))
            {
                throw new InvalidOperationException($"This loan agreement already exists!");
            }

            string    errMsg    = $"Unable to create loan agreement info, a financier with id {model.FinancierId} could not be found!";
            Financier financier = await financierRepo.GetByIdAsync(model.FinancierId) ?? throw new InvalidOperationException(errMsg);

            LoanAgreement loanAgreement = new LoanAgreement
                                          (
                new EconomicEvent(model.Id, EventType.CashReceiptFromLoanAgreement),
                FinancierId.Create(financier.Id),
                LoanAmount.Create(model.LoanAmount),
                InterestRate.Create(model.InterestRate),
                LoanDate.Create(model.LoanDate),
                MaturityDate.Create(model.MaturityDate),
                PaymentsPerYear.Create(model.PaymentsPerYear),
                model.UserId
                                          );

            await loanAgreementRepo.AddAsync(loanAgreement);

            await unitOfWork.Commit();
        }
Exemple #4
0
        public async Task ShouldUpdate_LoanAgreement_UsingFinancierRepo()
        {
            Financier financier = await _financierRepo.GetByIdAsync(new Guid("12998229-7ede-4834-825a-0c55bde75695"));

            LoanAgreement agreement = financier.LoanAgreements.FirstOrDefault(p => p.Id == new Guid("41ca2b0a-0ed5-478b-9109-5dfda5b2eba1"));


            Assert.NotNull(agreement);
        }
Exemple #5
0
        public async void ShouldDelete_LoanAgreement_UsingLoanAgreementRepo()
        {
            LoanAgreement agreement = await _loanAgreementRepo.GetByIdAsync(new Guid("0a7181c0-3ce9-4981-9559-157fd8e09cfb"));

            Assert.NotNull(agreement);

            _loanAgreementRepo.Delete(agreement);
            await _unitOfWork.Commit();

            LoanAgreement result = await _loanAgreementRepo.GetByIdAsync(new Guid("0a7181c0-3ce9-4981-9559-157fd8e09cfb"));

            Assert.Null(result);
        }
        public static async Task Execute
        (
            DeleteLoanAgreementInfo model,
            ILoanAgreementAggregateRepository loanAgreementRepo,
            IUnitOfWork unitOfWork
        )
        {
            string        errMsg        = $"Unable to delete loan agreement info, a loan agreement with LoanId '{model.Id}' could not be found!";
            LoanAgreement loanAgreement = await loanAgreementRepo.GetByIdAsync(model.Id) ?? throw new InvalidOperationException(errMsg);

            loanAgreementRepo.Delete(loanAgreement);
            await unitOfWork.Commit();
        }
Exemple #7
0
        public async Task ShouldDelete_LoanPayment_UsingLoanAgreementAggregate()
        {
            LoanAgreement agreement = await _loanAgreementRepo.GetByIdAsync(new Guid("1511c20b-6df0-4313-98a5-7c3561757dc2"));

            LoanPayment payment = agreement.LoanPayments.FirstOrDefault(p => p.Id == new Guid("409e60dc-bbe6-4ca9-95c2-ebf6886e8c4c"));

            agreement.DeleteLoanPayment(payment.Id);
            await _unitOfWork.Commit();

            LoanPayment result = agreement.LoanPayments.FirstOrDefault(p => p.Id == new Guid("409e60dc-bbe6-4ca9-95c2-ebf6886e8c4c"));

            Assert.Null(result);
        }
Exemple #8
0
        public async Task ShouldUpdate_LoanAgreement_UsingLoanAgreementRepo()
        {
            LoanAgreement agreement = await _loanAgreementRepo.GetByIdAsync(new Guid("09b53ffb-9983-4cde-b1d6-8a49e785177f"));

            agreement.UpdateInterestRate(InterestRate.Create(.0975));
            agreement.UpdateLoanAmount(LoanAmount.Create(52128M));

            await _unitOfWork.Commit();

            LoanAgreement result = await _loanAgreementRepo.GetByIdAsync(new Guid("09b53ffb-9983-4cde-b1d6-8a49e785177f"));

            Assert.Equal(.0975, result.InterestRate);
            Assert.Equal(52128M, result.LoanAmount);
        }
Exemple #9
0
        private void CreateLoanAgreement()
        {
            var agreement = new LoanAgreement
            {
                Client     = SelectedClient,
                Interest   = SelectedOffer.Interest,
                Months     = (int)MonthsInput,
                LoanAmount = (decimal)LoanAmountInput,
                Payment    = (decimal?)Payment,
            };

            ShowAddAgreementDialog(agreement);
            ResetFilters(null);
        }
        public async Task ShouldDelete_LoanAgreement_UsingDeleteLoanAgreementInfoWriteModel()
        {
            var model = new DeleteLoanAgreementInfo
            {
                Id     = new Guid("1511c20b-6df0-4313-98a5-7c3561757dc2"),
                UserId = UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
            };

            await _cmdHdlr.Handle(model);

            LoanAgreement result = await _dbContext.LoanAgreements.FindAsync(model.Id);

            Assert.Null(result);
        }
Exemple #11
0
        public async Task ShouldUpdate_LoanPayment_UsingLoanAgreementAggregate()
        {
            LoanAgreement agreement = await _loanAgreementRepo.GetByIdAsync(new Guid("1511c20b-6df0-4313-98a5-7c3561757dc2"));

            LoanPayment payment = agreement.LoanPayments.FirstOrDefault(p => p.Id == new Guid("2205ebde-58dc-4af7-958b-9124d9645b38"));

            payment.UpdatePaymentDueDate(PaymentDueDate.Create(new DateTime(2021, 1, 10)));
            payment.UpdateLoanInterestAmount(LoanInterestAmount.Create(360.07M));

            agreement.UpdateLoanPayment(payment);
            await _unitOfWork.Commit();

            LoanPayment result = agreement.LoanPayments.FirstOrDefault(p => p.Id == new Guid("2205ebde-58dc-4af7-958b-9124d9645b38"));

            Assert.Equal(new DateTime(2021, 1, 10), result.PaymentDueDate);
            Assert.Equal(360.07M, result.LoanInterestAmount);
        }
Exemple #12
0
        /// <exception cref="OverflowException">The number of elements in is larger than <see cref="F:System.Int32.MaxValue" />.</exception>
        /// <exception cref="NullReferenceException"><paramref /> is null. </exception>
        /// <exception cref="NoScheduleException">Condition. </exception>
        public void RenderAgreements(Loan loan, bool isRebuld, NL_Model nlModel = null)
        {
            var model = !isRebuld
                                ? this._builder.Build(loan.Customer, loan.LoanAmount, loan)
                                : this._builder.ReBuild(loan.Customer, loan);

            // NL - AgreementModel in json
            if (nlModel != null)
            {
                nlModel.Loan.LastHistory().AgreementModel = JsonConvert.SerializeObject(this._builder.NL_BuildAgreementModel(loan.Customer, nlModel));
            }

            var productSubTypeID = loan.CashRequest.ProductSubTypeID;
            var isRegulated      = loan.Customer.PersonalInfo.TypeOfBusiness.IsRegulated();
            var originId         = loan.Customer.CustomerOrigin.CustomerOriginID;

            LoanAgreementTemplate[] loanAgreementTemplates = this.serviceClient.Instance.GetLegalDocs(loan.Customer.Id, 1, originId, isRegulated, productSubTypeID ?? 0).LoanAgreementTemplates;
            foreach (var loanAgreementTemplate in loanAgreementTemplates)
            {
                var agreement = new LoanAgreement(loanAgreementTemplate.Name, loan, loanAgreementTemplate.Id);
                loan.Agreements.Add(agreement);
                string        path1         = Path.Combine(CurrentValues.Instance.AgreementPdfLoanPath1, agreement.FilePath);
                string        path2         = Path.Combine(CurrentValues.Instance.AgreementPdfLoanPath2, agreement.FilePath);
                TemplateModel templateModel = new TemplateModel {
                    Template = loanAgreementTemplate.Template
                };
                this.serviceClient.Instance.SaveAgreement(loan.Customer.Id, model, loan.RefNumber, Enum.GetName(typeof(LegalDocsEnums.LoanAgreementTemplateType), agreement.Id), templateModel, path1, path2);

                string nlpath1 = Path.Combine(CurrentValues.Instance.NL_AgreementPdfLoanPath1, agreement.FilePath);
                string nlpath2 = Path.Combine(CurrentValues.Instance.NL_AgreementPdfLoanPath2, agreement.FilePath);
                this.serviceClient.Instance.SaveAgreement(loan.Customer.Id, model, loan.RefNumber, Enum.GetName(typeof(LegalDocsEnums.LoanAgreementTemplateType), agreement.Id), templateModel, nlpath1, nlpath2);


                if (nlModel != null)
                {
                    nlModel.Loan.LastHistory()
                    .Agreements.Add(new NL_LoanAgreements()
                    {
                        LoanAgreementTemplateID = agreement.TemplateID,
                        FilePath = agreement.FilePath
                    });
                }
            }
            loan.AgreementModel = JsonConvert.SerializeObject(model);
        }
        public void ShouldReturn_NewLoanAgreement()
        {
            var       economicEvent = new EconomicEvent(Guid.NewGuid(), EventType.CashReceiptFromLoanAgreement);
            Financier financier     = GetFinancier();

            LoanAgreement agreement = new LoanAgreement
                                      (
                economicEvent,
                FinancierId.Create(financier.Id),
                LoanAmount.Create(10000),
                InterestRate.Create(.006),
                LoanDate.Create(new DateTime(2020, 12, 31)),
                MaturityDate.Create(new DateTime(2021, 12, 31)),
                PaymentsPerYear.Create(12),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            Assert.IsType <LoanAgreement>(agreement);
        }
Exemple #14
0
        private void ShowAddAgreementDialog(LoanAgreement agreement)
        {
            _dialogService.ShowDialog(nameof(AgreementAddingDialog),
                                      new DialogParameters
            {
                { "AgreementViewModel", new AgreementViewModel(agreement, _bankEntities) },
                { "CurrentOffer", SelectedOffer }
            },
                                      async r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    var addedAgreementVm = r.Parameters.GetValue <AgreementViewModel>("AddedAgreementViewModel");

                    SelectedClient.LoanAgreements.Add(addedAgreementVm.Entity);
                    await _bankEntities.SaveChangesAsync(CancellationToken.None);
                }
            });
        }
Exemple #15
0
        public static async Task Execute
        (
            EditLoanAgreementInfo model,
            ILoanAgreementAggregateRepository loanAgreementRepo,
            IUnitOfWork unitOfWork
        )
        {
            string        errMsg        = $"Unable to locate loan agreement with LoanId '{model.Id}'!";
            LoanAgreement loanAgreement = await loanAgreementRepo.GetByIdAsync(model.Id) ?? throw new InvalidOperationException(errMsg);

            loanAgreement.UpdateLoanAmount(LoanAmount.Create(model.LoanAmount));
            loanAgreement.UpdateInterestRate(InterestRate.Create(model.InterestRate));
            loanAgreement.UpdateLoanDate(LoanDate.Create(model.LoanDate));
            loanAgreement.UpdateMaturityDate(MaturityDate.Create(model.MaturityDate));
            loanAgreement.UpdatePaymentsPerYear(PaymentsPerYear.Create(model.PaymentsPerYear));
            loanAgreement.UpdateUserId(model.UserId);
            loanAgreement.UpdateLastModifiedDate();

            await unitOfWork.Commit();
        }
        public async Task ShouldInsert_LoanAgreement_UsingCreateLoanAgreementInfoWriteModel()
        {
            Guid id    = Guid.NewGuid();
            var  model = new CreateLoanAgreementInfo
            {
                Id              = id,
                FinancierId     = new Guid("12998229-7ede-4834-825a-0c55bde75695"),
                LoanAmount      = 10000,
                InterestRate    = .006,
                LoanDate        = new DateTime(2021, 1, 5),
                MaturityDate    = new DateTime(2022, 1, 5),
                PaymentsPerYear = 12,
                UserId          = UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
            };

            await _cmdHdlr.Handle(model);

            LoanAgreement result = await _dbContext.LoanAgreements.FindAsync(id);

            Assert.NotNull(result);
        }
Exemple #17
0
        public async Task ShouldInsert_LoanAgreement_UsingLoanAgreementRepo()
        {
            LoanAgreement agreement = new LoanAgreement
                                      (
                new EconomicEvent(Guid.NewGuid(), EventType.CashReceiptFromLoanAgreement),
                FinancierId.Create(new Guid("b49471a0-5c1e-4a4d-97e7-288fb0f6338a")),
                LoanAmount.Create(175000),
                InterestRate.Create(.0675),
                LoanDate.Create(new DateTime(2021, 11, 5)),
                MaturityDate.Create(new DateTime(2022, 11, 5)),
                PaymentsPerYear.Create(12),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            await _loanAgreementRepo.AddAsync(agreement);

            await _unitOfWork.Commit();

            var result = await _loanAgreementRepo.Exists(agreement.Id);

            Assert.True(result);
        }
        public async Task ShouldUpdate_LoanAgreement_UsingEditLoanAgreementInfoWriteModel()
        {
            var model = new EditLoanAgreementInfo
            {
                Id              = new Guid("1511c20b-6df0-4313-98a5-7c3561757dc2"),
                LoanAmount      = 70000,
                InterestRate    = .12,
                LoanDate        = new DateTime(2021, 1, 5),
                MaturityDate    = new DateTime(2023, 1, 5),
                PaymentsPerYear = 24,
                UserId          = UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
            };

            await _cmdHdlr.Handle(model);

            LoanAgreement result = await _dbContext.LoanAgreements.FindAsync(model.Id);

            Assert.Equal(model.LoanAmount, result.LoanAmount);
            Assert.Equal(model.InterestRate, result.InterestRate);
            Assert.Equal(model.PaymentsPerYear, result.PaymentsPerYear);
            Assert.Equal(model.MaturityDate, result.MaturityDate);
        }
 private string GenerateFileName(LoanAgreement agreement)
 {
     return(this.context.UserRoles.Any(r => r == "Underwriter") ? agreement.LongFilename() : agreement.ShortFilename());
 }
        public static void Approve(LoanApplication loanApplication, DateTime today, List<AmortizationScheduleModel> model, DateTime loanReleaseDate)
        {
            RoleType borrowerRoleType = RoleType.BorrowerApplicationType;
            PartyRole borrowerPartyRole = PartyRole.GetPartyRoleFromLoanApplication(loanApplication, borrowerRoleType);
            PartyRole customerPartyRole = PartyRole.GetByPartyIdAndRole(borrowerPartyRole.PartyId, RoleType.CustomerType);

            LoanApplicationStatu loanStatus = LoanApplicationStatu.CreateOrUpdateCurrent(loanApplication, LoanApplicationStatusType.ApprovedType, today);

            var agreement = Agreement.Create(loanApplication, AgreementType.LoanAgreementType, today);

            //Create new Loan Agreement Record
            LoanAgreement loanAgreement = new LoanAgreement();
            loanAgreement.Agreement = agreement;
            Context.LoanAgreements.AddObject(loanAgreement);

            var agreementItem = Create(loanApplication, agreement);
            Context.AgreementItems.AddObject(agreementItem);

            var borrower = RoleType.BorrowerAgreementType;
            var newBorrowerPartyRole = PartyRole.Create(borrower, customerPartyRole.Party, today);
            Context.PartyRoles.AddObject(newBorrowerPartyRole);

            var newBorrowerAgreementRole = CreateAgreementRole(agreement, newBorrowerPartyRole);
            Context.AgreementRoles.AddObject(newBorrowerAgreementRole);

            CreateAgreementForCoBorrowers(loanApplication, agreement, today);
            CreateAgreementForGuarantor(loanApplication, agreement, today);

            var pendingdvst = DisbursementVcrStatusEnum.PendingType;
            var disbursement = LoanDisbursementVcr.Create(loanApplication, agreement, today);
            DisbursementVcrStatu.CreateOrUpdateCurrent(disbursement, pendingdvst, today);

            AmortizationSchedule schedule = new AmortizationSchedule();
            schedule.DateGenerated = today;
            schedule.EffectiveDate = today;
            schedule.LoanReleaseDate = today;
            schedule.PaymentStartDate = model.First().ScheduledPaymentDate;
            schedule.LoanAgreement = loanAgreement;
            Context.AmortizationSchedules.AddObject(schedule);

            foreach (var models in model)
            {
                AmortizationScheduleItem item = new AmortizationScheduleItem();
                item.AmortizationSchedule = schedule;
                item.ScheduledPaymentDate = models.ScheduledPaymentDate;
                item.PrincipalPayment = models.PrincipalPayment;
                item.InterestPayment = models.InterestPayment;
                item.PrincipalBalance = models.PrincipalBalance;
                item.TotalLoanBalance = models.TotalLoanBalance;
                item.IsBilledIndicator = false;
                Context.AmortizationScheduleItems.AddObject(item);
            }
            Context.SaveChanges();
        }
        public static void Approve(LoanApplication loanApplication, DateTime today, DateTime loanReleaseDate, DateTime paymentStartDate)
        {
            RoleType borrowerRoleType = RoleType.BorrowerApplicationType;
            PartyRole borrowerPartyRole = PartyRole.GetPartyRoleFromLoanApplication(loanApplication, borrowerRoleType);
            PartyRole customerPartyRole = PartyRole.GetByPartyIdAndRole(borrowerPartyRole.PartyId, RoleType.CustomerType);

            LoanApplicationStatu loanStatus = LoanApplicationStatu.CreateOrUpdateCurrent(loanApplication, LoanApplicationStatusType.ApprovedType, today);

            var agreement = Agreement.Create(loanApplication, AgreementType.LoanAgreementType, today);

            //Create new Loan Agreement Record
            LoanAgreement loanAgreement = new LoanAgreement();
            loanAgreement.Agreement = agreement;
            Context.LoanAgreements.AddObject(loanAgreement);

            var agreementItem = Create(loanApplication, agreement);
            Context.AgreementItems.AddObject(agreementItem);

            var borrower = RoleType.BorrowerAgreementType;
            var newBorrowerPartyRole = PartyRole.Create(borrower, customerPartyRole.Party, today);
            Context.PartyRoles.AddObject(newBorrowerPartyRole);

            var newBorrowerAgreementRole = CreateAgreementRole(agreement, newBorrowerPartyRole);
            Context.AgreementRoles.AddObject(newBorrowerAgreementRole);

            CreateAgreementForCoBorrowers(loanApplication, agreement, today);
            CreateAgreementForGuarantor(loanApplication, agreement, today);

            var pendingdvst = DisbursementVcrStatusEnum.PendingType;
            var disbursement = LoanDisbursementVcr.Create(loanApplication, agreement, today);
            DisbursementVcrStatu.CreateOrUpdateCurrent(disbursement, pendingdvst, today);

            //TODO :: Generate Amortization Schedule....
            AmortizationSchedule schedule = new AmortizationSchedule();
            schedule.DateGenerated = today;
            schedule.EffectiveDate = today;
            schedule.LoanReleaseDate = today;
            schedule.PaymentStartDate = paymentStartDate;
            schedule.LoanAgreement = loanAgreement;
            Context.AmortizationSchedules.AddObject(schedule);

            LoanCalculatorOptions options = new LoanCalculatorOptions();
            var aiInterestComputationMode = ApplicationItem.GetFirstActive(loanApplication.Application, ProductFeatureCategory.InterestComputationModeType);
            options.InterestComputationMode = aiInterestComputationMode.ProductFeatureApplicability.ProductFeature.Name;
            options.LoanAmount = loanApplication.LoanAmount;
            options.LoanTerm = loanApplication.LoanTermLength;
            options.LoanTermId = loanApplication.LoanTermUomId;
            options.InterestRate = loanApplication.InterestRate ?? 0;
            options.InterestRateDescription = loanApplication.InterestRateDescription;
            options.InterestRateDescriptionId = Context.ProductFeatures.SingleOrDefault(entity => entity.Name == loanApplication.InterestRateDescription).Id;
            options.PaymentModeId = loanApplication.PaymentModeUomId;
            options.PaymentMode = UnitOfMeasure.GetByID(options.PaymentModeId).Name;
            options.PaymentStartDate = paymentStartDate;
            options.LoanReleaseDate = loanReleaseDate;

            LoanCalculator loanCalculator = new LoanCalculator();
            var models = loanCalculator.GenerateLoanAmortization(options);
            foreach (var model in models)
            {
                AmortizationScheduleItem item = new AmortizationScheduleItem();
                item.AmortizationSchedule = schedule;
                item.ScheduledPaymentDate = model.ScheduledPaymentDate;
                item.PrincipalPayment = model.PrincipalPayment;
                item.InterestPayment = model.InterestPayment;
                item.PrincipalBalance = model.PrincipalBalance;
                item.TotalLoanBalance = model.TotalLoanBalance;
                item.IsBilledIndicator = false;
                Context.AmortizationScheduleItems.AddObject(item);
            }
            Context.SaveChanges();
        }
        private AmortizationSchedule CreateAmortizationScheduleWithParent(LoanAgreement loanAgreement, AmortizationItemsModel schedule, DateTime today, AmortizationSchedule parentSchedule)
        {
            AmortizationSchedule amortizationScheduleNew1 = new AmortizationSchedule();
            amortizationScheduleNew1.LoanAgreement = loanAgreement;
            amortizationScheduleNew1.LoanReleaseDate = schedule.LoanReleaseDate;
            amortizationScheduleNew1.PaymentStartDate = schedule.PaymentStartDate;
            amortizationScheduleNew1.DateGenerated = today;
            amortizationScheduleNew1.EffectiveDate = today;
            amortizationScheduleNew1.ParentAmortizationScheduleId = parentSchedule.Id;

            return amortizationScheduleNew1;
        }
        public IHttpActionResult GenerateLoanAgreement(LoanAgreement Param)
        {
            JSON returnJSON = new JSON();

            Application app = new Application();

            //object misValue = System.Reflection.Missing.Value;

            if (!File.Exists(ServerPathTempForms() + Param.FileName + ".docx"))
            {
                File.Copy(ServerPathFormsTemplate() + "Loan Agreement.docx", ServerPathTempForms() + Param.FileName + ".docx");

                Document doc = app.Documents.Open(ServerPathTempForms() + Param.FileName + ".docx");

                string terms           = "";
                string undertakings    = "";
                string otherTerms      = "";
                string termsAndManners = "";

                //int TermAndConditionLength = Param.TermsAndConditions.Count;
                int TermAndConditionCounter    = 0;
                int SpecificUndertakingCounter = 0;
                int OtherTermCounter           = 0;
                int TermAndMannerCounter       = 0;

                foreach (TermAndCondition term in Param.TermsAndConditions)
                {
                    TermAndConditionCounter += 1;

                    terms += term.frm_textArea;

                    if (TermAndConditionCounter < Param.TermsAndConditions.Count)
                    {
                        terms += Environment.NewLine;
                    }
                }

                foreach (SpecificUndertaking undertaking in Param.SpecificUndertakings)
                {
                    SpecificUndertakingCounter += 1;

                    undertakings += undertaking.frm_textArea;

                    if (SpecificUndertakingCounter < Param.SpecificUndertakings.Count)
                    {
                        undertakings += Environment.NewLine;
                    }
                }

                foreach (OtherTermAndCondition otherTerm in Param.OtherTermsAndConditions)
                {
                    OtherTermCounter += 1;

                    otherTerms += otherTerm.frm_textArea;

                    if (OtherTermCounter < Param.OtherTermsAndConditions.Count)
                    {
                        otherTerms += Environment.NewLine;
                    }
                }

                foreach (TermAndMannerOfPayment termAndManner in Param.TermsAndMannersOfPayment)
                {
                    TermAndMannerCounter += 1;

                    termsAndManners += Environment.NewLine + termAndManner.frm_textArea;
                }

                Dictionary <string, string> bookmarks = new Dictionary <string, string> {
                    { "LoanAgreementNumberHeader", "Loan Agreement No. " + Param.LoanAgreementNumber.ToString() },
                    { "BorrowerCompanyNameHeader", Param.BorrowerCompanyName },
                    { "LoanAgreementNumber", "LOAN AGREEMENT NO. " + Param.LoanAgreementNumber.ToString() },
                    { "LLFCPresidentName", Param.LLFCPresidentFirstName + ' ' + Param.LLFCPresidentMiddleInitial + ". " + Param.LLFCPresidentLastName },
                    { "BorrowerCompanyName", Param.BorrowerCompanyName },
                    { "BorrowerCompanyAddress", Param.BorrowerCompanyAddress },
                    { "BorrowerAuthorizedSignatoryPosition", Param.BorrowerAuthorizedSignatoryPosition },
                    { "BorrowerAuthorizedSignatoryName", Param.BorrowerAuthorizedSignatoryFirstName + ' ' + Param.BorrowerAuthorizedSignatoryMiddleInitial + ". " + Param.BorrowerAuthorizedSignatoryLastName },
                    { "TypeOfFacility", Param.TypeOfFacility },
                    { "AmountInWords", "PESOS: " + NumberToText.Convert(Param.AmountInValue) + " ONLY " },
                    { "AmountInValue", "(₱ " + String.Format("{0:n}", Param.AmountInValue) + ")" },
                    { "AmountInWordsArticle1", "PESOS: " + NumberToText.Convert(Param.AmountInValue) + " ONLY " },
                    { "AmountInValueArticle1", "(₱ " + String.Format("{0:n}", Param.AmountInValue) + ")" },
                    { "PurposeOfTheLoan", Param.PurposeOfTheLoan },
                    { "LLFCPresidentPage1", Param.LLFCPresidentFirstName + ' ' + Param.LLFCPresidentMiddleInitial + ". " + Param.LLFCPresidentLastName },
                    { "LLFCPresidentPage2", Param.LLFCPresidentFirstName + ' ' + Param.LLFCPresidentMiddleInitial + ". " + Param.LLFCPresidentLastName },
                    { "LLFCPresidentPage3", Param.LLFCPresidentFirstName + ' ' + Param.LLFCPresidentMiddleInitial + ". " + Param.LLFCPresidentLastName },
                    { "LLFCPresidentPage4", Param.LLFCPresidentFirstName + ' ' + Param.LLFCPresidentMiddleInitial + ". " + Param.LLFCPresidentLastName },
                    { "LLFCPresidentPage5", Param.LLFCPresidentFirstName + ' ' + Param.LLFCPresidentMiddleInitial + ". " + Param.LLFCPresidentLastName },
                    { "LLFCPresidentPage6", Param.LLFCPresidentFirstName + ' ' + Param.LLFCPresidentMiddleInitial + ". " + Param.LLFCPresidentLastName },
                    { "AuthorizedSignatoryPage1", Param.BorrowerAuthorizedSignatoryFirstName + ' ' + Param.BorrowerAuthorizedSignatoryMiddleInitial + ". " + Param.BorrowerAuthorizedSignatoryLastName },
                    { "AuthorizedSignatoryPage2", Param.BorrowerAuthorizedSignatoryFirstName + ' ' + Param.BorrowerAuthorizedSignatoryMiddleInitial + ". " + Param.BorrowerAuthorizedSignatoryLastName },
                    { "AuthorizedSignatoryPage3", Param.BorrowerAuthorizedSignatoryFirstName + ' ' + Param.BorrowerAuthorizedSignatoryMiddleInitial + ". " + Param.BorrowerAuthorizedSignatoryLastName },
                    { "AuthorizedSignatoryPage4", Param.BorrowerAuthorizedSignatoryFirstName + ' ' + Param.BorrowerAuthorizedSignatoryMiddleInitial + ". " + Param.BorrowerAuthorizedSignatoryLastName },
                    { "AuthorizedSignatoryPage5", Param.BorrowerAuthorizedSignatoryFirstName + ' ' + Param.BorrowerAuthorizedSignatoryMiddleInitial + ". " + Param.BorrowerAuthorizedSignatoryLastName },
                    { "AuthorizedSignatoryPage6", Param.BorrowerAuthorizedSignatoryFirstName + ' ' + Param.BorrowerAuthorizedSignatoryMiddleInitial + ". " + Param.BorrowerAuthorizedSignatoryLastName },
                    { "WitnessPage1", Param.WitnessFirstName + ' ' + Param.WitnessMiddleInitial + ". " + Param.WitnessLastName },
                    { "WitnessPage2", Param.WitnessFirstName + ' ' + Param.WitnessMiddleInitial + ". " + Param.WitnessLastName },
                    { "WitnessPage3", Param.WitnessFirstName + ' ' + Param.WitnessMiddleInitial + ". " + Param.WitnessLastName },
                    { "WitnessPage4", Param.WitnessFirstName + ' ' + Param.WitnessMiddleInitial + ". " + Param.WitnessLastName },
                    { "WitnessPage5", Param.WitnessFirstName + ' ' + Param.WitnessMiddleInitial + ". " + Param.WitnessLastName },
                    { "WitnessPage6", Param.WitnessFirstName + ' ' + Param.WitnessMiddleInitial + ". " + Param.WitnessLastName },
                    { "AccountOfficerPage1", Param.AccountOfficerFirstName + ' ' + Param.AccountOfficerMiddleInitial + ". " + Param.AccountOfficerLastName },
                    { "AccountOfficerPage2", Param.AccountOfficerFirstName + ' ' + Param.AccountOfficerMiddleInitial + ". " + Param.AccountOfficerLastName },
                    { "AccountOfficerPage3", Param.AccountOfficerFirstName + ' ' + Param.AccountOfficerMiddleInitial + ". " + Param.AccountOfficerLastName },
                    { "AccountOfficerPage4", Param.AccountOfficerFirstName + ' ' + Param.AccountOfficerMiddleInitial + ". " + Param.AccountOfficerLastName },
                    { "AccountOfficerPage5", Param.AccountOfficerFirstName + ' ' + Param.AccountOfficerMiddleInitial + ". " + Param.AccountOfficerLastName },
                    { "AccountOfficerPage6", Param.AccountOfficerFirstName + ' ' + Param.AccountOfficerMiddleInitial + ". " + Param.AccountOfficerLastName },
                    { "CompanyNamePage5", Param.BorrowerCompanyName },
                    { "AuthorizedSignatoryPositionPage5", Param.BorrowerAuthorizedSignatoryPosition },
                    { "AcknowledgementAuthorizedSignatoryName", Param.BorrowerAuthorizedSignatoryFirstName + ' ' + Param.BorrowerAuthorizedSignatoryMiddleInitial + ". " + Param.BorrowerAuthorizedSignatoryLastName },
                    { "AcknowledgementAuthorizedSignatoryTINNum", Param.BorrowerAuthorizedSignatoryTINNumber },
                    { "AcknowledgementBorrowerCompanyName", Param.BorrowerCompanyName },
                    { "AcknowledgementBorrowerCompanyTINNumber", Param.BorrowerCompanyTINNumber },
                    { "LLFCPresidentAcknowledgement", Param.LLFCPresidentFirstName + ' ' + Param.LLFCPresidentMiddleInitial + ". " + Param.LLFCPresidentLastName },
                    { "LLFCPresidentTINNumAcknowledgement", Param.LLFCPresidentTINNum },
                    { "Article2Section1TermsAndCondition", terms },
                    { "Article3Section2SpecificUndertakings", undertakings },
                    { "Article8OtherTermsAndConditions", otherTerms },
                    //{ "Article3Section2SpecificUndertakings", termsAndManners },
                };

                FormToWord.ApplyDataToBookmark(bookmarks, doc);

                doc.Save();
                //doc.SaveAs2(ServerPathTempForms() + Param.FileName + ".pdf", WdSaveFormat.wdFormatPDF);
                doc.Close();

                app.Quit();

                var response = ResponseMessage(Response(Param.FileName));

                return(response);
            }
            else
            {
                returnJSON.Message = "Error";
                return(Json(returnJSON));
            }
        }