public void ProduceOfferReturnsCorrectResult(
            LoanType loanType,
            int term,
            PaymentFrequency frequency)
        {
            var sut = new DesiredLoanMortgageApplicationProcessor();
            var application = new MortgageApplication
            {
                DesiredLoanType = loanType,
                DesiredTerm = term,
                DesiredFrequency = frequency
            };

            var actual = sut.ProduceOffer(application);

            var expected = new IRendering[]
            {
                new Heading2Rendering("Desired loan"),
                new BoldRendering("Loan type:"),
                new TextRendering(" " + loanType),
                new LineBreakRendering(),
                new BoldRendering("Term:"),
                new TextRendering(" " + term + " years."),
                new LineBreakRendering(),
                new BoldRendering("Frequency:"),
                new TextRendering(" " + frequency),
                new LineBreakRendering()
            };
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 2
0
 public Loan(int crn,  DateTime loanComDate, decimal atb, int repayPeriod, LoanType loanType, string comments)
 {
     CRN = crn;
     LoanCommencementDate = loanComDate;
     ATB = atb;
     RepaymentPeriod = repayPeriod;
     LoanType = loanType;
     Comments = comments;
     
 }
Ejemplo n.º 3
0
        public async Task <LoanType> CreateNewLoanTypes(LoanType LoanTypes)
        {
            try
            {
                _context.LoanTypes.Add(LoanTypes);
                await _context.SaveChangesAsync();

                return(LoanTypes);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static List <LoanType> GetLoanTypeList(bool allOffices = false, bool showDeleted = false)
        {
            List <LoanType> LoanTypeList  = new List <LoanType>();
            DataTable       LoanTypeTable = LoanTypeDataAccess.GetInstance.GetLoanTypeList(allOffices, showDeleted);

            foreach (DataRow dr in LoanTypeTable.Rows)
            {
                LoanType TheLoanType = DataRowToObject(dr);

                LoanTypeList.Add(TheLoanType);
            }

            return(LoanTypeList);
        }
        // GET: LoanTypes/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            LoanType loanType = db.LoanTypes.Find(id);

            if (loanType == null)
            {
                return(HttpNotFound());
            }
            return(View(loanType));
        }
Ejemplo n.º 6
0
 /// <summary>
 /// To the data contract.
 /// </summary>
 /// <param name="loanType">Type of the loan.</param>
 /// <returns></returns>
 public static LoanTypeContract ToDataContract(this LoanType loanType)
 {
     return(new LoanTypeContract()
     {
         DegreeType = loanType.LoanName,
         Amount = loanType.LoanAmount,
         LessonUserId = loanType.UserId,
         //new fields
         AnnualIncome = loanType.AnnualIncome,
         FinancialDependents = loanType.FinancialDependents,
         State = loanType.State,
         InterestRate = loanType.InterestRate,
         Id = loanType.LoanTypeId
     });
 }
Ejemplo n.º 7
0
 //only called once at beginning could be refactored who cares for now
 public void InitializeLoan( float newAmount, LoanType type )
 {
     initLoanAmount = newAmount;
     loanAmount = initLoanAmount;
     thisLoanType = type;
     if (type == LoanType.Business) {
         loanName = "Business Loans";
     }
     else if (type == LoanType.School) {
         loanName = "School Loans";
     }
     else if (type == LoanType.RealEstate) {
         loanName = "Real Estate Loans";
     }
 }
Ejemplo n.º 8
0
		public IDictionary<string, string> GetAppraisalFormsData(AppraisalType appraisalType, LoanType loanType, int? propertyType, int? occupancy)
		{
			IEnumerable<AppraisalFormEntity> formsData = propertyType.HasValue && occupancy.HasValue ?
				GetEntities().Where(e => e.AppraisalTypes.Contains(appraisalType) && e.LoanTypes.Contains(loanType)) :
				Enumerable.Empty<AppraisalFormEntity>();
			if (propertyType.HasValue)
			{
				formsData = formsData.Where(e => e.PropertyTypes.Contains(propertyType.Value));
			}
			if (occupancy.HasValue)
			{
				formsData = formsData.Where(e => e.Occupancies.Contains(occupancy.Value));
			}
			return formsData.ToDictionary(e => e.Id.ToString(CultureInfo.InvariantCulture), e => e.FormName);
		}
Ejemplo n.º 9
0
        /// <summary>
        /// Parse text to loan type
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool TryParseLoanStatus(string text, out LoanType loanType)
        {
            switch (text.Trim().Replace(' ', default(char)))
            {
            case var name when name.Equals("agriculturalloan", StringComparison.InvariantCultureIgnoreCase):
                loanType = LoanType.Agricultural;

                return(true);

            case var name when name.Equals("businessloan", StringComparison.InvariantCultureIgnoreCase):
                loanType = LoanType.Business;

                return(true);

            case var name when name.Equals("carloan", StringComparison.InvariantCultureIgnoreCase):
                loanType = LoanType.Car;

                return(true);

            case var name when name.Equals("invoicefinancing", StringComparison.InvariantCultureIgnoreCase):
                loanType = LoanType.InvoiceFinancing;

                return(true);

            case var name when name.Equals("mortgageloan", StringComparison.InvariantCultureIgnoreCase):
                loanType = LoanType.Mortage;

                return(true);

            case var name when name.Equals("pawnbrokingloan", StringComparison.InvariantCultureIgnoreCase):
                loanType = LoanType.Pawnbroking;

                return(true);

            case var name when name.Equals("personalloan", StringComparison.InvariantCultureIgnoreCase):
                loanType = LoanType.Personal;

                return(true);

            case var name when name.Equals("short-termloan", StringComparison.InvariantCultureIgnoreCase):
                loanType = LoanType.ShortTerm;

                return(true);
            }

            loanType = default(LoanType);
            return(false);
        }
Ejemplo n.º 10
0
        // GET: LoanType/Delete/5
        public ActionResult Delete(Nullable <short> id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            Db       db       = new Db(DbServices.ConnectionString);
            LoanType loanType = LoanTypeServices.Get(id.Value, db);

            if (loanType == null)
            {
                return(HttpNotFound());
            }
            return(View(loanType));
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> UpdateLoanType(int LoanTypeId, LoanType loanType)
        {
            try
            {
                var res = await _service.UpdateLoanType(LoanTypeId, loanType);

                if (res != null)
                {
                    return(Ok(res));
                }
                return(StatusCode(StatusCodes.Status204NoContent));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 12
0
 private Loan CreateTestLoan(decimal amount, decimal apr, State state, LoanType loanType)
 {
     return(new Loan
     {
         Apr = apr,
         LoanAmount = amount,
         Fees = new List <Fee>
         {
             new Fee {
                 Amount = 50, FeeType = FeeType.Application
             }
         },
         LoanType = loanType,
         PrimaryOccupancy = true,
         State = state
     });
 }
Ejemplo n.º 13
0
        public async Task <IActionResult> CreateLoanType(LoanType loanType)
        {
            try
            {
                var response = await _service.CreateNewLoanType(loanType);

                if (response != null)
                {
                    return(Ok(response));
                }
                return(StatusCode(StatusCodes.Status204NoContent));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 14
0
        public void IsSatisfiedByReturnsCorrectResult(
            LoanType matchingLoanType,
            LoanType desiredLoanType,
            bool expected)
        {
            var sut = new DesiredLoanTypeMortgageApplicationSpecification
            {
                MatchingLoanType = matchingLoanType
            };
            var application = new MortgageApplication
            {
                DesiredLoanType = desiredLoanType
            };

            var actual = sut.IsSatisfiedBy(application);

            Assert.Equal(expected, actual);
        }
        public void IsSatisfiedByReturnsCorrectResult(
            LoanType matchingLoanType,
            LoanType desiredLoanType,
            bool expected)
        {
            var sut = new DesiredLoanTypeMortgageApplicationSpecification
            {
                MatchingLoanType = matchingLoanType
            };
            var application = new MortgageApplication
            {
                DesiredLoanType = desiredLoanType
            };

            var actual = sut.IsSatisfiedBy(application);

            Assert.Equal(expected, actual);
        }
        public void EqualsReturnsCorrectResult(
            LoanType sutLoanType,
            LoanType otherLoanType,
            bool expected)
        {
            var sut = new DesiredLoanTypeMortgageApplicationSpecification
            {
                MatchingLoanType = sutLoanType
            };
            var other = new DesiredLoanTypeMortgageApplicationSpecification
            {
                MatchingLoanType = otherLoanType
            };

            var actual = sut.Equals(other);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 17
0
        public async Task <string> UpdateLoanTypes(int id, LoanType LoanTypes)
        {
            try
            {
                var res = await _context.LoanTypes.FirstOrDefaultAsync(m => m.LoanTypeId == id);

                res.Name    = LoanTypes.Name;
                res.Details = LoanTypes.Details;
                _context.Update(res);
                await _context.SaveChangesAsync();

                return("Updated Record");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 18
0
        public void EqualsReturnsCorrectResult(
            LoanType sutLoanType,
            LoanType otherLoanType,
            bool expected)
        {
            var sut = new DesiredLoanTypeMortgageApplicationSpecification
            {
                MatchingLoanType = sutLoanType
            };
            var other = new DesiredLoanTypeMortgageApplicationSpecification
            {
                MatchingLoanType = otherLoanType
            };

            var actual = sut.Equals(other);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 19
0
        public virtual ILoanGateway CreateLoanGateway(LoanType type)
        {
            ILoanGateway gateway = null;

            switch (type)
            {
            case LoanType.Car:
                gateway = new CarLoan();
                break;

            case LoanType.House:
                gateway = new HousingLoan();
                break;

            default: break;
            }
            return(gateway);
        }
Ejemplo n.º 20
0
 //only called once at beginning could be refactored who cares for now
 public void InitializeLoan(float newAmount, LoanType type)
 {
     initLoanAmount = newAmount;
     loanAmount     = initLoanAmount;
     thisLoanType   = type;
     if (type == LoanType.Business)
     {
         loanName = "Business Loans";
     }
     else if (type == LoanType.School)
     {
         loanName = "School Loans";
     }
     else if (type == LoanType.RealEstate)
     {
         loanName = "Real Estate Loans";
     }
 }
Ejemplo n.º 21
0
        public PaymentSchedule GetPaymentSchedule(LoanType loanType, int duration, double principal)
        {
            Validate(duration, principal);

            var factory = new LoanFactory();
            var loan    = factory.GetLoan(loanType);

            var calculationStrategy = new FixedMonthlyRateCalculationStrategy();

            var loanCalulator = new LoanCalculator(calculationStrategy);

            return(loanCalulator.GetPaymentSchedule(new LoanCalculationParameters()
            {
                AnnualInterestRate = loan.InterestRate,
                PaybackTimeInYears = duration,
                Principal = principal
            }));
        }
Ejemplo n.º 22
0
 public static Boolean isLoanTypeValidForAdding(LoanType loanType)
 {
     if (loanType != null)
     {
         if (!loanType.Type_name.Equals(""))
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
Ejemplo n.º 23
0
    /// <summary>
    /// Attempts to add a loan of the specified amount of money,
    /// failure conditions included and will affect the dialog
    /// </summary>
    public void addDebt(ValidLoan associatedLoanData)
    {
        try{
            float    amount   = float.Parse(associatedLoanData.addLoanInput.text, CultureInfo.InvariantCulture.NumberFormat);
            LoanType loanType = associatedLoanData.loanType;
            if (amount < 0.0f)
            {
                dialogText.text = associatedLoanData.errorText;
                audioS.PlayOneShot(failureSound, Settings.volume);
                Debug.Log($"{creditorId}: You're supposed to borrow from *me*!");
                return;
            }

            if (
                (threatLevel < threatThreshold) &&
                ((maxLoanAmount * StateManager.maxLoanAdjuster) >= (loanTotal + amount)) &&  // secured loans bypass this a bit...
                (numberOfLoans < loanHardCap)
                )
            {
                float modifiedInterest = associatedLoanData.interestRate * associatedLoanData.collateralRateReduction * StateManager.rateAdjuster; // collateralRateReduction should always be 1 for unsecured loans
                float collateral       = (float)Math.Round(associatedLoanData.collateralAmountPercent * amount, 2);                                // collateralAmountPercent should always be 0 for unsecured loans
                float modifiedAmount   = (float)Math.Round(collateral + amount, 2);
                Loan  newLoan          = new Loan(StateManager.nextID, modifiedAmount, modifiedInterest, loanType, collateral, creditorId);
                Debug.Log($"{creditorId}: adding ${modifiedAmount} loan with a  {collateral} deposit @ {modifiedInterest*100}%");
                StateManager.loanList.Add(newLoan);
                StateManager.cashOnHand += amount;
                StateManager.nextID++;
                initialDebtType.addLoanInput.text = "";
                updateFields();

                dialogText.text = associatedLoanData.successText;
                audioS.PlayOneShot(paymentSound, Settings.volume * debtIsLoud);
                return;
            }
            Debug.Log($"{creditorId}: Bad dog, no biscuit!");
            dialogText.text = associatedLoanData.failureText;
            audioS.PlayOneShot(failureSound, Settings.volume);
            return;
        }
        catch (Exception e) {
            dialogText.text = "Oh, hi, who are you? And why do you smell like motor oil?";
            Debug.Log($"Exception found: {e}");
        }
    }
Ejemplo n.º 24
0
		public static Order CreateTestOrder(LoanType loanType = LoanType.Conventional, bool supplementalREOAddendum = false)
		{
			using (var db = new DVSContext())
			{
				Order order = new Order()
				{
					GeneralInfo = new OrderGeneralInfo()
					{
						PropertyAddress = new Address() { ZIP = "12345", State = "NY" },
					},

					AppraisalInfo = new OrderAppraisalInfo()
					{
						PropertyTypeId = 1, //Single Family Residence - Attached
						OccupancyTypeId = 1,
						AppraisalTypeId = 1,
						Rush = true,
						AppraisalForm = 1,
						LoanType = loanType,
						SupplementalREOAddendum = supplementalREOAddendum
					},

					FeeInfo = new OrderFeeInfo()
					{
						AppraisalFee = 100
					},

					DueDate = DateTime.Now.AddDays(1),
					Latitude = 42.8140,
					Longitude = -73.94,
					OrderPublicId = Guid.NewGuid().ToString().Replace("-", String.Empty).Substring(0, 20),
					CreationDate = DateTime.Now,

					OrderStatus = OrderStatus.PendingAssignment,
					CreatedByClientUserId = 1
				};
				db.Orders.Add(order);
				db.SaveChanges();


				return order;
			}
		}
Ejemplo n.º 25
0
        public static LinkedList <LoanType> GetAllLoanTypes()
        {
            MySqlDataReader reader = Connection.getData("select * from loan_type order by id;");

            LinkedList <LoanType> types = new LinkedList <LoanType>();

            while (reader.Read())
            {
                LoanType loanType = new LoanType();

                loanType.Id        = reader.GetInt32(0);
                loanType.Type_name = reader.GetString(1);

                types.AddLast(loanType);
            }

            reader.Close();

            return(types);
        }
Ejemplo n.º 26
0
        private ObservableCollection <PostLoan> LoadCurrentLoans(LoanType selected)
        {
            ObservableCollection <PostLoan> psList = new ObservableCollection <PostLoan>();
            var result = _loansRepository.Where(
                x => x.LoanType.Code == selected.Code
                &&
                x.PeriodYear.Year == SelectedYear.Year
                );

            foreach (var loan in result)
            {
                PostLoan pl = new PostLoan(true, loan.FamilyMember.Code, loan.FamilyMember.FullName,
                                           loan.LoanType.Code, loan.LoanType.LoanDescription,
                                           loan.PeriodYear.Year, loan.PeriodYear.Year,
                                           loan.PaymentSequence.Id, loan.PaymentSequence.SequenceDescription,
                                           loan.Amount);
                psList.Add(pl);
            }
            return(psList);
        }
Ejemplo n.º 27
0
        void Search()
        {
            if (string.IsNullOrEmpty(SearchField))
            {
                return;
            }
            int searchedCode;

            if (int.TryParse(SearchField, out searchedCode))
            {
                var result = _repository.Query(loan => loan.Code == searchedCode);
                if (result == null || result.Count() != 1)
                {
                    return;
                }
                _currnetModel = result.First();
                ReadModelValues(_currnetModel);
                SetState(ModelState.Saved);
            }
        }
Ejemplo n.º 28
0
        public static Loan CreateLoanInstance(LoanType type, double interestRate)
        {
            Loan loanObject = default(Loan);

            switch (type)
            {
            case LoanType.Business:
                loanObject = new BusinessLoan(interestRate);
                break;

            case LoanType.Education:
                loanObject = new EducationLoan(interestRate);
                break;

            case LoanType.Home:
                loanObject = new HomeLoan(interestRate);
                break;
            }

            return(loanObject);
        }
 public LoanTrackingSolidarityGroupsReport(int groupId,
     string solidarityGroupName,
     Address solidarityGroupAddress,
     string CURP,
     string names,
     string lastName,
     string secondLastName,
     Gender gender,
     Ocupation ocupation,
     EducationLevel educationLevel,
     Address address,
     ContactInformation contactInformation,
     string trackingCode,
     UInt64 internalTrackingCode,
     LoanRequestStatus loanRequestStatus,
     DateTime loanRequestDate,
     DateTime? loanAuthorizationDate,
     LoanType loanType,
     decimal loanedAmount)
 {
     this._groupId = groupId;
     this._solidarityGroupName = solidarityGroupName;
     this._solidarityGroupAddress = solidarityGroupAddress;
     this._curp = CURP;
     this._names = names;
     this._lastName = lastName;
     this._secondLastName = secondLastName;
     this._gender = gender;
     this._ocupation = ocupation;
     this._educationLevel = educationLevel;
     this._address = address;
     this._contactInformation = contactInformation;
     this._trackingCode = trackingCode;
     this._internalTrackingCode = internalTrackingCode;
     this._loanRequestStatus = loanRequestStatus;
     this._loanRequestDate = loanRequestDate;
     this._loanAuthorizationDate = loanAuthorizationDate;
     this._loanType = loanType;
     this._loanedAmount = loanedAmount;
 }
Ejemplo n.º 30
0
        public async Task CreateLoanRequest(LoanRequest loanRequest, LoanType loanType,
                                            int userId, int employmentId)
        {
            if (loanRequest.LoanSum < loanType.MinLoanSum || loanRequest.LoanSum > loanType.MaxLoanSum)
            {
                throw new LoanSumOutOfBoundException();
            }
            if (loanRequest.Term < loanType.MinTerm || loanRequest.Term > loanType.MaxTerm)
            {
                throw new LoanTermOutOfBoundException();
            }

            loanRequest.DateOfRequest = DateTime.Now;
            loanRequest.LoanTypeId    = loanType.Id;
            loanRequest.UserId        = userId;
            loanRequest.EmployementId = employmentId;
            await _loanRequestRepository.InsertAsync(loanRequest);

            await _loanRequestRepository.SaveAsync();

            _logger.Info($"Created new loan request type: {loanType.Name}");
        }
Ejemplo n.º 31
0
        public void DeleteRecord(string index)
        {
            try
            {
                //Step 1 Code to delete the object from the database
                LoanType s = new LoanType();
                s.recordId = index;
                s.name     = "";

                PostRequest <LoanType> req = new PostRequest <LoanType>();
                req.entity = s;
                PostResponse <LoanType> r = _loanService.ChildDelete <LoanType>(req);
                if (!r.Success)
                {
                    X.MessageBox.ButtonText.Ok = Resources.Common.Ok;
                    Common.errorMessage(r);
                    return;
                }
                else
                {
                    //Step 2 :  remove the object from the store
                    Store1.Remove(index);

                    //Step 3 : Showing a notification for the user
                    Notification.Show(new NotificationConfig
                    {
                        Title = Resources.Common.Notification,
                        Icon  = Icon.Information,
                        Html  = Resources.Common.RecordDeletedSucc
                    });
                }
            }
            catch (Exception ex)
            {
                //In case of error, showing a message box to the user
                X.MessageBox.ButtonText.Ok = Resources.Common.Ok;
                X.Msg.Alert(Resources.Common.Error, Resources.Common.ErrorDeletingRecord).Show();
            }
        }
        public IList <LoanType> GetLoanTypes()
        {
            IList <LoanType> loanTypes = new List <LoanType>();

            SqlConnection connection = GetDBConnection();

            connection.Open();
            SqlCommand    command = new SqlCommand("SELECT LoanTypeID, LoanType FROM LoanTypes", connection);
            SqlDataReader reader  = command.ExecuteReader();

            while (reader.Read())
            {
                LoanType type = new LoanType();
                type.LoanTypeID   = int.Parse(reader.GetValue(0).ToString());
                type.LoanTypeName = reader.GetValue(1).ToString();
                loanTypes.Add(type);
            }
            command.Dispose();
            connection.Close();

            return(loanTypes);
        }
Ejemplo n.º 33
0
        public LoanType AskForLoanType(string message)
        {
            LoanType type = LoanType.Null;

            while (type == LoanType.Null)
            {
                //foreach (LoanType tipe in Enum.GetValues(typeof(LoanType)))
                //{
                //    if (tipe != LoanType.Null)
                //        WriteMessage(tipe.ToString());
                //}
                WriteMessage("1) Tasso fisso", ConsoleColor.Yellow);
                WriteMessage("2) Tasso variabile", ConsoleColor.Yellow);

                WriteMessage($"{message}", ConsoleColor.Gray, false);
                string strType = Console.ReadLine();

                int selection = 0;

                if (!int.TryParse(strType, out selection))
                {
                    WriteMessage("Il valore selezionato non è valido", ConsoleColor.Red);
                }
                else
                {
                    if (selection == 1)
                    {
                        return(LoanType.Fixed);
                    }
                    if (selection == 2)
                    {
                        return(LoanType.Variable);
                    }
                }
            }

            return(type);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Saves the loan information.
        /// </summary>
        /// <param name="loanInfo">The loan information.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">loanInfo</exception>
        public string SaveLoanInfo(ILoanView loanInfo)
        {
            if (loanInfo == null)
            {
                throw new ArgumentNullException(nameof(loanInfo));
            }

            var result = string.Empty;

            var newRecord = new LoanType
            {
                LoanType1 = loanInfo.LoanType,
                //LoanAmount = loanInfo.LoanAmount,
                //InterestRate = loanInfo.InterestRate,
                //DeductionRate = loanInfo.DeductionRate,
                //Duration = loanInfo.Duration,
                IsActive    = true,
                DateCreated = DateTime.UtcNow,
                // CompanyId = loanInfo.CompanyId
            };

            try
            {
                using (
                    var dbContext = (HRMSEntities)this.dbContextFactory.GetDbContext(ObjectContextType.HRMS))
                {
                    dbContext.LoanTypes.Add(newRecord);
                    dbContext.SaveChanges();
                }
            }
            catch (Exception e)
            {
                result = string.Format("Save Loan Information - {0} , {1}", e.Message,
                                       e.InnerException != null ? e.InnerException.Message : "");
            }

            return(result);
        }
Ejemplo n.º 35
0
 private LoanInfo(LoanType ltype, int minimumdaily, int maximumdaily, int daysforpayback, LoanInterest interest)
 {
     LType          = ltype;
     MinimumDaily   = minimumdaily;
     MaximumDaily   = maximumdaily;
     DaysForPayBack = daysforpayback;
     Interest       = interest;
     if (Interest == null)
     {
         if (ltype == LoanType.Small)
         {
             Interest = new DailyInterest(0.01);
         }
         else if (ltype == LoanType.Medium)
         {
             Interest = new DailyInterest(0.015);
         }
         else
         {
             Interest = new DailyInterest(0.02);
         }
     }
 }
Ejemplo n.º 36
0
        public ILoan Create(LoanType loanType)
        {
            ILoan loan = null;

            switch (loanType)
            {
            case LoanType.HomeLoan:
                loan = new HomeLoan();
                break;

            case LoanType.CarLoan:
                loan = new CarLoan();
                break;

            case LoanType.PersonalLoan:
                loan = new PersonalLoan();
                break;

            default:
                break;
            }
            return(loan);
        }
Ejemplo n.º 37
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var db = new DMSIPayrollEntities())
                {
                    if (tbDescription.Text == "" || tbLoanTypeCode.Text == "")
                    {
                        MessageBox.Show("Required fields cannot be empty.", "System Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (mode == 1)
                    {
                        LoanType loanType = new LoanType();
                        loanType.Description  = tbDescription.Text;
                        loanType.LoanTypeCode = tbLoanTypeCode.Text;
                        db.LoanTypes.Add(loanType);
                        db.SaveChanges();
                        MessageBox.Show("Add Succesful", "System Succes!", MessageBoxButton.OK, MessageBoxImage.Information);
                        clear();
                    }
                    else if (mode == 2)
                    {
                        var loanType = db.LoanTypes.Where(m => m.LoanTypeID == loantypeid).FirstOrDefault();
                        loanType.Description  = tbDescription.Text;
                        loanType.LoanTypeCode = tbLoanTypeCode.Text;
                        db.SaveChanges();
                        MessageBox.Show("Update Succesful", "System Succes!", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Something went wrong.", "System Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 38
0
        static ILoanCalculator AskForLoanCalculator(IGui gui)
        {
            LoanType        loanType   = gui.AskForLoanType("Quale tipo di mutuo desideri?");
            ILoanCalculator calculator = null;

            decimal initialAmount = gui.AskForDecimal("Quanti soldi si desidera richiedere?");
            bool    isClient      = gui.AskForBool("Sei già cliente della banca?");

            switch (loanType)
            {
            case LoanType.Fixed:
                calculator = new FixedLoanCalculator();
                break;

            case LoanType.Variable:
                calculator = new VariableLoanCalculator();
                break;
            }

            calculator.InitialAmount = initialAmount;
            calculator.IsClient      = isClient;

            return(calculator);
        }
Ejemplo n.º 39
0
        public virtual void Load()
        {
            string sql = "SELECT * FROM loans WHERE id=:id";
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters[":id"] = Id;

            DataTable result = database.Query(sql, parameters);
            if (result.Rows.Count == 1)
            {
                DataRow row = result.Rows[0];
                Principal = (decimal)row["principal"];
                Type = (Loan.LoanType)int.Parse(row["type"].ToString());
                if (Type == LoanType.AmortizedPayment)
                {
                    Term = int.Parse(row["term"].ToString());
                }
                InterestRate = (decimal)row["interest"];

                TakenDate = (DateTime)row["taken_date"];
                StartDate = (DateTime)row["start_date"];
                processingFee = (decimal)row["processing_fee"];
                //reloanFee = (decimal)row["reloan_fee"];
                if (row["remarks"].GetType() != typeof(System.DBNull))
                {
                    Remarks = (string)row["remarks"];
                }
                else
                {
                    Remarks = "";
                }

                Account loanAccount = new Account();
                loanAccount.Id = (long)row["account_id"];
                loanAccount.Load(database);

                Account = loanAccount;
                return;
            }
            throw new ApplicationException("Unable to load loan");
        }
Ejemplo n.º 40
0
 public LoanRequestMainReport(int loanRequestId,
     string CURP,
     string names,
     string lastName,
     string secondLastName,
     string clltrlNames,
     string clltrlLastName,
     string clltrlSecondLastName,
     DateTime birthDate,
     Gender gender,
     Ocupation ocupation,
     EducationLevel educationLevel,
     Address address,
     ContactInformation contactInformation,
     string trackingCode,
     UInt64 internalTrackingCode,
     string userName,
     LoanRequestStatus loanRequestStatus,
     DateTime loanRequestDate,
     DateTime? loanAuthorizationDate,
     LoanType loanType,
     decimal loanedAmount,
     string sector,
     string subsector,
     string branch)
 {
     this._loanRequestId = loanRequestId;
     this._curp = CURP;
     this._names = names;
     this._lastName = lastName;
     this._secondLastName = secondLastName;
     this._collateralNames = clltrlNames;
     this._collateralLastName = clltrlLastName;
     this._collateralSecondLastName = clltrlSecondLastName;
     this._birthDate = birthDate;
     this._gender = gender;
     this._ocupation = ocupation;
     this._educationLevel = educationLevel;
     this._address = address;
     this._contactInformation = contactInformation;
     this._trackingCode = trackingCode;
     this._internalTrackingCode = internalTrackingCode;
     this._username = userName;
     this._loanRequestStatus = loanRequestStatus;
     this._loanRequestDate = loanRequestDate;
     this._loanAuthorizationDate = loanAuthorizationDate;
     this._loanType = loanType;
     this._loanedAmount = loanedAmount;
     this._sector = sector;
     this._subsector = subsector;
     this._branch = branch;
 }
Ejemplo n.º 41
0
        public static decimal GetClosingCosts(
            decimal LoanAmount, 
            LoanPurpose LoanPurpose, 
            LoanType LoanType, 
            bool AddSurvey, 
            bool GetHOATransfer,
            bool? IsVAFirstTime,
            VeteranType? VeteranType, 
            decimal? PurchasePrice,
            DateTime? OriginalCloseDate,
            decimal? EstimatedLoanPayoff,
            out decimal VAFundingPercent,
            out decimal VAFundingFee
            )
        {
            VAFundingFee = 0;
            VAFundingPercent = 0;
            var ClosingCosts = 0m;

            decimal
                SellerContributions = 0m,
                NonAllowableContributions = 1990m;

            bool IsCashOutRefi = false,
                T17 = true,
                T19 = true,
                T36 = true,
                R19 = true,
                R24 = true,
                T33 = true,
                T42 = true,
                T421 = true;

            if (AddSurvey == true)
            {
                var surveyCost = 200;
                ClosingCosts += surveyCost;
            }

            if (GetHOATransfer == true)
            {
                var HoaTransferFee = 100;
                ClosingCosts += HoaTransferFee;
            }

            if (LoanPurpose == FullerHelpers.LoanPurpose.Purchase)
            {
                ClosingCosts = 2465m;
                if (LoanType == FullerHelpers.LoanType.VA)
                {
                    SellerContributions = 1990;
                    VAFundingFee = GetVAFundingFee(LoanAmount, LoanPurpose, VeteranType.Value, 0, IsVAFirstTime.Value, out VAFundingFee, out VAFundingPercent);
                    ClosingCosts += VAFundingFee;
                }

                if (LoanAmount == 0 || PurchasePrice == 0)
                {
                    throw new Exception("Cannot be Zero");
                }
                else
                {

                }
            }
            else if(LoanPurpose == FullerHelpers.LoanPurpose.Refinance)
            {
                ClosingCosts += 2557.42m;
                if (LoanType == FullerHelpers.LoanType.VA)
                {
                    SellerContributions = 1990;
                    VAFundingFee = GetVAFundingFee(LoanAmount, LoanPurpose, VeteranType.Value, 0, IsVAFirstTime.Value, out VAFundingFee, out VAFundingPercent);
                    ClosingCosts += VAFundingFee;
                }

                if (LoanAmount == 0 || EstimatedLoanPayoff == 0 || OriginalCloseDate == null)
                {
                    throw new Exception("");
                }
            }
            return ClosingCosts;
        }
Ejemplo n.º 42
0
        public static decimal GetPurchaseClosingCosts(
            decimal LoanAmount, 
            LoanType loanType, 
            bool AddSurvey, 
            bool GetHOATransfer, 
            VeteranType? VetType, 
            bool isVAFirstTime,
            decimal PurchasePrice,
            out decimal VAFundingPercent,
            out decimal VAFundingFee
        )
        {
            VAFundingFee = 0;
            VAFundingPercent = 0;

            return GetClosingCosts(LoanAmount, LoanPurpose.Purchase, loanType, AddSurvey, GetHOATransfer, isVAFirstTime, VetType, PurchasePrice, null, null, out VAFundingPercent, out VAFundingFee);
        }
Ejemplo n.º 43
0
		public JsonResult AppraisalFormsData(AppraisalType appraisalType, LoanType loanType, int propertyType, int occupancy)
		{
			var result = new Dictionary<string, string>();
			result.Add(string.Empty, Constants.Text.NoSelection);

			foreach (
				var keyValuePair in _appraisalFormsService.GetAppraisalFormsData(appraisalType, loanType, propertyType, occupancy))
			{
				result.Add(keyValuePair.Key, keyValuePair.Value);
			}

			return Json(result.Select(e => new { key = e.Key, value = e.Value }), JsonRequestBehavior.AllowGet);
		}
Ejemplo n.º 44
0
        /// <summary>
        /// Calculates the statement.
        /// </summary>	
        private void CalculateStatement()
        {
            try
            {
                _loanStmntCalc.GenerateStatement ();

                /* Displaying user data requires access to the data base via queries
                * In some instances this may not be required (automatic loan status updates)
                * thus the _displayUserData variable will be set to false */
                if (_displayUserData)
                {
                    /* Set some of the main properties */
                    _loanedAmount = _loan.LoanedAmount;
                    _loanType = _loan.LoanType;
                    _clientName = _loan.LoanRequest.Client.FullName;
                    _clientAddress = _loan.LoanRequest.Client.Address.FullAddress;
                    _clientPhoneNumber = _loan.LoanRequest.Client.ContactInformation.Telephone;
                    _loanTrackingInternal = _loan.LoanRequest.InternalTrackingCode.ToString ();
                    _loanTrackingCustom = _loan.LoanRequest.TrackingCode;
                    _curp = _loan.LoanRequest.Client.CURP;
                }
            }
            /* If the exception was thrown here, just pass it up */
            catch (ZiblerBusinessComponentsException ex)
            {
                throw;
            }
            /* Catch any Data Layer or other exception and throw an unkown exception */
            catch (Exception ex)
            {
                ZiblerBusinessComponentsUnknownException exc
                = new ZiblerBusinessComponentsUnknownException (ex);

                /* Throw the new exception */
                throw exc;
            }
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Calculates the statement.
        /// </summary>	
        private void CalculateStatement()
        {
            try
            {
                bool isValidDate =
                !DateUtilities.IsFirstDateGreaterThanSecondDate (Convert.ToDateTime (_stmntDate),
                                                                 DateTime.Today);

                if (!isValidDate)
                {
                    throw new ZiblerBusinessComponentsException (
                        Resources.LoanOperationsMsgStatementDateInFuture);
                }

                /* Set some of the main properties */
                _loanedAmount = _loan.LoanedAmount;
                _loanType = _loan.LoanType;

                /* Calculated the expected amortization table. This is just for informational purposes */
                CreateAmortizationTable (ref _expectedAmortization);
                RecalculateInterestAndVAT (_expectedAmortization);

                /* Create the amortization table without the Interest and VAT values */
                CreateAmortizationTable (ref _amortization);

                /* Calculate the Interest and VAT for every amortization in the
                * amortization table. This calculation takes into account the different
                * interest rate values over time, as well as VAT values over time.
                * If the amortization is in the future, then the statement date is used
                * to determine what Interest and VAT rates will be used. */
                RecalculateInterestAndVAT (_amortization);

                /* Use the Loan Start Date as the first calculation date */
                DateTime calcDate = Convert.ToDateTime (_loan.StartDate);
                DateTime statementDate = Convert.ToDateTime (_stmntDate);

                /* Local variables */
                decimal delinquentPrincipal = 0.00m;
                decimal delinquentInterest = 0.00m;
                decimal delinquentVAT = 0.00m;
                decimal moratoryInterest = 0.00m;
                decimal commissions = GetTotalAmountInCommissions ();

                /* Copy the values for the commission */
                _commissionsTotal = commissions;

                /* Contains the remainder after applying the payment */
                decimal remainder = 0.00m;

                /* While the calcDate is less or equal to the statement date
                * perform the operations within the while loop on a day by day
                * basis */
                while (!DateUtilities.IsFirstDateGreaterThanSecondDate (calcDate, statementDate))
                {
                    /* This list is only used for receipt purposes so it must be cleared
                    * every iteration */
                    _pymntApplctnRcrd = new List<PaymentApplicationRecord> ();

                    /* Used to calculate what was the application of a specific payment */
                    decimal pymntApplctn = 0.00m;

                    /* Calculate the moratory interest for the day using the delinquent principal */
                    decimal todaysMoratoryInterest
                    = CalculateMoratoryInterests (calcDate, delinquentPrincipal);

                    moratoryInterest = moratoryInterest + todaysMoratoryInterest;

                    /* List of payments that were made on the current iteration date */
                    IList<Payment> paymentsOnDate = GetPaymentsOnDate (calcDate);

                    /* The total number of payments to be proccessed.
                    * Note that each payment is processed individually. If
                    * it is not done this way, issues occur while printing
                    * payment receipts in which the application amounts change */
                    int totalPayments = paymentsOnDate.Count;

                    /* Index used to access the payments made on this date */
                    int prcssIndx = 0;

                    /* Apply payments one at the time (if the exist). Process the
                    * calculations at least one time.
                    * Process for each payment or (until the remainder is zero and there is nothing
                    * left to apply the remainder to)*/
                    do
                    {
                        /* If a payment exists */
                        if (prcssIndx < totalPayments)
                        {
                            /* Get the current payment */
                            Payment payment = paymentsOnDate[prcssIndx];

                            /* Copy the payments to the property list of payments */
                            _payments.Add (payment);

                            /* Add the amount paid to the totalAmountPaid and the remainder
                            * from a previous payment */
                            _totalAmountPaid = _totalAmountPaid + payment.Amount;
                            remainder = remainder + payment.Amount;

                            PaymentApplicationRecord crrntPymntApplctnRcrd = new PaymentApplicationRecord ();
                            crrntPymntApplctnRcrd.Amount = payment.Amount;
                            crrntPymntApplctnRcrd.PaymentDate = payment.PaymentDate;
                            crrntPymntApplctnRcrd.PaymentId = payment.Id;
                            crrntPymntApplctnRcrd.PaymentDetails = payment.Details;
                            crrntPymntApplctnRcrd.PaymentReference = payment.PaymentReference;
                            crrntPymntApplctnRcrd.ConfirmationNumber = payment.ConfirmationNumber;
                            crrntPymntApplctnRcrd.PaymentType = payment.PaymentType;
                            crrntPymntApplctnRcrd.LoanType = _loanType;

                            /* Calculate the percentage of total payment. Note that this is
                            * done in case there is a remainder from previous iterations.
                            * If no remainder exists it is assumed that the application
                            * will be done in total. */
                            if (remainder > 0)
                                crrntPymntApplctnRcrd.PercentageOfTotalPayment = crrntPymntApplctnRcrd.Amount /
                                                                                 remainder;
                            else
                                crrntPymntApplctnRcrd.PercentageOfTotalPayment = 1;

                            _pymntApplctnRcrd.Add (crrntPymntApplctnRcrd);
                        }

                        /* Apply the payments to any fees due or delinquent amounts. After doing so
                        * if there is any payment amount left, we will proceed to apply it to the
                        * corresponding amortization. */

                        /* Apply payment to the commissions first */
                        if (commissions > 0)
                        {
                            pymntApplctn = remainder;

                            remainder = ApplyPaymentToAmount (remainder, ref commissions);

                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);
                            CalculateSpecificPaymentApplication (pymntApplctn,
                                                                 PaymentApplicationPropertyType.CurrentCommissions);
                        }

                        /* Apply payment to the delinquent VAT next */
                        if (delinquentVAT > 0)
                        {
                            pymntApplctn = remainder;

                            remainder = ApplyPaymentToAmount (remainder, ref delinquentVAT);

                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);
                            CalculateSpecificPaymentApplication (pymntApplctn,
                                                                 PaymentApplicationPropertyType.DelinquentVAT);
                        }

                        /* Apply payment to the moratory interest next */
                        if (moratoryInterest > 0)
                        {
                            pymntApplctn = remainder;

                            remainder = ApplyPaymentToAmount (remainder, ref moratoryInterest);

                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);
                            CalculateSpecificPaymentApplication (pymntApplctn,
                                                                 PaymentApplicationPropertyType.MoratoryInterests);
                        }

                        /* Apply payment to the delinquent interest next */
                        if (delinquentInterest > 0)
                        {
                            pymntApplctn = remainder;

                            remainder = ApplyPaymentToAmount (remainder, ref delinquentInterest);

                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);
                            CalculateSpecificPaymentApplication (pymntApplctn,
                                                                 PaymentApplicationPropertyType.DelinquentInterests);
                        }

                        /* Apply payment to the delinquent principal next */
                        if (delinquentPrincipal > 0)
                        {
                            pymntApplctn = remainder;

                            remainder = ApplyPaymentToAmount (remainder, ref delinquentPrincipal);

                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);
                            CalculateSpecificPaymentApplication (pymntApplctn,
                                                                 PaymentApplicationPropertyType.DelinquentPrincipal);
                        }

                        /* Get the amortization for this day. If there is an amortization due on this
                        * date, then apply the remainder payment to it. If the amortization is not
                        * covered in full, then generate delinquent charges accordingly.
                        * If the amortization is covered in full, verify if there is remainder left.
                        * If there is remainder payment left, then it means that the payment should
                        * be applied to the last amortization. Apply it to the principal
                        * and change the principal due in that amortization. By doing so, also the
                        * interest will change as long as there is principal left. */
                        AmortizationEntry tdysAmrtztn = null;

                        /* Get the amortization for today if there is one. */
                        foreach (AmortizationEntry amrtztn in _amortization.AmortizationTable)
                        {
                            /* If the calcDate matches the amrtztn.Date it means that
                            * amortization is due today */
                            if (DateTime.Compare (amrtztn.Date, calcDate) == 0)
                            {
                                tdysAmrtztn = amrtztn;
                                break;
                            }
                        }

                        /* There is an amortization scheduled for calcDate, so go ahead and apply
                        * the payment and make sure it is covered in full, otherwise generate
                        * delinquent charges. Delinquent charges will only be generated if the
                        * calcDate is not the statement date. This is because I don't want to
                        * generate delinquent charges until the day after the payments are due. */
                        if (tdysAmrtztn != null)
                        {
                            decimal tax = tdysAmrtztn.Tax;

                            pymntApplctn = remainder;

                            /* Apply the payment to the VAT */
                            remainder = ApplyPaymentToAmount (remainder, ref tax);

                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);
                            CalculateSpecificPaymentApplication (pymntApplctn,
                                                                 PaymentApplicationPropertyType.CurrentVAT);

                            /* Set the unpaid balance to the amortization */
                            tdysAmrtztn.Tax = tax;

                            /* Generate delinquent charges if the VAT was not covered in full.*/

                            /* Make sure that all payments have been taken into account before
                            * we consider the amount not covered in full */
                            if (tax > 0 && prcssIndx + 1 >= totalPayments)
                            {
                                /* If the statement Date is equal than the CalcDate
                                * it means that we have calculated everything up to this date
                                * so we don't consider the amortization amounts as delinquent
                                * otherwise mark it as delinquent. */
                                if (DateTime.Compare (calcDate, Convert.ToDateTime (_stmntDate)) !=
                                    0)
                                {
                                    /* Mark it as delinquent */
                                    delinquentVAT = delinquentVAT + tax;
                                }
                            }

                            decimal interest = tdysAmrtztn.Interest;

                            pymntApplctn = remainder;

                            /* Apply the payment to the interest */
                            remainder = ApplyPaymentToAmount (remainder, ref interest);

                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);
                            CalculateSpecificPaymentApplication (pymntApplctn,
                                                                 PaymentApplicationPropertyType.CurrentInterests);

                            /* Set the unpaid balance to the amortization */
                            tdysAmrtztn.Interest = interest;

                            /* Generate delinquent charges if the Interest was not covered in full */

                            /* Make sure that all payments have been taken into account before
                            * we consider the amount not covered in full */
                            if (interest > 0 && prcssIndx + 1 >= totalPayments)
                            {
                                /* If the statement Date is equal than the CalcDate
                                * it means that we have calculated everything up to this date
                                * so we don't consider the amortization amounts as delinquent
                                * otherwise mark it as delinquent */
                                if (DateTime.Compare (calcDate, Convert.ToDateTime (_stmntDate)) !=
                                    0)
                                {
                                    delinquentInterest = delinquentInterest + interest;
                                }
                            }

                            decimal principal = tdysAmrtztn.Principal;

                            pymntApplctn = remainder;

                            /* Apply the payment to the principal */
                            remainder = ApplyPaymentToAmount (remainder, ref principal);

                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);
                            CalculateSpecificPaymentApplication (pymntApplctn,
                                                                 PaymentApplicationPropertyType.CurrentPrincipal);

                            /* Set the unpaid balance to the amortization */
                            tdysAmrtztn.Principal = principal;

                            /* Generate delinquent charges if the Principal was not covered in full */

                            /* Make sure that all payments have been taken into account before
                            * we consider the amount not covered in full */
                            if (principal > 0 && prcssIndx + 1 >= totalPayments)
                            {
                                /* If the statement Date is equal than the CalcDate
                                * it means that we have calculated everything up to this date
                                * so we don't consider the amortization amounts as delinquent
                                * otherwise mark it as delinquent */
                                if (DateTime.Compare (calcDate, Convert.ToDateTime (_stmntDate)) !=
                                    0)
                                {
                                    delinquentPrincipal = delinquentPrincipal + principal;
                                }
                            }
                        }

                        /* Two reasons may cause the ramainder to be greater than zero:
                        *
                        * 1. There is no amortization schedule for calcDate thus apply the remainder
                        * payment.
                        *			Or,
                        * 2. We found the amortization and applied the payment accordingly and there
                        * was still payment left. */
                        if (remainder > 0)
                        {
                            /* To apply the extra payment two circumstances are taken into account:
                            *
                            * 1. The client is current (he has no delayed payments). In this case
                            * the payment will be applied the capital from the last amortization
                            * to the first, and interest as well as tax will be calculated on the
                            * remainder principal for that amortization.
                            *
                            * 2. The client is not current. In this case, two things will be verified:
                            *
                            * -If the payment is not the total amount owed (principal + interest + vat)
                            * then the payment will be applied from the last amortization to the first
                            * and the interest and vat will be recalculated accordingly.
                            * -If the payment is the total amount owed then no recalculation is done,
                            * it is just simply applied to all the amortizations (principal + interest + vat). */
                            /* Holds if the client is current or not */
                            bool current = true;

                            /* If there are any delayed days, it means the user is not current */
                            if (DelayedDays > 0)
                            {
                                current = false;
                            }

                            /* If the user is current, then we go ahead and proceed
                            * to apply the payment to the principal of the last amortization
                            * to the principal of the first amortization */
                            if (current)
                            {
                                for (int i = _amortization.AmortizationTable.Count - 1; i >= 0; i--)
                                {
                                    AmortizationEntry amrtztn = _amortization.AmortizationTable[i];

                                    /* If the amortization date is greater than the calcDate
                                    * then go ahead and see if we can apply the remainder of the payment
                                    * to that amortization */
                                    if (DateUtilities.IsFirstDateGreaterThanSecondDate (amrtztn.Date,
                                                                                        calcDate))
                                    {
                                        pymntApplctn = remainder;

                                        /* I don not apply the payment to the tax since the interests are not
                                        * being charged and the tax is based on the interests */
                                        decimal principal = amrtztn.Principal;

                                        /* Apply the payment to the principal */
                                        remainder = ApplyPaymentToAmount (remainder, ref principal);

                                        pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);

                                        /* Set the new principal value after applying the
                                        * payment */
                                        amrtztn.Principal = principal;

                                        /* Recalculate the Interest and VAT using the new principal
                                        * value */
                                        RecalculateInterestAndVAT (amrtztn);
                                    }

                                    /* Exit the for if there is no more remainder */
                                    if (remainder <= 0)
                                        break;
                                }
                            }
                            else
                            {
                                /* The client is not current with his/her payments */
                                /* Holds the total amount owed */
                                decimal totalAmntOwed = 0m;

                                /* Calculate the toal amount owed from the last amortization
                                * to the first, skipping amortizations previous or on the
                                * calcDate */
                                for (int i = _amortization.AmortizationTable.Count - 1; i >= 0; i--)
                                {
                                    /* Get the current amortization */
                                    AmortizationEntry amrtztn = _amortization.AmortizationTable[i];

                                    /* Only account for the amortizations after the calcDate. This date
                                    * is the last date used to calculate the statement. */
                                    if (DateUtilities.IsFirstDateGreaterThanSecondDate (amrtztn.Date,
                                                                                        calcDate))
                                    {
                                        totalAmntOwed = totalAmntOwed + amrtztn.TotalPayment;
                                    }
                                }

                                /* Determine if we should apply the payment to all the amortizations
                                * only if it is more or equal */
                                if (remainder >= totalAmntOwed)
                                {
                                    /* Apply the payment to the amortizations */
                                    for (int i = _amortization.AmortizationTable.Count - 1; i >= 0;
                                    i--)
                                    {
                                        AmortizationEntry amrtztn = _amortization.AmortizationTable[i];

                                        /* If the amortization date is greater than the calcDate
                                        * then go ahead and see if we can apply the remainder of the payment
                                        * to that amortization */
                                        if (DateUtilities.IsFirstDateGreaterThanSecondDate (
                                            amrtztn.Date,
                                            calcDate))
                                        {
                                            pymntApplctn = remainder;

                                            /* Get the principal */
                                            decimal principal = amrtztn.Principal;

                                            /* Apply the payment to the principal */
                                            remainder = ApplyPaymentToAmount (remainder,
                                                                              ref principal);

                                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);

                                            /* Set the new principal value after applying the
                                            * payment */
                                            amrtztn.Principal = principal;

                                            /* Get the interest */
                                            decimal interest = amrtztn.Interest;

                                            /* Apply the payment to the interest */
                                            remainder = ApplyPaymentToAmount (remainder,
                                                                              ref interest);

                                            /* Set the new interest value after applying the
                                            * payment */
                                            amrtztn.Interest = interest;

                                            /* Get the VAT */
                                            decimal vat = amrtztn.Tax;

                                            /* Apply the payment to the VAT */
                                            remainder = ApplyPaymentToAmount (remainder, ref vat);

                                            /* Set the new vat value after applying the
                                            * payment */
                                            amrtztn.Tax = vat;
                                        }

                                        /* Exit the for if there is no more remainder */
                                        if (remainder <= 0)
                                            break;
                                    }
                                }
                                else
                                {
                                    /* If the remainder is not enough to cover the full
                                    * loan then:
                                    *
                                    /* Apply the payment to the amortizations and recalculate
                                    * the interst and vat values, since not all the loan has
                                    * been covered */
                                    for (int i = _amortization.AmortizationTable.Count - 1; i >= 0;
                                    i--)
                                    {
                                        AmortizationEntry amrtztn = _amortization.AmortizationTable[i];

                                        /* If the amortization date is greater than the calcDate
                                        * then go ahead and see if we can apply the remainder of the payment
                                        * to that amortization */
                                        if (DateUtilities.IsFirstDateGreaterThanSecondDate (
                                            amrtztn.Date,
                                            calcDate))
                                        {
                                            pymntApplctn = remainder;

                                            /* Get the principal */
                                            decimal principal = amrtztn.Principal;

                                            /* Apply the payment to the principal */
                                            remainder = ApplyPaymentToAmount (remainder,
                                                                              ref principal);

                                            pymntApplctn = GetAmoutApplied (pymntApplctn, remainder);

                                            /* Set the new principal value after applying the
                                            * payment */
                                            amrtztn.Principal = principal;

                                            /* Recalculate the Interest and VAT using the new principal
                                            * value */
                                            RecalculateInterestAndVAT (amrtztn);
                                        }

                                        /* Exit the for if there is no more remainder */
                                        if (remainder <= 0)
                                            break;
                                    }
                                }
                            }
                        }

                        /* Increment the index to process the next payment */
                        prcssIndx++;
                    } while ((prcssIndx < totalPayments));

                    /* If at the end of this calculation there is any delinquent balance
                    * we add one day to our DelayedDays, to indicate the user is delayed
                    * one more day covering the amounts that are due. If there is no
                    * delinquent balance, then we zero out the DelayedDays.
                    *
                    * NOTE: Although calculations are done using full blown decimal values,
                    * we truncate all decimal values after the second decimal.
                    */
                    delinquentPrincipal = NumberUtilities.RoundToEven (delinquentPrincipal, 2);
                    delinquentInterest = NumberUtilities.RoundToEven (delinquentInterest, 2);
                    delinquentVAT = NumberUtilities.RoundToEven (delinquentVAT, 2);
                    moratoryInterest = NumberUtilities.RoundToEven (moratoryInterest, 2);

                    if (delinquentPrincipal > 0 || delinquentInterest > 0
                        || delinquentVAT > 0 || moratoryInterest > 0)
                        DelayedDays++;
                    else
                        DelayedDays = 0;

                    calcDate = calcDate.AddDays (1);
                }

                /* Update the PaymentBalance */
                _paymentBalance = remainder;

                /* Now that we have calculated all the charges up to the statement date
                * we have to calculate the remainder of the amortization table, to
                * determine what are the Current Amortizations so we can let them
                * know. The amortization table is calculated a day after the statement
                * since the while loop might have calculated the amortization on the
                * day of the statement. */
                decimal currentInterest = 0.00m;
                decimal currentPrincipal = 0.00m;
                decimal currentVAT = 0.00m;

                foreach (AmortizationEntry amortization in _amortization.AmortizationTable)
                {
                    /* If the amortization date is grater or equal than the statement date
                    * then determine what the current Interest, Principal and VAT values
                    * are. The comparison has to be Grater Or Equal because there may
                    * be an amortization on the day of the statement day and that needs to
                    * be considered as current. */
                    if (DateUtilities.IsFirstDateGreaterOrEqualThanSecondDate (amortization.Date,
                                                                               Convert.ToDateTime (
                                                                                   _stmntDate)))
                    {
                        currentInterest = currentInterest + amortization.Interest;
                        currentPrincipal = currentPrincipal + amortization.Principal;
                        currentVAT = currentVAT + amortization.Tax;
                    }
                }

                /**************************************************************
                * After all calculations have been made. We won't recalculate *
                * the amortization table again, since we may need to know     *
                * what future payments may be.                                *
                * *************************************************************/

                /* Now just update the delinquent charges */
                _delinquentInterests = delinquentInterest;
                _delinquentPrincipal = delinquentPrincipal;
                _delinquentVAT = delinquentVAT;
                _moratoryInterests = moratoryInterest;

                /* Now update the current balances */
                _currentInterests = currentInterest;
                _currentPrincipal = currentPrincipal;
                _currentVAT = currentVAT;

                /* Update the commissions owed */
                _currentCommissions = commissions;
            }
            /* If the exception was thrown here, just pass it up */
            catch (ZiblerBusinessComponentsException ex)
            {
                throw;
            }
            /* Catch any Data Layer or other exception and throw an unkown exception */
            catch (Exception ex)
            {
                ZiblerBusinessComponentsUnknownException exc
                = new ZiblerBusinessComponentsUnknownException (ex);

                /* Throw the new exception */
                throw exc;
            }
        }