Esempio n. 1
0
 public void Create(LoanApplication application)
 {
     using (var db = new BankingSitedDb())
     {
         db.LoanApplications.Add(application);
         db.SaveChanges();
     }            
 }
Esempio n. 2
0
        public void ShouldPopulateIdOnCreateLoanApplication()
        {
            var sut = new Repository();

            var applicationToSave = new LoanApplication
            {
                FirstName    = "Gentry",
                LastName     = "Smith",
                Age          = 33,
                AnnualIncome = 12345.67m
            };

            sut.Create(applicationToSave);

            Assert.That(applicationToSave.ID, Is.Not.EqualTo(0));
        }
Esempio n. 3
0
        public ActionResult WorkContactInformation(LoanApplication application)
        {
            LoanApplication existingApplication = Session["Loan_Application"] as LoanApplication;

            if (existingApplication != null)
            {
                existingApplication.JobTitle       = application.JobTitle;
                existingApplication.WorkAddress    = application.WorkAddress;
                existingApplication.WorkCity       = application.WorkCity;
                existingApplication.WorkState      = application.WorkState;
                existingApplication.WorkPostalCode = application.WorkPostalCode;
                existingApplication.WorkPhone      = application.WorkPhone;
            }

            return(RedirectToAction("FinancialInformation"));
        }
        public void ShouldDeclineWhenNotTooYoungAndWealthyButPoorCredit_Classical()
        {
            var sut = new LoanApplicationScorer(new CreditHistoryChecker());

            var application = new LoanApplication
            {
                FirstName    = "Sarah",
                LastName     = "Smith",
                AnnualIncome = 1000000.01m,
                Age          = 22
            };

            sut.ScoreApplication(application);

            Assert.That(application.IsAccepted, Is.False);
        }
        public IHttpActionResult PostLoanRequests([FromBody] LoanApplication loanApplication)
        {
            // if(!ModelState.IsValid)
            if (string.IsNullOrWhiteSpace(loanApplication.FullName))
            {
                return(StatusCode(HttpStatusCode.BadRequest));
            }
            else
            {
                var result = services.SaveLoanRequest(loanApplication);

                string responseTime = DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss tt");

                return(result == "Success" ? Ok($"S-100-M {responseTime}") : Ok($"R-500-M {responseTime}. Something went wrong."));
            }
        }
        public ActionResult FinancialInformation(LoanApplication application)
        {
            LoanApplication existingApplication = Session["Loan_Application"] as LoanApplication;

            if (existingApplication != null)
            {
                existingApplication.NetWorth        = application.NetWorth;
                existingApplication.Reference1Name  = application.Reference1Name;
                existingApplication.Reference1Phone = application.Reference1Phone;
            }

            Session["Loan_Application"] = existingApplication;


            return(RedirectToAction("Review"));
        }
        public void ShouldRenderAcceptedMessage()
        {
            var sut = new Views.LoanApplicationSearch.ApplicationStatus();

            var model = new LoanApplication
            {
                IsAccepted = true
            };

            HtmlDocument html = sut.RenderAsHtml(model);

            var isAcceptedMessageRendered = html.GetElementbyId("acceptedMessage") != null;
            var isDeclinedMessageRendered = html.GetElementbyId("declinedMessage") != null;

            Assert.That(isAcceptedMessageRendered, Is.True);
            Assert.That(isDeclinedMessageRendered, Is.False);
        }
        public static LoanApplication ToEntity(this LoanApplicationDTO dto)
        {
            if (dto is null)
            {
                return(null);
            }

            var entity = new LoanApplication
            {
                Id                = dto.Id,
                Amount            = dto.LoanAmount,
                ApplicationStatus = (ApplicationStatus)Enum.Parse(typeof(ApplicationStatus), dto.ApplicationStatusName),
                EmailId           = dto.EmailId,
            };

            return(entity);
        }
Esempio n. 9
0
        public ActionResult PersonalContactInformation(LoanApplication application)
        {
            LoanApplication existingApplication = Session["Loan_Application"] as LoanApplication;

            if (existingApplication != null)
            {
                existingApplication.HomeAddress    = application.HomeAddress;
                existingApplication.HomeCity       = application.HomeCity;
                existingApplication.HomeState      = application.HomeState;
                existingApplication.HomePostalCode = application.HomePostalCode;
                existingApplication.HomePhone      = application.HomePhone;
            }

            Session["Loan_Application"] = existingApplication;

            return(RedirectToAction("WorkContactInformation"));
        }
        public LoanApplicationResult ProcessLoan(LoanApplication application)
        {
            // Check for loan qualification
            var failingRule = _loanApprovalRules.FirstOrDefault(rule => rule.CheckLoanApprovalRule(application) == false);

            if (failingRule != null)
            {
                var result = LoanApplicationResult.CreateDeniedResult(application, failingRule.RuleName);
                return(result);
            }

            // Applicant qualifies for the loan, so figure out the interest rate we can offer and the monthly payment
            double interestRate   = DetermineInterestRate(application);
            double monthlyPayment = CalculateLoanPayment(application.LoanAmount, application.Term.Years, interestRate);

            return(LoanApplicationResult.CreateApprovedResult(application, interestRate, monthlyPayment));
        }
Esempio n. 11
0
        /// <summary>
        /// Deletes the object.
        /// </summary>
        public virtual void Delete(LoanApplication deleteObject)
        {
            // create a new instance of the connection
            SqlConnection cnn = new SqlConnection(LoanApplication.GetConnectionString());
            // create local variable array for the sql parameters
            SqlParameterHash sqlparams = null;


            try
            {
                // discover the parameters
                sqlparams = SqlHelperParameterCache.GetSpParameterSet(LoanApplication.GetConnectionString(), "gsp_DeleteLoanApplication");


                // Store the parameter for the Id attribute.
                sqlparams["@id"].Value = deleteObject.Id;


                using (cnn)
                {
                    // open the connection
                    cnn.Open();


                    // Execute the stored proc to perform the delete on the instance.
                    SqlHelper.ExecuteNonQuery(cnn, CommandType.StoredProcedure, "gsp_DeleteLoanApplication", sqlparams);


                    // close the connection after usage
                    cnn.Close();
                }


                // nullify the connection var
                cnn = null;
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }


            // nullify the reference
            deleteObject = null;
        }
Esempio n. 12
0
        public async Task <bool> ApproveAsync(LoanApplication loanApplication, CancellationToken cancellationToken)
        {
            var existingApplication = await this.context.LoanApplications.SingleOrDefaultAsync(a => a.Id.Equals(loanApplication.Id), cancellationToken);

            if (existingApplication != null)
            {
                existingApplication.ApplicationStatusId = -2;

                this.context.LoanApplications.Update(existingApplication);
                await this.context.SaveChangesAsync(cancellationToken);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 13
0
        public void ScoreApplication(LoanApplication application)
        {
            var isBasicCriteriaMet = ValidateBasicCriteria(application);

            if (isBasicCriteriaMet)
            {
                var isCreditHistoryGood =
                    _creditHistoryChecker.CheckCreditHistory(
                        application.FirstName,
                        application.LastName);

                application.IsAccepted = isCreditHistoryGood;
            }
            else
            {
                application.IsAccepted = false;
            }
        }
        public ActionResult Create(LoanApplication loanapplication)
        {
            if (ModelState.IsValid)
            {
                db.LoanApplications.Add(loanapplication);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.BranchId                = new SelectList(db.Branches, "BranchId", "BranchCode", loanapplication.BranchId);
            ViewBag.ClientId                = new SelectList(db.Clients, "ClientId", "ClientName", loanapplication.ClientId);
            ViewBag.FreequencyId            = new SelectList(db.Freequencies, "FreequencyId", "Freequency1", loanapplication.FreequencyId);
            ViewBag.InterestModelId         = new SelectList(db.InterestModels, "InterestModelId", "interestModel1", loanapplication.InterestModelId);
            ViewBag.LoanApplicationStatusId = new SelectList(db.LoanApplicationStatus, "LoanApplicationStatusId", "LoanApplicationStatus", loanapplication.LoanApplicationStatusId);
            ViewBag.UserId = new SelectList(db.Users, "Id", "UserName", loanapplication.UserId);
            ViewBag.LaonApplicationCode = GetLoanAppCode();
            return(View(loanapplication));
        }
        private void SubmitForApproval(LoanApplication loanApplication)
        {
            //check use case: Submit Loan Application Directly for Approval : to know if selected loan application
            //can be submitted directly for approval :)

            //end current status of loan application
            var activeLoanApplication = LoanApplicationStatu.GetActive(loanApplication);
            activeLoanApplication.TransitionDateTime = DateTime.Now;
            activeLoanApplication.IsActive = false;

            //change status to pending: approval
            var approvedLoanAppStatusId = LoanApplicationStatusType.GetByName(LoanApplicationStatusType.PendingApprovalType);
            LoanApplicationStatu loanApplicationStatus = new LoanApplicationStatu();
            loanApplicationStatus.StatusTypeId = approvedLoanAppStatusId.Id;
            loanApplicationStatus.ApplicationId = loanApplication.ApplicationId;
            loanApplicationStatus.TransitionDateTime = DateTime.Now;
            loanApplicationStatus.IsActive = true;
        }
        public void MapApplication_StateUnderTest_ExpectedBehavior()
        {
            var             mapper      = this.CreateMapper();
            LoanApplication application = new LoanApplication {
                ApprovalDenialComformation = true,
                LoanAmount  = 1,
                CreditScore = 1,
                EstIncome   = 1,
                Id          = 1,
                Ssn         = "1",
                User        = null,
                UserId      = 1
            };
            var result = Mapper.MapApplication(
                application);

            Assert.True(true);
        }
Esempio n. 17
0
        public void ScoreApplication(LoanApplication application)
        {
            var isBasicCriteriaMet = ValidateBasicCriteria(application);

            if (isBasicCriteriaMet)
            {
                var isCreditHistoryGood = 
                    _creditHistoryChecker.CheckCreditHistory(
                                            application.FirstName,
                                            application.LastName);

                application.IsAccepted = isCreditHistoryGood;
            }
            else
            {
                application.IsAccepted = false;
            }
        }
Esempio n. 18
0
        public async Task <ActionResult <Schedule> > GetPaybackSchedule([FromQuery] LoanApplication data, string loanType)
        {
            if (data == null | data.Amount == 0 | data.AnnualInterest == 0 | data.DurationInMonths == 0 | data.PayoffsPerYear == 0)
            {
                return(BadRequest());
            }

            var offers = await _loanRepo.GetOffers();

            if (!offers.Any(offer => offer.SearchString == loanType))
            {
                return(NotFound());
            }

            var scheduleData = _paybackSchedule.CreateSchedule(data);

            return(Ok(scheduleData));
        }
Esempio n. 19
0
        public ActionResult Start(LoanApplication application)
        {
            // setup for test of temp data
            // view contents
            //string session_controller = Session["sessionName1"] as string;
            //string viewbag_controller = ViewBag.viewbagName1 as string;
            //string viewdata_controller = ViewData["viewdataName1"] as string;
            //string tempdata_controller = TempData["tempdataName1"] as string;

            //string session_view = Session["sessionName2"] as string;
            //string viewbag_view = ViewBag.viewbagName2 as string;
            //string viewdata_view = ViewData["viewdataName2"] as string;
            //string tempdata_view = TempData["tempdataName2"] as string;

            Session["Loan_Application"] = application;

            return(RedirectToAction("PersonalContactInformation"));
        }
Esempio n. 20
0
        public ActionResult Index(LoanCalculatorModel loanCalculatorModel, string btnToApplication)
        {
            if (btnToApplication != null && btnToApplication == "To Application")
            {
                if (ModelState.IsValid)
                {
                    var loanApplication = new LoanApplication
                    {
                        LoanAmount = loanCalculatorModel.LoanAmount,
                        Term       = loanCalculatorModel.Term,
                        TariffId   = loanCalculatorModel.TariffId
                    };
                    if (_cellPhone != null)
                    {
                        loanApplication.CellPhone = _cellPhone;
                    }

                    TempData.Add("loanApplication", loanApplication);
                    return(RedirectToAction((User.IsInRole("Consultant") ? "Fill" : "Create"), "LoanApplication"));
                }
            }

            var tariffs = Service.GetTariffs().Where(t => t.IsActive).ToList();

            ViewBag.TariffId = new SelectList(tariffs, "Id", "Name");
            var tariff = tariffs.FirstOrDefault(t => t.Id == loanCalculatorModel.TariffId);

            if (ModelState.IsValid)
            {
                try
                {
                    var paymentSchedule =
                        PaymentScheduleCalculator.Calculate(loanCalculatorModel.LoanAmount, tariff,
                                                            loanCalculatorModel.Term);
                    loanCalculatorModel.Payments = paymentSchedule.Payments;
                }
                catch (ArgumentException e)
                {
                    ModelState.AddModelError("TariffId", e.Message);
                    return(View(loanCalculatorModel));
                }
            }
            return(View(loanCalculatorModel));
        }
        //
        // GET: /LoanApplication/Edit/5

        public ActionResult Edit(int id = 0)
        {
            LoanApplication loanapplication = db.LoanApplications.Find(id);

            if (loanapplication == null)
            {
                return(HttpNotFound());
            }
            ViewBag.BranchId                = new SelectList(db.Branches, "BranchId", "BranchCode", loanapplication.BranchId);
            ViewBag.ClientId                = new SelectList(db.Clients, "ClientId", "ClientName", loanapplication.ClientId);
            ViewBag.FreequencyId            = new SelectList(db.Freequencies, "FreequencyId", "Freequency1", loanapplication.FreequencyId);
            ViewBag.InterestModelId         = new SelectList(db.InterestModels, "InterestModelId", "interestModel1", loanapplication.InterestModelId);
            ViewBag.LoanApplicationStatusId = new SelectList(db.LoanApplicationStatus, "LoanApplicationStatusId", "LoanApplicationStatus", loanapplication.LoanApplicationStatusId);
            ViewBag.UserId              = new SelectList(db.Users, "Id", "UserName", loanapplication.UserId);
            ViewBag.EMIStartDate        = loanapplication.EMIStartDate.Value;
            ViewBag.LoanApplicationDate = loanapplication.LoanApplicationDate.Value;

            return(View(loanapplication));
        }
Esempio n. 22
0
        public ActionResult Create([Bind(Include = "AppliedAmount,ApplicationDate,Product,TermsQty")] LoanApplication loanApplication)
        {
            if (ModelState.IsValid)
            {
                loanApplication.MemberCode         = Global.Cifkey;
                loanApplication.LoanAmount         = Convert.ToDecimal(0.00);
                loanApplication.IsAddRequirement   = false;
                loanApplication.IsAgreeToCondition = false;
                loanApplication.IsChangeLoanAmount = false;
                loanApplication.IsChangeTerm       = false;
                loanApplication.ApplicationDate    = DateTime.Now;
                db.LoanApplications.Add(loanApplication);
                db.SaveChanges();
                //TempData["LANo"] = loanApplication.LAno;
                return(RedirectToAction("Verify", new { id = loanApplication.LAno }));
            }

            return(View(loanApplication));
        }
        public void ShouldDeclineWhenNotTooYoungAndWealthyButPoorCredit()
        {
            var fakeCreditHistoryChecker = new Mock <ICreditHistoryChecker>();

            fakeCreditHistoryChecker.Setup(x => x.CheckCreditHistory(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(false);

            var sut = new LoanApplicationScorer(fakeCreditHistoryChecker.Object);

            var application = new LoanApplication
            {
                AnnualIncome = 1000000.01m,
                Age          = 22
            };

            sut.ScoreApplication(application);

            Assert.That(application.IsAccepted, Is.False);
        }
Esempio n. 24
0
        public async void Can_check_identity(string applicantName, IdentityCheckResult expectedResult)
        {
            // Arrange

            var loanApplication = new LoanApplication
            {
                ApplicantName = applicantName
            };

            var sut = new IdentityService();

            // Act

            var actualResult = await sut.CheckIdentity(loanApplication);

            // Assert

            Assert.Equal(expectedResult, actualResult);
        }
Esempio n. 25
0
        /// <summary>
        /// Fills a single instance with data based on its primary key values.
        /// </summary>
        public virtual void Fill(LoanApplication loanapplication, System.Int64 id)
        {
            // create the connection to use
            SqlConnection cnn = new SqlConnection(LoanApplication.GetConnectionString());

            try
            {
                // discover the sql parameters
                SqlParameterHash sqlparams = SqlHelperParameterCache.GetSpParameterSet(LoanApplication.GetConnectionString(), "gsp_SelectLoanApplication");


                using (cnn)
                {
                    // open the connection
                    cnn.Open();


                    // set the parameters
                    sqlparams["@id"].Value = id;


                    // create an instance of the reader to fill.
                    SqlDataReader datareader = SqlHelper.ExecuteReader(cnn, "gsp_SelectLoanApplication", sqlparams);


                    if (datareader.Read())
                    {
                        loanapplication.SetMembers(ref datareader);
                    }


                    cnn.Close();                     // close the connection
                }


                // nullify the connection var
                cnn = null;
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }
        }
Esempio n. 26
0
 public HttpResponseMessage Put(string id, [FromBody] LoanApplication loanApplication)
 {
     if (ModelState.IsValid)
     {
         bool success = _repository.editLoanApplication(id, loanApplication);
         if (success)
         {
             return(new HttpResponseMessage()
             {
                 StatusCode = HttpStatusCode.OK
             });
         }
     }
     return(new HttpResponseMessage()
     {
         StatusCode = HttpStatusCode.NotFound,
         Content = new StringContent("Kunne ikke endre kunden i DB")
     });
 }
Esempio n. 27
0
        public void Can_verify_eligibility(bool isEmployed, bool expectedEligibility)
        {
            // Arrange

            var loanApplication = new LoanApplication
            {
                IsEmployed = isEmployed
            };

            var sut = new EligibilityVerifier();

            // Act

            var isEligible = sut.IsEligible(loanApplication);

            // Assert

            Assert.Equal(expectedEligibility, isEligible);
        }
Esempio n. 28
0
        private bool ValidateBasicCriteria(LoanApplication application)
        {
            // Basic simulated business rules

            // If applicant earns over a million dollars then
            // other criteria don't matter
            if (application.AnnualIncome > 1000000)
            {
                return(true);
            }

            // Don't lend to younger applicants
            if (application.Age <= 21)
            {
                return(false);
            }

            return(true);
        }
        public void ShouldDeclineWhenTooYoung()
        {
            var fakeCreditHistoryChecker = new Mock <ICreditHistoryChecker>();

            fakeCreditHistoryChecker.Setup(
                x => x.CheckCreditHistory(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(true);

            var sut = new LoanApplicationScorer(fakeCreditHistoryChecker.Object);

            var application = new LoanApplication
            {
                Age = 21
            };

            sut.ScoreApplication(application);

            Assert.That(application.IsAccepted, Is.False);
        }
Esempio n. 30
0
        public ActionResult Fill(LoanApplication loanApplication)
        {
            var tariffs = Service.GetTariffs().Where(t => t.IsActive);

            ViewBag.Tariff = new SelectList(tariffs, "Id", "Name");
            var tariffGuarantor = tariffs.Select(t => new { Id = t.Id, isGuarantorNeeded = t.IsGuarantorNeeded });

            ViewBag.tariffGuarantor = tariffGuarantor;
            if (ModelState.IsValidField("CellPhone"))
            {
                // connect to db to refresh connection
                // saving of loanApplication doesn't save docs
                var dbApp = Service.GetLoanApplications().FirstOrDefault(l => l.Id.Equals(loanApplication.Id));
                return(dbApp != null
                    ? FillExistingLoanApplication(loanApplication, tariffs, dbApp)
                    : FillNewLoanApplication(loanApplication));
            }
            return(View(loanApplication));
        }
Esempio n. 31
0
        private bool ValidateBasicCriteria(LoanApplication application)
        {
            // Basic simulated business rules

            // If applicant earns over a million dollars then 
            // other criteria don't matter
            if (application.AnnualIncome > 1000000)
            {
                return true;
            }

            // Don't lend to younger applicants
            if (application.Age <= 21)
            {
                return false;
            }

            return true;
        }
Esempio n. 32
0
        public IActionResult ApplyForLoan()
        {
            var user = RepositoryWrapper.UserRepository.FindByCondition(s => s.Email == this.User.Identity.Name).FirstOrDefault();

            if (!user.completed2)
            {
                return(RedirectToAction("Loans", "Client"));
            }
            else if (!user.completed3)
            {
                return(Redirect("/Client/Terms"));
            }
            else
            {
                LoanApplication loanApplication = new LoanApplication();
                loanApplication.estPayDate = loanApplication.applicationDate = DateTime.Now.AddDays(29);
                return(View(loanApplication));
            }
        }
Esempio n. 33
0
 public bool editLoanApplication(string birthNo, LoanApplication application)
 {
     using (var db = new BankContext())
     {
         // Find LoanAppication:
         LoanApplication app = db.LoanApplications.FirstOrDefault(x => x.BirthNo == birthNo);
         application.ID = app.ID;
         try
         {
             db.LoanApplications.AddOrUpdate(application);
             db.SaveChanges();
             return(true);
         }
         catch (Exception e)
         {
             Debug.Write(e.Message);
             return(false);
         }
     }
 }
        public void ShouldAcceptWhenYoungButWealthy()
        {
            var fakeCreditHistoryChecker = new Mock <ICreditHistoryChecker>();

            fakeCreditHistoryChecker.Setup(
                x => x.CheckCreditHistory(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(true);

            var sut = new LoanApplicationScorer(fakeCreditHistoryChecker.Object);

            var application = new LoanApplication
            {
                AnnualIncome = 1000000.01m,
                Age          = 21
            };

            sut.ScoreApplication(application);

            Assert.That(application.IsAccepted, Is.True);
        }
        public static void Reject(LoanApplication loanApplication, DateTime today, int processedByPartyId)
        {
            if (LoanApplicationStatu.CanChangeStatusTo(loanApplication, LoanApplicationStatusType.RejectedType))
            {
                var newStatus = LoanApplicationStatu.ChangeStatus(loanApplication, LoanApplicationStatusType.RejectedType, today);

                //Insert loan clerk who processed the application
                if (RoleType.ProcessedByApplicationType.PartyRoleType != null)
                {
                    var party = Party.GetById(processedByPartyId);
                    PartyRole processedBy = PartyRole.CreateAndUpdateCurrentLoanApplicationRole
                        (loanApplication, party, RoleType.ProcessedByApplicationType, today);
                }

                RoleType borrowerRoleType = RoleType.BorrowerApplicationType;
                PartyRole borrowerPartyRole = PartyRole.GetPartyRoleFromLoanApplication(loanApplication, borrowerRoleType);
                PartyRole customerPartyRole = PartyRole.GetByPartyIdAndRole(borrowerPartyRole.PartyId, RoleType.CustomerType);
                var customerStatus = customerPartyRole.Customer.CurrentStatus;
                //if customer status is active
                if (customerStatus.CustomerStatusType == CustomerStatusType.ActiveType)
                {
                    if ((CheckIfHasNoOutstandingLoans(borrowerRoleType, customerPartyRole)) && (CheckIfHasNoLoanApplications(loanApplication, borrowerRoleType, customerPartyRole.Party)))
                        CustomerStatu.ChangeStatus(customerPartyRole, CustomerStatusType.InactiveType, today); //change customer status
                    //else do not update customer status
                }
                //else: do not update customer status

                //Cancel Cheques associated and receipts
                var remarks = "Loan Application was rejected.";
                var assoc = Context.ChequeApplicationAssocs.Where(entity => entity.ApplicationId == loanApplication.ApplicationId);
                foreach (var item in assoc)
                {
                    //TODO:: Changed to new payment.
                    var cheque = Cheque.GetById(item.ChequeId);
                    var rpAssoc = Context.ReceiptPaymentAssocs.SingleOrDefault(entity => entity.PaymentId == cheque.PaymentId);
                    var receipt = rpAssoc.Receipt;

                    ChequeStatu.ChangeStatus(cheque, ChequeStatusType.CancelledType, remarks);
                    ReceiptStatu.ChangeStatus(receipt, ReceiptStatusType.CancelledReceiptStatusType, remarks);
                }
            }
        }
        public static AgreementItem Create(LoanApplication loanApplication, Agreement agreement)
        {
            AgreementItem agreementItem = new AgreementItem();
            agreementItem.Agreement = agreement;
            agreementItem.LoanAmount = loanApplication.LoanAmount;

            if (loanApplication.IsInterestProductFeatureInd)
            {
                agreementItem.InterestRate = loanApplication.InterestRate ?? 0;
                agreementItem.InterestRateDescription = loanApplication.InterestRateDescription;
            }

            if (loanApplication.IsPastDueProductFeatureInd)
            {
                agreementItem.PastDueInterestRateDescript = loanApplication.PastDueInterestDescription;
                agreementItem.PastDueInterestRate = loanApplication.PastDueInterestRate;
            }

            //descriptive values
            var uom = Context.UnitOfMeasures.SingleOrDefault(entity =>
                entity.Id == loanApplication.LoanTermUomId);
            var payment = Context.LoanApplications.FirstOrDefault(entity =>
                entity.UnitOfMeasure.Id == loanApplication.PaymentModeUomId);
            var featureAppMode = ProductFeatureApplicability.RetrieveFeature(ProductFeatureCategory.InterestComputationModeType, loanApplication);
            var fetaureAppMethod = ProductFeatureApplicability.RetrieveFeature(ProductFeatureCategory.MethodofChargingInterestType, loanApplication);

            agreementItem.LoanTermLength = loanApplication.LoanTermLength;
            agreementItem.LoanTermUom = uom.Name;
            agreementItem.PaymentMode = payment.UnitOfMeasure.Name;
            agreementItem.InterestComputationMode = featureAppMode.ProductFeature.Name;
            agreementItem.MethodOfChargingInterest = fetaureAppMethod.ProductFeature.Name;

            return agreementItem;
        }
 public static void Close(LoanApplication loanApplication, DateTime today, int processedByPartyId)
 {
     LoanApplicationStatu.ChangeStatus(loanApplication, LoanApplicationStatusType.ClosedType, today);
     //Insert loan clerk who processed the application
     if (RoleType.ProcessedByApplicationType.PartyRoleType != null)
     {
         var party = Party.GetById(processedByPartyId);
         PartyRole processedBy = PartyRole.CreateAndUpdateCurrentLoanApplicationRole
             (loanApplication, party, RoleType.ProcessedByApplicationType, today);
     }
 }
        public override void PrepareForSave(LoanApplication loanApplication, PartyRole customerPartyRole, DateTime today)
        {
            //throw new NotImplementedException();
            if (this.IsNew)
            {
                var asset = AddAsset(loanApplication, today);

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Add(asset, today);
                }

                Land land = new Land();
                land.Asset = asset;
                land.UomId = this.LandUOM;
                land.LandTypeId = this.LandType;
                land.OctTctNumber = this.TCTNumber;
                land.LandArea = this.LandArea;

                //add property location
                var borrowerParty = Context.Parties.SingleOrDefault(entity => entity.Id == customerPartyRole.PartyId);
                var propertyLocation = PostalAddress.CreatePostalAddress(borrowerParty, PostalAddressType.PropertyLocationType, today);
                propertyLocation.StreetAddress = this.StreetAddress;
                propertyLocation.Barangay = this.Barangay;
                propertyLocation.Municipality = this.Municipality;
                propertyLocation.CountryId = this.CountryId;
                propertyLocation.City = this.City;
                propertyLocation.Province = this.Province;
                propertyLocation.PostalCode = this.PostalCode;
                propertyLocation.Address.Asset = asset;
            }
            else if (this.ToBeDeleted)
            {
                Asset asset = Context.Assets.SingleOrDefault(entity => entity.Id == this.AssetId);
                RemoveCurrentMortgagee(asset, today);

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Remove(today);
                }

                var borrowerParty = Context.Parties.SingleOrDefault(entity => entity.Id == customerPartyRole.PartyId);
                var propertyLocation = PostalAddress.GetCurrentPostalAddress(borrowerParty, PostalAddressType.PropertyLocationType, asset);

                if (asset.Land != null)
                {
                    Address address = propertyLocation.Address;
                    Context.Lands.DeleteObject(asset.Land);
                    Context.PostalAddresses.DeleteObject(propertyLocation);
                    Context.Addresses.DeleteObject(address);
                }

                Context.Assets.DeleteObject(asset);
            }
            else if (this.IsEdited)
            {
                Asset asset = Context.Assets.SingleOrDefault(entity => entity.Id == this.AssetId);
                UpdateAsset(asset, today);

                Land land = asset.Land;
                land.UomId = this.LandUOM;
                land.LandTypeId = this.LandType;
                land.OctTctNumber = this.TCTNumber;
                land.LandArea = this.LandArea;

                //add property location
                var borrowerParty = Context.Parties.SingleOrDefault(entity => entity.Id == customerPartyRole.PartyId);
                var currentPropertyLocation = PostalAddress.GetCurrentPostalAddress(borrowerParty, PostalAddressType.PropertyLocationType, asset);
                var propertyLocation = new PostalAddress();
                propertyLocation.StreetAddress = this.StreetAddress;
                propertyLocation.Barangay = this.Barangay;
                propertyLocation.Municipality = this.Municipality;
                propertyLocation.CountryId = this.CountryId;
                propertyLocation.City = this.City;
                propertyLocation.Province = this.Province;
                propertyLocation.PostalCode = this.PostalCode;

                PostalAddress.CreateOrUpdatePostalAddress(currentPropertyLocation, propertyLocation, today);

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Save(asset, today);
                }
            }else if(this.IsNew == false && this.ToBeDeleted == false && this.IsEdited == false)
            {
                if (this.AssetId == 0)
                {
                    var asset = AddAsset(loanApplication, today);

                    foreach (PropertyOwner owner in PropertyOwners)
                    {
                        owner.Add(asset, today);
                    }

                    Land land = new Land();
                    land.Asset = asset;
                    land.UomId = this.LandUOM;
                    land.LandTypeId = this.LandType;
                    land.OctTctNumber = this.TCTNumber;
                    land.LandArea = this.LandArea;

                    //add property location
                    var borrowerParty = Context.Parties.SingleOrDefault(entity => entity.Id == customerPartyRole.PartyId);
                    //var currentPropertyLocation = PostalAddress.GetCurrentPostalAddress(borrowerParty, PostalAddressType.PropertyLocationType, asset);
                    var propertyLocation = PostalAddress.CreatePostalAddress(borrowerParty, PostalAddressType.PropertyLocationType, today);
                    propertyLocation.StreetAddress = this.StreetAddress;
                    propertyLocation.Barangay = this.Barangay;
                    propertyLocation.Municipality = this.Municipality;
                    propertyLocation.CountryId = this.CountryId;
                    propertyLocation.City = this.City;
                    propertyLocation.Province = this.Province;
                    propertyLocation.PostalCode = this.PostalCode;
                    propertyLocation.Address.Asset = asset;
                }
            }
        }
        private LoanApplication CreateLoanApplication(Application application, DateTime today, AmortizationItemsModel itemModel)
        {
            LoanApplication loanApplicationNew1 = new LoanApplication();
            loanApplicationNew1.Application = application;
            loanApplicationNew1.InterestRate = itemModel.InterestRate;
            loanApplicationNew1.LoanTermUomId = itemModel.UnitId;
            loanApplicationNew1.LoanTermLength = itemModel.Term;
            loanApplicationNew1.PaymentModeUomId = itemModel.PaymentModeId;
            loanApplicationNew1.LoanAmount = itemModel.NewLoanAmount;
            loanApplicationNew1.InterestRateDescription = itemModel.InterestRateDescription;
            loanApplicationNew1.IsInterestProductFeatureInd = true;

            return loanApplicationNew1;
        }
        public override void PrepareForSave(LoanApplication loanApplication, PartyRole customerPartyRole, DateTime today)
        {
            //throw new NotImplementedException();
            if (this.IsNew)
            {
                var asset = AddAsset(loanApplication, today);
                asset.Description = this.Description;
                asset.AcquisitionCost = this.AcquisitionCost;

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Add(asset, today);
                }

            }
            else if (this.ToBeDeleted)
            {
                Asset asset = Context.Assets.SingleOrDefault(entity => entity.Id == this.AssetId);
                RemoveCurrentMortgagee(asset, today);

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Remove(today);
                }

                var borrowerParty = Context.Parties.SingleOrDefault(entity => entity.Id == customerPartyRole.PartyId);

                if (asset.Vehicle != null)
                {
                    Context.Vehicles.DeleteObject(asset.Vehicle);
                }

                Context.Assets.DeleteObject(asset);
            }
            else if (this.IsEdited)
            {
                Asset asset = Context.Assets.SingleOrDefault(entity => entity.Id == this.AssetId);
                UpdateAsset(asset, today);

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Save(asset, today);
                }
            }
            else if (this.IsNew == false && this.IsEdited == false && this.ToBeDeleted == false)
            {
                if (this.AssetId == 0)
                {
                    var asset = AddAsset(loanApplication, today);
                    asset.Description = this.Description;
                    asset.AcquisitionCost = this.AcquisitionCost;

                    foreach (PropertyOwner owner in PropertyOwners)
                    {
                        owner.Add(asset, today);
                    }
                }
            }
        }
        public void PrepareForSave(LoanApplication loanApplication, DateTime today)
        {
            if (this.IsNew)
            {
                SubmittedDocument submittedDocument = new SubmittedDocument();
                submittedDocument.ProductRequiredDocumentId = this.ProductRequiredDocumentId;
                submittedDocument.ApplicationId = loanApplication.ApplicationId;
                submittedDocument.DateSubmitted = this.DateSubmitted;
                submittedDocument.Description = this.DocumentDescription;

                SaveDocumentPage(submittedDocument);

                SubmittedDocumentStatu documentStatus = new SubmittedDocumentStatu();
                var statusType = Context.SubmittedDocumentStatusTypes.SingleOrDefault(entity => entity.Name == "Approved");
                documentStatus.StatusTypeId = statusType.Id;
                documentStatus.SubmittedDocument = submittedDocument;
                documentStatus.TransitionDateTime = today;
                documentStatus.IsActive = true;

                Context.SubmittedDocuments.AddObject(submittedDocument);
                Context.SubmittedDocumentStatus.AddObject(documentStatus);
            }
            else if (this.ToBeDeleted)
            {
                SubmittedDocument submittedDocument = Context.SubmittedDocuments.SingleOrDefault(entity => entity.Id == this.SubmittedDocumentId);
                foreach (var status in submittedDocument.SubmittedDocumentStatus.ToList())
                {
                    Context.SubmittedDocumentStatus.DeleteObject(status);
                }
                foreach (var documentPage in submittedDocument.DocumentPages.ToList())
                {
                    Context.DocumentPages.DeleteObject(documentPage);
                }

                Context.SubmittedDocuments.DeleteObject(submittedDocument);
            }else if(this.IsNew == false && this.ToBeDeleted == false)
            {
                SubmittedDocument submittedDocument = new SubmittedDocument();
                submittedDocument.ProductRequiredDocumentId = this.ProductRequiredDocumentId;
                submittedDocument.LoanApplication = loanApplication;
                submittedDocument.DateSubmitted = this.DateSubmitted;
                submittedDocument.Description = this.DocumentDescription;

                SaveDocumentPage(submittedDocument);

                SubmittedDocumentStatu documentStatus = new SubmittedDocumentStatu();
                var statusType = Context.SubmittedDocumentStatusTypes.SingleOrDefault(entity => entity.Name == "Approved");
                documentStatus.StatusTypeId = statusType.Id;
                documentStatus.SubmittedDocument = submittedDocument;
                documentStatus.TransitionDateTime = today;
                documentStatus.IsActive = true;

                Context.SubmittedDocuments.AddObject(submittedDocument);
                Context.SubmittedDocumentStatus.AddObject(documentStatus);
            }
        }
        public Asset AddAsset(LoanApplication loanApplication, DateTime today)
        {
            Asset asset = new Asset();
            asset.AssetTypeId = this.AssetTypeId;
            asset.LoanApplication = loanApplication;
            asset.Description = Description;
            asset.IsMortgaged = this.IsPropertyMortgage;
            asset.AcquisitionCost = this.AcquisitionCost;
            Context.Assets.AddObject(asset);
            CreateMortgagee(asset, today);

            return asset;
        }
 public abstract void PrepareForSave(LoanApplication loanApplication, PartyRole customerPartyRole, DateTime today);
        public void PrepareForSave(LoanApplication loanApplication, PartyRole customerPartyRole, int employeePartyRole, DateTime today)
        {
            if (this.IsNew)
            {
                var assoc = Context.ChequeApplicationAssocs.Where(e => e.ApplicationId == loanApplication.ApplicationId);
                if (assoc != null)
                {
                    foreach (var item in assoc)
                    {
                        var cheque = Context.Cheques.SingleOrDefault(entity => entity.Id == item.ChequeId);
                        var payments = Payment.GetById(cheque.PaymentId);
                        var rpAssoc = Context.ReceiptPaymentAssocs.SingleOrDefault(entity => entity.PaymentId == payments.Id);
                        Receipt receipts = Context.Receipts.SingleOrDefault(entity => entity.Id == rpAssoc.ReceiptId);

                        Context.ChequeApplicationAssocs.DeleteObject(item);
                        Context.Cheques.DeleteObject(cheque);
                        Context.Receipts.DeleteObject(receipts);
                        Context.Payments.DeleteObject(payments);
                        Context.ReceiptPaymentAssocs.DeleteObject(rpAssoc);
                    }
                }

                //create Payment
                var transactionDate = DateTime.Today;
                Payment payment = Payment.CreatePayment(today, transactionDate, customerPartyRole.Id, employeePartyRole,
                    this.Amount, PaymentType.Receipt, PaymentMethodType.PersonalCheckType,
                    SpecificPaymentType.LoanPaymentType, this.ChequeNumber);
                Context.Payments.AddObject(payment);

                //create cheque
                Cheque newCheck = new Cheque();
                newCheck.BankPartyRoleId = this.BankId;
                newCheck.CheckDate = this.ChequeDate;
                newCheck.Payment = payment;
                Context.Cheques.AddObject(newCheck);

                //create cheque association
                ChequeApplicationAssoc chequeAssoc = new ChequeApplicationAssoc();
                chequeAssoc.Cheque = newCheck;
                chequeAssoc.Application = loanApplication.Application;

                //create receipt and receipt payment assoc
                Receipt receipt = Receipt.CreateReceipt(null, this.Amount);
                Receipt.CreateReceiptPaymentAssoc(receipt, payment);

                //Context.SaveChanges();
            }
            else if (this.ToBeDeleted)
            {
                var payment = Payment.GetById(this.PaymentId);
                //TODO:: Changed to new payment
                var cheque = Context.Cheques.SingleOrDefault(entity => entity.Id == this.ChequeId && entity.PaymentId == payment.Id);
                var rpAssoc = Context.ReceiptPaymentAssocs.SingleOrDefault(entity => entity.PaymentId == payment.Id);

                var assoc = Context.ChequeApplicationAssocs.SingleOrDefault(entity => entity.ChequeId == cheque.Id);
                //TODO:: Changed to new payment
                Context.ChequeApplicationAssocs.DeleteObject(assoc);
                Context.Cheques.DeleteObject(cheque);
                Context.Receipts.DeleteObject(rpAssoc.Receipt);
                Context.Payments.DeleteObject(rpAssoc.Payment);
                Context.ReceiptPaymentAssocs.DeleteObject(rpAssoc);
            }

            else if (this.IsNew == false && this.ToBeDeleted == false)
            {
                var payment = Context.Payments.SingleOrDefault(entity => entity.Id == this.PaymentId);
                payment.TransactionDate = this.TransactionDate;
                payment.PaymentReferenceNumber = this.ChequeNumber;

                var cheque = Context.Cheques.SingleOrDefault(entity => entity.Id == this.ChequeId && entity.PaymentId == payment.Id);
                cheque.BankPartyRoleId = this.BankId;
            }
        }
 public void PrepareForSave(LoanApplication loanApplication, RoleType roleType, DateTime today)
 {
     if (this.IsNew)
     {
         var party = Context.Parties.SingleOrDefault(entity => entity.Id == this.PartyId);
         var partyRole = PartyRole.CreateLoanApplicationRole(loanApplication, roleType, party, today);
         Context.PartyRoles.AddObject(partyRole);
     }
     else if (this.ToBeDeleted)
     {
         var role = Context.LoanApplicationRoles.SingleOrDefault(entity => entity.Id ==LoanApplicationRoleId);
         PartyRole partyRole = role.PartyRole;
         partyRole.EndDate = today;
         Context.LoanApplicationRoles.DeleteObject(role);
     }
     //else if (this.IsNew == false && this.ToBeDeleted == false)
     //{
     //    var party = Context.Parties.SingleOrDefault(entity => entity.Id == this.PartyId);
     //    var partyRole = PartyRole.CreateLoanApplicationRole(loanApplication, roleType, party, today);
     //    Context.PartyRoles.AddObject(partyRole);
     //}
 }
        public void PrepareForSave(LoanApplication loanApplication, DateTime today)
        {
            if (this.IsNew)
            {
                ProductFeatureApplicability featureApp;
                if (this.IsFromPickList == false)
                {
                    ProductFeature feature = ProductFeature.GetByName(this.Name);
                    if (feature == null)
                    {
                        feature = new ProductFeature();
                        feature.Name = this.Name;
                        feature.ProductFeatureCategory = ProductFeatureCategory.FeeType;
                        Context.ProductFeatures.AddObject(feature);
                    }

                    FinancialProduct financialProduct = FinancialProduct.GetById(this.FinancialProductId);
                    featureApp = ProductFeatureApplicability.GetActive(feature, financialProduct);
                    if (featureApp == null)
                        featureApp = ProductFeatureApplicability.Create(feature, financialProduct, today);

                }
                else
                {
                    featureApp = ProductFeatureApplicability.GetById(this.ProductFeatureApplicabilityId);
                }

                ApplicationItem item = new ApplicationItem();
                item.Application = loanApplication.Application;
                item.ProductFeatureApplicability = featureApp;
                item.FeeComputedValue = this.TotalChargePerFee;
                item.EffectiveDate = today;

                LoanApplicationFee fee = new LoanApplicationFee();
                fee.LoanApplication = loanApplication;
                fee.Particular = this.Name;
                fee.Amount = this.Amount;
                //fee.ApplicationItem = item;

                Context.LoanApplicationFees.AddObject(fee);
                Context.ApplicationItems.AddObject(item);
            }
            else if (this.ToBeDeleted)
            {
                LoanApplicationFee applicationFee = Context.LoanApplicationFees.SingleOrDefault(entity => entity.Id == this.LoanApplicationFeeId);
                if (applicationFee != null)
                {
                    var application = applicationFee.LoanApplication.Application;
                    var productFeature = ProductFeature.GetByName(applicationFee.Particular);
                    var applicationItem = ApplicationItem.Get(application, productFeature);
                    applicationItem.EndDate = today;
                    Context.LoanApplicationFees.DeleteObject(applicationFee);
                }
            }
            else if (this.IsNew == false && this.ToBeDeleted == false)
            {
                ProductFeatureApplicability featureApp;
                if (this.IsFromPickList == false)
                {
                    ProductFeature feature = ProductFeature.GetByName(this.Name);
                    if (feature == null)
                    {
                        feature = new ProductFeature();
                        feature.Name = this.Name;
                        feature.ProductFeatureCategory = ProductFeatureCategory.FeeType;
                        Context.ProductFeatures.AddObject(feature);
                    }

                    FinancialProduct financialProduct = FinancialProduct.GetById(this.FinancialProductId);
                    featureApp = ProductFeatureApplicability.GetActive(feature, financialProduct);
                    if (featureApp == null)
                        featureApp = ProductFeatureApplicability.Create(feature, financialProduct, today);

                }
                else
                {
                    featureApp = ProductFeatureApplicability.GetById(this.ProductFeatureApplicabilityId);
                }

                ApplicationItem item = new ApplicationItem();
                item.Application = loanApplication.Application;
                item.ProductFeatureApplicability = featureApp;
                item.FeeComputedValue = this.TotalChargePerFee;
                item.EffectiveDate = today;

                LoanApplicationFee fee = new LoanApplicationFee();
                fee.LoanApplication = loanApplication;
                fee.Particular = this.Name;
                fee.Amount = this.Amount;
                //fee.ApplicationItem = item;

                Context.LoanApplicationFees.AddObject(fee);
                Context.ApplicationItems.AddObject(item);
            }
        }
        //if customer has no loan application with status of: //‘Pending: Approval’, ‘Approved’ or ‘Pending: In Funding’
        private static bool CheckIfHasNoLoanApplications(LoanApplication loanApplication, RoleType borrowerRoleType, Party party)
        {
            var allLoanApplications = LoanApplication.GetAllLoanApplicationOf(party, borrowerRoleType); //get all loan applications under the borrower
            var all = from application in allLoanApplications
                      join status in Context.LoanApplicationStatus on application.ApplicationId equals status.ApplicationId
                      where status.IsActive && (status.StatusTypeId == LoanApplicationStatusType.PendingApprovalType.Id
                      || status.StatusTypeId == LoanApplicationStatusType.ApprovedType.Id
                      || status.StatusTypeId == LoanApplicationStatusType.PendingInFundingType.Id)
                      && application.ApplicationId != loanApplication.ApplicationId
                      select application;

            return all.Count() == 0;
        }
        public void PrepareForSave(LoanApplication app, AmortizationSchedule sched, AmortizationScheduleModel models)
        {
            if (this.IsNew)
            {
                if (app.LoanTermLength != 0)
                {
                    AmortizationScheduleItem item = new AmortizationScheduleItem();
                    item.AmortizationSchedule = sched;
                    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);
                }
            }
            else
            {
                if (app.LoanTermLength != 0)
                {
                    var items = Context.AmortizationScheduleItems.Where(entity => entity.AmortizationScheduleId == sched.Id);
                    foreach (var schedule in items)
                    {
                        Context.AmortizationScheduleItems.DeleteObject(schedule);
                    }

                    AmortizationScheduleItem item = new AmortizationScheduleItem();
                    item.AmortizationSchedule = sched;
                    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);

                    //int count = Convert.ToInt32(models.Counter.ElementAt(models.Counter.Length - 1));
                    //int i = 0;
                    //foreach (var item in items)
                    //{
                    //    if (i != count)
                    //        i++;
                    //    else
                    //    {
                    //        DateTime date = models.ScheduledPaymentDate;
                    //        item.ScheduledPaymentDate = date;
                    //        item.PrincipalPayment = models.PrincipalPayment;
                    //        item.InterestPayment = models.InterestPayment;
                    //        item.PrincipalBalance = models.PrincipalBalance;
                    //        item.TotalLoanBalance = models.TotalLoanBalance;
                    //        item.IsBilledIndicator = false;
                    //        break;
                    //    }
                    //}
                }
            }
        }
        private static void CreateAgreementForGuarantor(LoanApplication loanApplication, Agreement agreement, DateTime today)
        {
            var applicationGuarantor = RoleType.GuarantorApplicationType;
            var roles = Context.LoanApplicationRoles.Where(entity => entity.ApplicationId == loanApplication.ApplicationId && entity.PartyRole.RoleTypeId == applicationGuarantor.Id
                 && entity.PartyRole.EndDate == null);

            var agreementGuarantor = RoleType.GuarantorAgreementType;
            foreach (var role in roles)
            {
                PartyRole partyRole = role.PartyRole;
                var newpartyRole = PartyRole.Create(agreementGuarantor, partyRole.Party, today);
                Context.PartyRoles.AddObject(newpartyRole);

                var agreementRole = CreateAgreementRole(agreement, newpartyRole);
                Context.AgreementRoles.AddObject(agreementRole);
            }
        }
        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 LoanApplicationStatu ChangeLoanApplicationStatusToCancelled(LoanApplication oldLoanApplication, DateTime today)
        {
            LoanApplicationStatu oldLoanApplicationStatus = new LoanApplicationStatu();
            oldLoanApplicationStatus.LoanApplication = oldLoanApplication;
            oldLoanApplicationStatus.LoanApplicationStatusType = LoanApplicationStatusType.CancelledType;
            oldLoanApplicationStatus.IsActive = true;
            oldLoanApplicationStatus.TransitionDateTime = today;

            return oldLoanApplicationStatus;
        }
        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();
        }
Esempio n. 53
0
 public Ticket Store(LoanApplication application)
 {
     // Hard coded to store to a file via IO... code omitted
     return new Ticket();
 }
        public static void Cancel(LoanApplication loanApplication, DateTime today, int processedByPartyId)
        {
            if (LoanApplicationStatu.CanChangeStatusTo(loanApplication, LoanApplicationStatusType.CancelledType))
            {
                RoleType borrowerRoleType = RoleType.BorrowerApplicationType;
                PartyRole borrowerPartyRole = PartyRole.GetPartyRoleFromLoanApplication(loanApplication, borrowerRoleType);
                PartyRole customerPartyRole = PartyRole.GetByPartyIdAndRole(borrowerPartyRole.PartyId, RoleType.CustomerType);
                var customerStatus = customerPartyRole.Customer.CurrentStatus;
                //if customer status is active
                if (customerStatus.CustomerStatusType == CustomerStatusType.ActiveType)
                {
                    if ((CheckIfHasNoOutstandingLoans(borrowerRoleType, customerPartyRole)) && (CheckIfHasNoLoanApplications(loanApplication, borrowerRoleType, customerPartyRole.Party)))
                        CustomerStatu.ChangeStatus(customerPartyRole, CustomerStatusType.InactiveType, today); //change customer status
                    //else do not update customer status
                }
                //else: do not update customer status
                var status = loanApplication.CurrentStatus;
                if (status.StatusTypeId == LoanApplicationStatusType.ApprovedType.Id
                    || status.StatusTypeId == LoanApplicationStatusType.PendingApprovalType.Id)
                {
                    var agreement = loanApplication.Application.Agreements.FirstOrDefault(entity => entity.EndDate == null);
                    if (agreement != null)
                    {
                        var vcrStatuses = from vcr in agreement.LoanDisbursementVcrs
                                          join vcrStatus in Context.DisbursementVcrStatus on vcr.Id equals vcrStatus.LoanDisbursementVoucherId
                                          where vcrStatus.IsActive == true &&
                                          (vcrStatus.DisbursementVoucherStatTypId == DisbursementVcrStatusEnum.PendingType.Id
                                          || vcrStatus.DisbursementVoucherStatTypId == DisbursementVcrStatusEnum.ApprovedType.Id
                                          || vcrStatus.DisbursementVoucherStatTypId == DisbursementVcrStatusEnum.RejectedType.Id)
                                          select vcrStatus;

                        foreach (var vcrStatus in vcrStatuses)
                        {
                            vcrStatus.IsActive = false;
                        }

                        foreach (var vcr in agreement.LoanDisbursementVcrs)
                        {
                            var vcrStatus = DisbursementVcrStatu.Create(vcr, DisbursementVcrStatusEnum.CancelledType, today);
                            vcrStatus.Remarks = "Loan Application is cancelled";
                        }
                    }
                }

                LoanApplicationStatu.ChangeStatus(loanApplication, LoanApplicationStatusType.CancelledType, today);

                //Insert loan clerk who processed the application
                if (RoleType.ProcessedByApplicationType.PartyRoleType != null)
                {
                    var party = Party.GetById(processedByPartyId);
                    PartyRole processedBy = PartyRole.CreateAndUpdateCurrentLoanApplicationRole
                        (loanApplication, party, RoleType.ProcessedByApplicationType, today);
                }

                //Cancel Cheques associated and receipts
                var remarks = "Loan Application was cancelled.";
                var assoc = Context.ChequeApplicationAssocs.Where(entity => entity.ApplicationId == loanApplication.ApplicationId);
                foreach (var item in assoc)
                {
                    //TODO:: Changed to new payment.
                    var cheque = Cheque.GetById(item.ChequeId);
                    var rpAssoc = Context.ReceiptPaymentAssocs.SingleOrDefault(entity => entity.PaymentId == cheque.PaymentId);
                    var receipt = rpAssoc.Receipt;

                    ChequeStatu.ChangeStatus(cheque, ChequeStatusType.CancelledType, remarks);
                    ReceiptStatu.ChangeStatus(receipt, ReceiptStatusType.CancelledReceiptStatusType, remarks);
                }
            }
        }
        private LoanApplicationStatu CreateLoanApplicationStatus(LoanApplication loanApplication, DateTime today)
        {
            LoanApplicationStatu loanApplicationStatus = new LoanApplicationStatu();
            loanApplicationStatus.LoanApplication = loanApplication;
            loanApplicationStatus.LoanApplicationStatusType = LoanApplicationStatusType.ClosedType;
            loanApplicationStatus.TransitionDateTime = today;
            loanApplicationStatus.IsActive = true;

            Context.LoanApplicationStatus.AddObject(loanApplicationStatus);
            return loanApplicationStatus;
        }
        public override void PrepareForSave(LoanApplication loanApplication, PartyRole customerPartyRole, DateTime today)
        {
            if (this.IsNew)
            {
                var asset = AddAsset(loanApplication, today);

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Add(asset, today);
                }

                BankAccount bank = new BankAccount();
                bank.Asset = asset;
                bank.BankAccountTypeId = this.BankAccountType;
                bank.BankPartyRoleId = this.BankPartyRoleId;
                bank.AccountNumber = this.BankAccountNumber;
                bank.AccountName = this.BankAccountName;
            }
            else if (this.ToBeDeleted)
            {
                Asset asset = Context.Assets.SingleOrDefault(entity => entity.Id == this.AssetId);
                RemoveCurrentMortgagee(asset, today);

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Remove(today);
                }

                if (asset.BankAccount != null)
                    Context.BankAccounts.DeleteObject(asset.BankAccount);

                Context.Assets.DeleteObject(asset);
            }
            else if (this.IsEdited)
            {
                Asset asset = Context.Assets.SingleOrDefault(entity => entity.Id == this.AssetId);
                UpdateAsset(asset, today);
                BankAccount bank = asset.BankAccount;
                bank.BankAccountTypeId = this.BankAccountType;
                bank.BankPartyRoleId = this.BankPartyRoleId;
                bank.AccountNumber = this.BankAccountNumber;
                bank.AccountName = this.BankAccountName;

                foreach (PropertyOwner owner in PropertyOwners)
                {
                    owner.Save(asset, today);
                }
            }
            else if (this.IsNew == false && this.ToBeDeleted == false && this.IsEdited == false)
            {
                if (this.AssetId == 0)
                {
                    var asset = AddAsset(loanApplication, today);

                    foreach (PropertyOwner owner in PropertyOwners)
                    {
                        owner.Add(asset, today);
                    }

                    BankAccount bank = new BankAccount();
                    bank.Asset = asset;
                    bank.BankAccountTypeId = this.BankAccountType;
                    bank.BankPartyRoleId = this.BankPartyRoleId;
                    bank.AccountNumber = this.BankAccountNumber;
                    bank.AccountName = this.BankAccountName;
                }
            }
        }