/// <summary> /// Updates the loan requests statuses in the database /// for all loan requests based on the NextStatusUpdate. /// Note that this function is inteded to perform automatic updates /// on loan requests. /// </summary> /// <param name="financialInstitution">Financial Institution</param> /// <param name="requestTime">Date/Time of the request</param> public void UpdateLoanRequestStatus(string financialInstitution, DateTime requestTime) { try { /* Get all the loan requests whose ContinueStatusUpdates is TRUE and * NextStatusUpdate is on the same requestTime date and * hour (only hour) or before this date and hour * and a state passed Aprobada and not in a final state */ ILoanRequestDAO loanRequestDAO = _daoFactory.GetLoanRequestDAO (); IInterestRateValueDAO interestRateValueDAO = _daoFactory.GetInterestRateValueDAO (); IVatDAO vatDAO = _daoFactory.GetVatDAO (); /* Normalize the date, so there are no seconds or minutes. * We only care for the hour */ DateTime nrmlzdDate = new DateTime (requestTime.Year, requestTime.Month, requestTime.Day, requestTime.Hour, 0, 0); /* Add one hour to compensate for the time difference * between Mexico time and Arizona time (where the servers * are located ) */ nrmlzdDate = nrmlzdDate.AddHours (1); /* Loans to update. Note that even though a next update date may exist for a loan, the loan will be selected if the state is any state behind or aprobada. If the loan is corriente, then it won't be selected until the next update date. */ IList<LoanRequest> loanReqts = loanRequestDAO.GetAutomaticUpdateLoans (financialInstitution, nrmlzdDate); /* If the loan requests is null return */ if (loanReqts == null) return; /* Check that there is at least one loan request. Otherwise return */ if (loanReqts.Count <= 0) return; /* Hash table to store unique Interest Rate Ids and the earliest date from * where their values are needed. This is to avoid getting the same * Interest Rates more than once if they are repeated. */ Hashtable hashIntRtDates = new Hashtable (); /* List of Interest Rate values for a given Interest Rate Id */ Hashtable hashIntRtValues = new Hashtable (); /* Earliest date from where the VAT values are needed */ DateTime? vatStart = null; /* Go through each loan request */ foreach (LoanRequest loanReq in loanReqts) { /* Iterate through the loans and get the unique Interest Rate Ids * along with the earliest date needed for the interest rate. * At the same time select the earliest VAT value needed. This is * to retreive all the interest rate values and VAT values in * less queries. */ foreach (Loan loan in loanReq.Loans) { /* Add the Interest Rate Id and the Loan StartDate * to the hashIntRtDates list. This list is used to minimize the number * of queries made to the database if the Interest Rate Id is the * same for multiple loans */ if (!hashIntRtDates.Contains (loan.InterestRate.Id)) { /* NOTE: that loan.InterestRate.Id, will generate a query to the * database */ hashIntRtDates.Add (loan.InterestRate.Id, loan.StartDate.Value); } /* Add the start date only if it is previous to the current one */ if (hashIntRtDates[loan.InterestRate.Id] == null) hashIntRtDates[loan.InterestRate.Id] = loan.StartDate.Value; else { /* Get the date associated to the Interest Rate */ DateTime currDate = Convert.ToDateTime ( hashIntRtDates[loan.InterestRate.Id]); /* Determine if there is another loan (loan.StartDate.Value) whose * date is earlier than the previously assigned to the Interest Rate Id. * If so (replace) then use this date as the new data so later we get * all the interest rate values from there */ bool replace = DateUtilities.IsFirstDateGreaterThanSecondDate (currDate, loan.StartDate.Value); if (replace) hashIntRtDates[loan.InterestRate.Id] = loan.StartDate.Value; } /* If we don't have a VAT date yet, use the current loan StartDate */ if (vatStart == null) vatStart = Convert.ToDateTime (loan.StartDate); else { /* Determine if the loan has an earlier date than the currently selected for * the VAT. If so, then this date should be used to search for the VAT */ bool replace = DateUtilities.IsFirstDateGreaterThanSecondDate ( vatStart.Value, loan.StartDate.Value); if (replace) vatStart = Convert.ToDateTime (loan.StartDate); } } } /* Get all the Interests and their values to be used to calculate * the statements for all the loans */ IDictionaryEnumerator en = hashIntRtDates.GetEnumerator (); while (en.MoveNext ()) { /* Interest Rate needed */ int intRateId = Convert.ToInt32 (en.Key); /* Values needed from this date */ DateTime dt = Convert.ToDateTime (en.Value); IList<InterestRateValue> list = interestRateValueDAO.GetInterestRateValuesForStatement (intRateId, dt, DateTime.Today); /* If the list is not null, then add it to the list */ if (list != null) { /* Add the values to a hash list and move on */ hashIntRtValues.Add (intRateId, list); } } /* Get all the VATs */ IList<VAT> vats = vatDAO.GetVATsForStatement (financialInstitution, vatStart.Value, DateTime.Today); /* If there are no VATs or Interest Rate Values return */ if (vats.Count <= 0 || hashIntRtValues.Count <= 0) return; /* Calculate the loan statements for all the loans previously selected * Adjust the Loan Request status based on the number of days * the loan request is delayed. * * Clasify the Loan Request based on the loan that has the most delayed * days as follows: * * Corriente - No Delays * Vencida - Delayed 1 to 3 days (including day 3) * ExtraJudicial - Delayed 4 to 89 days * JudicialAltoRiesgo - Delayed 90 or more * */ bool firstPass = true; foreach (LoanRequest loanRequest in loanReqts) { foreach (Loan loan in loanRequest.Loans) { /* Interest Rate values for the loan */ IList<InterestRateValue> intValues = (IList<InterestRateValue>)hashIntRtValues[loan.InterestRate.Id]; try { SetLoanRequestStatus (loanRequest, loan, DateTime.Today, vats, intValues, nrmlzdDate, firstPass); } catch { break; } } } } /* 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; } }
/// <summary> /// Gets the names of all financial institutions in the system /// </summary> /// <returns></returns> public IList<string> GetFinancialInstitutionNames() { try { IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); IList<string> institutions = null; institutions = financialInstitutionDAO.GetFinancialInstitutionNames (); return institutions; } /* 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; } }
/// <summary> /// Updates the Financial Institution in the system /// along with its memberships for applications. /// </summary> /// <param name="finInstToUpdate">finInstToUpdate</param> /// <param name="appMemberships">Fin Inst memberships</param> public void UpdateFinancialInstitution(FinancialInstitution finInstToUpdate, IList<ApplicationFinancialInstitutionMembership> appMemberships) { try { IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); IApplicationDAO applicationDAO = _daoFactory.GetApplicationDAO (); string oldName = financialInstitutionDAO.GetFinancialInstName (finInstToUpdate.Id); /* If the old name is not in the system, then the Financial * Institution must have been deleted */ if (oldName == "") throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); //Determine if we should check for the user name. bool checkForUserName = true; if (oldName == finInstToUpdate.Name) checkForUserName = false; //If the name has been changed, then we verified that the new one //is not already in the system. if (checkForUserName) { FinancialInstitution finInstExists = financialInstitutionDAO.GetFinancialInstitutionByName ( finInstToUpdate.Name); if (finInstExists != null) throw new ZiblerBusinessComponentsException ( Resources.FinancialInstitutionOperationsMsgFinancialInstitutionExists); } //Remove all membershipts. finInstToUpdate.ApplicationFinancialInstitutionMemberships.Clear (); //Get all the applications. //TODO: There are not too many applications, however this may cause issues // in future releases when applications are many IList<Application> applications = applicationDAO.FindAll (); //Add the memberships since we did not throw any exception foreach (Application application in applications) { bool found = false; int i = 0; while (found == false && i < appMemberships.Count) { /* If the selected membership contains the current * application, then add it as the membership. * Note that the passed membership objects only contain * the Name of the application */ if (application.Name == appMemberships[i].Application.Name) { /* Change the application to the current and * then add the membership */ appMemberships[i].Application = application; finInstToUpdate.AddApplicationFinancialInstitutionMembership ( appMemberships[i]); /* Exit the loop and try the next app */ found = true; } i++; } } DateTime? startDate = null; DateTime? endDate = null; /* To set the Main start and end Date, we will use the earliest * and the latest dates of all the memberships. */ foreach (ApplicationFinancialInstitutionMembership membership in finInstToUpdate.ApplicationFinancialInstitutionMemberships) { /* If we have a date, then we compare to see which one is earliest */ if (startDate != null) { bool keepDate = true; /* the Main membership range dates will be null, * so check for it */ if (membership.ValidFrom != null) { keepDate = DateUtilities.IsFirstDateGreaterOrEqualThanSecondDate ( membership.ValidFrom.Value, startDate.Value); } if (keepDate) { /* Do nothing, keep the date */ } else { /* Replace it */ startDate = membership.ValidFrom; } } else { startDate = membership.ValidFrom; } if (endDate != null) { bool keepDate = true; /* the Main membership range dates will be null, * so check for it */ if (membership.ValidUntil != null) { keepDate = DateUtilities.IsFirstDateGreaterOrEqualThanSecondDate ( endDate.Value, membership.ValidUntil.Value); } if (keepDate) { /* Do nothing, keep the date */ } else { /* Replace it */ endDate = membership.ValidUntil; } } else { endDate = membership.ValidUntil; } } /* Only do this if the dates where found, otherwise * rise an exception */ if (startDate != null && endDate != null) { /* Now that we have a start date and an end date, assign them to * the Main app membership */ foreach (ApplicationFinancialInstitutionMembership membership in finInstToUpdate.ApplicationFinancialInstitutionMemberships) { /* Assign the dates */ if (membership.Application.Name == "Main") { membership.ValidFrom = startDate; membership.ValidUntil = endDate; } } } else { /* Something really bad must have happened if we got here. * Add the error data*/ ZiblerBusinessComponentsUnknownException ex = new ZiblerBusinessComponentsUnknownException (); ex.Data.Add ("StartDate", startDate); ex.Data.Add ("EndDate", endDate); throw ex; } } /* 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; } }
/// <summary> /// Returns a list of the Application section that the Financial Institution/user /// is allowed to view. /// </summary> /// <param name="userName">User name</param> /// <param name="financialInstitution">Financiera</param> /// <returns>Application section names</returns> /// <exception cref="ZiblerBusinessComponentsException"/> public IList<string> RetrieveAuthorizedAppSection(string userName, string financialInstitution) { try { //DAO to access stored information IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); FinancialUser financialUser = financialUserDAO.FindByUserNameFinancialInst (userName, financialInstitution); IList<string> authorizedSections = new List<string> (); //If no user was found, then return false. if (financialUser == null) return authorizedSections; if (financialUser.Active == true) { if (financialUser.Username == userName) { if (financialUser.FinancialInstitution.Name == financialInstitution) { //Look through all the memberships foreach (ApplicationFinancialInstitutionMembership membership in financialUser.FinancialInstitution.ApplicationFinancialInstitutionMemberships) { if (membership.Active) { if (DateUtilities.IsCurrentDateWithinDateRange ( Convert.ToDateTime (membership.ValidFrom), Convert.ToDateTime (membership.ValidUntil))) { authorizedSections.Add (membership.Application.Name); } } } } } } return authorizedSections; } /* 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; } }
/// <summary> /// This function will determine if the Client Username /password/Financiera /// combination is valid /// </summary> /// <param name="userName">User name</param> /// <param name="password">Password (not hashed)</param> /// <param name="financialInstitution">Financiera</param> /// <returns>True if all data is valid, false if it is not.</returns> /// <exception cref="ZiblerBusinessComponentsException"/> public bool AuthenticateClientUser(string userName, string password, string financialInstitution) { try { //DAO to access stored information IClientDAO clientDAO = _daoFactory.GetClientDAO (); //The user name in this case is the CURP Client client = clientDAO.FindByCURPFinancialInst (userName, financialInstitution); //If no user was found, then return false. if (client == null) return false; string hashedPwd = Encryption.CreateHash (password); if (client.CURP == userName) { if (client.AccountPassword == hashedPwd) { if (client.FinancialInstitution.Name == financialInstitution) { foreach (ApplicationFinancialInstitutionMembership membership in client.FinancialInstitution.ApplicationFinancialInstitutionMemberships) { //TODO: HACK /* This is hardcoded in the code. We should remove it from here * and follow the same approach folloed in Zibler app */ if (membership.Application.Name == "Clients") { bool withinRange = DateUtilities.IsCurrentDateWithinDateRange ( Convert.ToDateTime (membership.ValidFrom), Convert.ToDateTime (membership.ValidUntil)); if (withinRange) { if (membership.Active) { return true; } } } } return true; } } } return false; } /* 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; } }
/// <summary> /// This function will determine if the Financial User and the Financial Institution /// has the right to access a specific section of the application /// </summary> /// <param name="userName">User Name</param> /// <param name="financialInstitution">Financiera</param> /// <param name="applicationSection">Section to be accessed</param> /// <returns>True if the user / financial institution can access the section, false if not.</returns> /// <exception cref="ZiblerBusinessComponentsException"/> public bool AuthorizeFinancialUserToAppSection(string userName, string financialInstitution, string applicationSection) { try { //DAO to access stored information IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); FinancialUser financialUser = financialUserDAO.FindByUserNameFinancialInst (userName, financialInstitution); //If no user was found, then return false. if (financialUser == null) return false; if (financialUser.Active == true) { if (financialUser.Username == userName) { if (financialUser.FinancialInstitution.Name == financialInstitution) { //Look through all the memberships and compare against the one that has //been provided foreach (ApplicationFinancialInstitutionMembership membership in financialUser.FinancialInstitution.ApplicationFinancialInstitutionMemberships) { //If found, now verify it is still valid if (membership.Application.Name == applicationSection) { if (membership.Active) { if (DateUtilities.IsCurrentDateWithinDateRange ( Convert.ToDateTime (membership.ValidFrom), Convert.ToDateTime (membership.ValidUntil))) { return true; } } } } } } } return false; } /* 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; } }
/// <summary> /// Generates the new password. /// </summary> /// <param name="financialInstitutionName">Name of the financial institution.</param> /// <param name="curp">The curp.</param> /// <param name="email">The email.</param> /// <returns>Generated password (not hashed)</returns> public string ClientGenerateNewPassword(string financialInstitutionName, string curp, string email) { try { //DAO to access stored information IClientDAO clientDAO = _daoFactory.GetClientDAO (); Client client = clientDAO.FindByCURPFinancialInst (curp, financialInstitutionName); if (client == null) { throw new ZiblerBusinessComponentsException ( Resources.SecurityOperationsMsgPasswordRecoveryFailed); } else { if (client.ContactInformation.Email != email) { throw new ZiblerBusinessComponentsException ( Resources.SecurityOperationsMsgPasswordRecoveryFailed); } else { int passwordMinSize = 10; int passwordMaxSize = 11; string password = PasswordUtilities.Generate (passwordMinSize, passwordMaxSize); string hash = Encryption.CreateHash (password); client.AccountPassword = hash; return password; } } } /* 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; } }
/// <summary> /// Adds a new Loan to a loan request /// </summary> /// <param name="financialInstitutionName">financialInstitution</param> /// <param name="loanRequest">loanRequest</param> /// <param name="workingCapitalLoan">workingCapitalLoan</param> /// <param name="interestRateId">interestRateId</param> /// <remarks>This function won't change the balances in the Credit lines. This is because /// when a new loan is created, the Loan Request has not been completed. I will only update /// the amounts once the Loan Request has been completed or when they update a Loan Amount and the /// loan request is completed.</remarks> public void CreateNewLoanInLoanRequest(string financialInstitutionName, LoanRequest loanRequest, Loan loan, int interestRateId) { try { IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); IInterestRateDAO interestRateDAO = _daoFactory.GetInterestRateDAO (); /* Check that the loan has a valid amount */ if (loan.LoanedAmount <= 0) { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgInvalidLoanAmount); } //First we determine if we need to use default values for the loan, //of if this values were provided. This values will only be provided //if the user has the authority to do so. //If it is an Administrator, they may choose to leave the Start Date Blank //so the system will determine the Start Date automatically, however, they //may still want to override the default parameters, that is why I check for //the Interest Rate Id. Interest Rate Id won't be reported if they have not //selected one. if (loan.StartDate == null && interestRateId == 0) { FinancialInstitution financialInstitution = financialInstitutionDAO. GetFinancialInstitutionByName (financialInstitutionName); //TODO: If enforce //Look for the Loan Bracket. if (!financialInstitution.LoanBrackets.IsEmpty) { //We need to know what was the last request from the client //to whom the Loan Request belongs to. //TODO: It may be a better idea to calculate the max amount // using the database, rather than retrieven the records and // performing the operation here. Client client = loanRequest.Client; decimal maxTotalAmount = 0m; foreach (LoanRequest existingLoanRequest in client.LoanRequests) { //In theory all loan requests must be paid before they allow //the client to get another loan. The system checks for this before //allow them to register a new loan request, so technically I should //only be looking for Pagada. if ((existingLoanRequest.LoanRequestStatus == LoanRequestStatus.Aprobada) || (existingLoanRequest.LoanRequestStatus == LoanRequestStatus.Corriente) || (existingLoanRequest.LoanRequestStatus == LoanRequestStatus.Vencida) || existingLoanRequest.LoanRequestStatus == LoanRequestStatus.ExtraJudicial || existingLoanRequest.LoanRequestStatus == LoanRequestStatus.JudicialAltoRiesgo || existingLoanRequest.LoanRequestStatus == LoanRequestStatus.Pagada) { decimal loanReqTotalAmount = 0.0m; foreach (Loan existingLoan in existingLoanRequest.Loans) { loanReqTotalAmount = loanReqTotalAmount + existingLoan.LoanedAmount; } //If this is higher, then use it. if (loanReqTotalAmount > maxTotalAmount) maxTotalAmount = loanReqTotalAmount; } } //Order the loan brackets IList<LoanBracket> orderLoanBrackets = new List<LoanBracket> (); //Copy the list to a structure that will make it easier to work with. foreach (LoanBracket existingLoanBracket in financialInstitution.LoanBrackets) { orderLoanBrackets.Add (existingLoanBracket); } // Sorting: Bubble Sort for (int i = orderLoanBrackets.Count - 1; i >= 0; i--) { for (int j = 1; j <= i; j++) { if (orderLoanBrackets[j - 1].MinimumAmount > orderLoanBrackets[j].MinimumAmount) { LoanBracket temp = orderLoanBrackets[j - 1]; orderLoanBrackets[j - 1] = orderLoanBrackets[j]; orderLoanBrackets[j] = temp; } } } decimal maxAmountAllowed = 0; decimal minAmountAllowed = 0; LoanParameter loanParameterToUse = null; //It is a new loan request, then use the lowest bracket if (maxTotalAmount <= 0) { //Take the first loan bracket. I would not be here //if there was not at least one bracket. maxAmountAllowed = orderLoanBrackets[0].MaximumAmount; minAmountAllowed = orderLoanBrackets[0].MinimumAmount; foreach (LoanParameter loanParamInBracket in orderLoanBrackets[0].LoanParameters) { if (loanParamInBracket.LoanType == loan.LoanType) { loanParameterToUse = loanParamInBracket; break; } } } else { bool bracketFound = false; //Search for the appropriate bracket. for (int i = 0; i < orderLoanBrackets.Count; i++) { decimal currentMaxAmnt = orderLoanBrackets[i].MaximumAmount; decimal currentMinAmnt = orderLoanBrackets[i].MinimumAmount; //If we have found the bracket for the maximum amount //the user has ever borrowed, then we step up to the next //bracket. if (maxTotalAmount <= currentMaxAmnt && maxTotalAmount >= currentMinAmnt) { //indicate we have found a bracket for the max amount //ever borrowd bracketFound = true; //If there is another Loan Bracket if (i + 1 <= orderLoanBrackets.Count) { maxAmountAllowed = orderLoanBrackets[i + 1].MaximumAmount; minAmountAllowed = orderLoanBrackets[i + 1].MinimumAmount; foreach (LoanParameter loanParamInBracket in orderLoanBrackets[i + 1].LoanParameters) { if (loanParamInBracket.LoanType == loan.LoanType) { loanParameterToUse = loanParamInBracket; break; } } } else { //If there are no more brackets //use this one. maxAmountAllowed = orderLoanBrackets[i].MaximumAmount; minAmountAllowed = orderLoanBrackets[i].MinimumAmount; foreach (LoanParameter loanParamInBracket in orderLoanBrackets[i].LoanParameters) { if (loanParamInBracket.LoanType == loan.LoanType) { loanParameterToUse = loanParamInBracket; break; } } } } } //If there are brackets registered in the system //but we could not find one which would fit the maximum //amount the client have ever requested then, we will simply //use the first one. We will then leave it up to an //administrator to change the loan amounts. if (!bracketFound) { //Take the first loan bracket. maxAmountAllowed = orderLoanBrackets[0].MaximumAmount; minAmountAllowed = orderLoanBrackets[0].MinimumAmount; foreach (LoanParameter loanParamInBracket in orderLoanBrackets[0].LoanParameters) { if (loanParamInBracket.LoanType == loan.LoanType) { loanParameterToUse = loanParamInBracket; break; } } } } //Now that we have the data we will use for max/min amounts //and parameters we have to run a check to make sure the user //is within the min and max parameters. decimal amntAlrdyRqsted = 0m; foreach (Loan requestLoan in loanRequest.Loans) { //Only account for the loans that are not the same. //other wise I will end up counting twice. if (requestLoan.Id != loan.Id) amntAlrdyRqsted = amntAlrdyRqsted + requestLoan.LoanedAmount; } decimal amntCheck = loan.LoanedAmount + amntAlrdyRqsted; //if we are within boundaries if (amntCheck <= maxAmountAllowed && amntCheck >= minAmountAllowed) { //There no loan parameters setup for //the loan bracket if (loanParameterToUse == null) { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgNoParameterExistsForLoanBracket); } //Setup the parameters for the loan. loan.AmortizationTableType = loanParameterToUse.AmortizationTableType; loan.GracePeriod = loanParameterToUse.GracePeriod; loan.GrossEarningsMargin = loanParameterToUse.GrossEarningsMargin; loan.NumberOfAmortizations = loanParameterToUse.NumberOfAmortizations; loan.OverdueRateFactor = loanParameterToUse.OverdueRateFactor; loan.OverdueRateAmount = loanParameterToUse.OverdueRateAmount; loan.PaymentFrequency = loanParameterToUse.PaymentFrequency; loan.DelayedDays = 0; //Now get the interest rate loan.InterestRate = loanParameterToUse.InterestRate; //Get the applicable commissions foreach (LoanCommission commissionToApply in loanParameterToUse.LoanCommissions) { LoanApplicableCommission newCommission = new LoanApplicableCommission (); newCommission.Amount = commissionToApply.Amount; newCommission.Concept = commissionToApply.Concept; newCommission.RateOverAmount = commissionToApply.RateOverAmount; loan.AddLoanApplicableCommission (newCommission); } //Now that we have set the loan properties, we will add it to the //loan request. loanRequest.AddLoan (loan); } else { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgAmountOutOfBoundariesForBracket, minAmountAllowed.ToString ("C"), maxAmountAllowed.ToString ("C"))); } } else { bool defaultParamFound = false; //If the loan bracket was not found, look for the default parameters foreach (LoanParameter existingParam in financialInstitution.LoanParameters) { //Look for the default parameter if (existingParam.IsDefault && existingParam.LoanType == loan.LoanType) { defaultParamFound = true; loan.AmortizationTableType = existingParam.AmortizationTableType; loan.GracePeriod = existingParam.GracePeriod; loan.GrossEarningsMargin = existingParam.GrossEarningsMargin; loan.NumberOfAmortizations = existingParam.NumberOfAmortizations; loan.OverdueRateFactor = existingParam.OverdueRateFactor; loan.OverdueRateAmount = existingParam.OverdueRateAmount; loan.PaymentFrequency = existingParam.PaymentFrequency; loan.DelayedDays = 0; //Now get the interest rate loan.InterestRate = existingParam.InterestRate; //Get the applicable commissions foreach (LoanCommission commissionToApply in existingParam.LoanCommissions) { LoanApplicableCommission newCommission = new LoanApplicableCommission (); newCommission.Amount = commissionToApply.Amount; newCommission.Concept = commissionToApply.Concept; newCommission.RateOverAmount = commissionToApply.RateOverAmount; loan.AddLoanApplicableCommission (newCommission); } break; } } if (defaultParamFound) { loanRequest.AddLoan (loan); } //There are no Default parameters else { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgNoDefaultParameterExists); } } } else { //TODO: Add the loan applicable commissions //If values have been provided then we simply take the loan //and add it to the loan request. InterestRate interestRate = interestRateDAO.FindById (interestRateId); if (interestRate == null) { //No interest rate is available throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgNoInterestRateExists); } loan.InterestRate = interestRate; loanRequest.AddLoan (loan); } } /* 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; } }
/// <summary> /// Adds a new Collateral to the Loan Request /// </summary> /// <param name="loanRequest">loanRequest</param> /// <param name="collateral">collateral</param> public void CreateNewLoanRequestCollateral(LoanRequest loanRequest, Collateral collateral) { try { //If the loan request is not editable, then don't give them the option //to delete any data from it. if (loanRequest.LoanRequestStatus != LoanRequestStatus.Condicionada && loanRequest.LoanRequestStatus != LoanRequestStatus.Capturada && loanRequest.LoanRequestStatus != LoanRequestStatus.ExpedienteIntegrado) { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgCannotAddCollateral); } //Add the collateral if no exceptions were thrown loanRequest.AddCollateral (collateral); } /* 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; } }
/// <summary> /// Returns the next update date as one day after /// the date provided. /// </summary> /// <param name="nextUpdtDate">nextUpdtDate</param> /// <returns>Next update date.</returns> private DateTime GetNextUpdateDate(DateTime nextUpdtDate) { try { /* Set the next update day to one day after */ nextUpdtDate = nextUpdtDate.AddDays (1); /* * Now that we have added the days, we need to calculate * the hour. Valid hours are: * * 12am * 1am * 2am * 3am * 4am * 5am * * Look at the hour in the nextUpdtDate and add 1 hour to it. * Verify that the resulting hour is within range. * */ AmPm dateType = DateUtilities.GetDateAmPm (nextUpdtDate); /* Check and see that the date is not PM */ if (dateType == AmPm.PM) { /* If this is a PM, then roll back 12 hours, to * make it AM */ nextUpdtDate = nextUpdtDate.AddHours (-12); } /* At this point the hour should be AM only*/ /* Check the hour */ int hour = nextUpdtDate.Hour; /* If the hour is not any of the following then reset to 12. */ if (hour != 12 && hour != 1 && hour != 2 && hour != 3 && hour != 4 && hour != 5) { DateTime dateHldr = new DateTime (nextUpdtDate.Year, nextUpdtDate.Month, nextUpdtDate.Day, 12, nextUpdtDate.Minute, nextUpdtDate.Second); /* Check the hour is not PM */ AmPm checkTyp = DateUtilities.GetDateAmPm (dateHldr); /* Check and see that the date is not PM */ if (checkTyp == AmPm.PM) { dateHldr = dateHldr.AddHours (-12); } /* Set the hour to 12am */ nextUpdtDate = dateHldr; } /* If the hour is 5am, we need to substract 5 hours * to roll the hour to 12 am */ if (hour == 5) { nextUpdtDate = nextUpdtDate.AddHours (-5); } else { /* Add one hour */ nextUpdtDate = nextUpdtDate.AddHours (1); } return nextUpdtDate; } /* 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; } }
private int NextHour(int previousHour) { try { if (previousHour == 5) previousHour = 12; else { if (previousHour == 12) previousHour = 1; else { previousHour++; } } return previousHour; } /* 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; } }
/// <summary> /// Creates a new Financial Information /// </summary> /// <param name="financialInstitution">financialInstitution</param> /// <param name="loanRequest">loanRequest</param> /// <param name="financialInformation">financialInformation</param> public void CreateNewFinancialInfoInLoanRequest(string financialInstitution, LoanRequest loanRequest, FinancialInformation financialInformation) { try { loanRequest.FinancialInformation = financialInformation; } /* 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; } }
/// <summary> /// Verifies that a loan request transition is a valid transition /// from the old state to the new state. If not it will raise an exception /// </summary> /// <param name="oldStatus"></param> /// <param name="newStatus"></param> public void VerifyLoanRequestTransitionIsValid(LoanRequestStatus oldStatus, LoanRequestStatus newStatus) { try { string oldStatusName = Enum.GetName (typeof (LoanRequestStatus), oldStatus); string newStatusName = Enum.GetName (typeof (LoanRequestStatus), newStatus); if (oldStatus == LoanRequestStatus.Aprobada) { if (newStatus != LoanRequestStatus.Corriente && newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.Aprobada) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.Cancelada) { if (newStatus != LoanRequestStatus.Cancelada) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.Capturada) { if (newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.Rechazada && newStatus != LoanRequestStatus.ExpedienteIntegrado && newStatus != LoanRequestStatus.Capturada) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.Condicionada) { if (newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.Rechazada && newStatus != LoanRequestStatus.ExpedienteIntegrado && newStatus != LoanRequestStatus.Condicionada) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.Corriente) { if (newStatus != LoanRequestStatus.Vencida && newStatus != LoanRequestStatus.Pagada && newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.Corriente) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.EnCaptura) { if (newStatus != LoanRequestStatus.Capturada && newStatus != LoanRequestStatus.EnCaptura) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.ExpedienteIntegrado) { if (newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.Rechazada && newStatus != LoanRequestStatus.Condicionada && newStatus != LoanRequestStatus.Aprobada && newStatus != LoanRequestStatus.ExpedienteIntegrado) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.ExtraJudicial) { if (newStatus != LoanRequestStatus.JudicialAltoRiesgo && newStatus != LoanRequestStatus.Pagada && newStatus != LoanRequestStatus.Vencida && newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.ExtraJudicial) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.JudicialAltoRiesgo) { if (newStatus != LoanRequestStatus.Pagada && newStatus != LoanRequestStatus.Corriente && newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.JudicialAltoRiesgo) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.Pagada) { if (newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.Pagada) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.Rechazada) { if (newStatus != LoanRequestStatus.Rechazada) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else if (oldStatus == LoanRequestStatus.Vencida) { if (newStatus != LoanRequestStatus.Corriente && newStatus != LoanRequestStatus.ExtraJudicial && newStatus != LoanRequestStatus.Pagada && newStatus != LoanRequestStatus.Cancelada && newStatus != LoanRequestStatus.Vencida) { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } else { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgLoanStatusTransitionIsInvalid, oldStatusName, newStatusName)); } } /* 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; } }
/// <summary> /// Updates the loan request status based on the Loan ID for a /// loan belonging to the loanrequest /// </summary> /// <param name="financialInstitution">Financial institution</param> /// <param name="loanId">Loan Id</param> /// <param name="requestTime">Request Time</param> public void UpdateLoanRequestStatus(string financialInstitution, int loanId, DateTime requestTime) { try { ILoanDAO loanDAO = _daoFactory.GetLoanDAO (); IVatDAO vatDAO = _daoFactory.GetVatDAO (); IInterestRateValueDAO interestRateValueDAO = _daoFactory.GetInterestRateValueDAO (); bool calculate = true; /* Normalize the date, so there are no seconds or minutes. * We only care for the hour */ DateTime nrmlzdDate = new DateTime (requestTime.Year, requestTime.Month, requestTime.Day, 12, 0, 0); Loan loan = loanDAO.FindById (loanId); /* Check the statement date is not before the start */ if (!DateUtilities.IsFirstDateGreaterOrEqualThanSecondDate ( Convert.ToDateTime (requestTime), Convert.ToDateTime (loan.StartDate))) { calculate = false; } /* Get all the VATS within the range. Note that both loans should have * the same start date.*/ IList<VAT> vats = vatDAO.GetVATsForStatement (financialInstitution, Convert.ToDateTime (loan.StartDate), requestTime); /* Make sure there is at least one from the beginning of the loan */ bool vatFound = false; if (vats != null) { foreach (VAT vat in vats) { if (!DateUtilities.IsFirstDateGreaterThanSecondDate ( Convert.ToDateTime (vat.ValidFrom), Convert.ToDateTime (loan.StartDate))) { vatFound = true; break; } } } if (!vatFound) calculate = false; /* Make sure we can calculate the statement */ if (calculate) { bool firstPass = true; /* Loop through all the loans associated to the * Loan request */ foreach (Loan ln in loan.LoanRequest.Loans) { /* Get the interest Rate Values */ IList<InterestRateValue> interestValues = interestRateValueDAO.GetInterestRateValuesForStatement (ln.InterestRate.Id, ln.StartDate.Value, requestTime); /* Make sure there is at least one from the beginning of the loan */ bool intFound = false; if (interestValues != null) { foreach (InterestRateValue val in interestValues) { if (!DateUtilities.IsFirstDateGreaterThanSecondDate ( Convert.ToDateTime (val.ValidFrom), Convert.ToDateTime (loan.StartDate))) { intFound = true; break; } } } if (!intFound) calculate = false; try { if (calculate) { SetLoanRequestStatus (loan.LoanRequest, ln, DateTime.Today, vats, interestValues, nrmlzdDate, firstPass); firstPass = false; } } catch { break; } } } } /* 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; } }
/// <summary> /// Creates a new Financial User in the system /// </summary> /// <param name="financialInstitution">Financial Institution this user belongs to.</param> /// <param name="username">Username creating user</param> /// <param name="financialUser">Financial User to be created</param> /// <param name="applicationRoles">Application roles to be assigned to the financial user</param> public void CreateNewFinancialUser(string financialInstitutionName, string username, FinancialUser financialUser, IList<int> applicationRolesIds) { try { IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); IApplicationRoleDAO applicationRoleDAO = _daoFactory.GetApplicationRoleDAO (); //Make sure it does not exist in the system if (financialInstitutionDAO.FinancialUserExists (financialInstitutionName, financialUser.Username)) { throw new ZiblerBusinessComponentsException ( Resources.FinancialUserOperationsMsgFinancialUserExists); } //Get all the application roles. //TODO: There are not too many application roles, however this may cause issues // in future releases when application roles are defined by the financial institution IList<ApplicationRole> applicationRoles = applicationRoleDAO.FindAll (); //Hash the password. Encryption.EncryptProperties (financialUser); //Add the roles since we did not throw any exception foreach (ApplicationRole applicationRole in applicationRoles) { if (applicationRolesIds.Contains (applicationRole.Id)) financialUser.AddApplicationRole (applicationRole); } //Add the user to the financial institution FinancialInstitution financialInstitution = financialInstitutionDAO.GetFinancialInstitutionByName ( financialInstitutionName); /* If we could not find the financial institution * raise an exception */ if (financialInstitution == null) { throw new ZiblerBusinessComponentsUnknownException (); } else { financialInstitution.AddFinancialUser (financialUser); financialInstitutionDAO.MakePersistent (financialInstitution); } } /* 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; } }
/// <summary> /// Creates a new Business Client /// </summary> /// <param name="businessId">businessId</param> /// <param name="businessVersion">businessVersion</param> /// <param name="client">client to be created</param> public void CreateNewBusinessClient(int businessId, int businessVersion, BusinessClient client) { try { IBusinessInformationDAO businessInformationDAO = _daoFactory.GetBusinessInformationDAO (); //Get all the business products. Note that I retrieve all products in a batch base //and don't care about the number of records. This is because it is not likely //the business will contain hundreds of products BusinessInformation businessInformation = businessInformationDAO.FindByIdAndVersion ( businessId, businessVersion); if (businessInformation == null) throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); else { foreach (BusinessClient existingClient in businessInformation.BusinessClients) { if (existingClient.Name == client.Name) { //Throw an exception and indicate the product already exists throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgBusinessAlreadyHasClient); } } //Since no exception was thrown, then we add the new client to the list. businessInformation.AddBusinessClient (client); } } /* 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; } }
/// <summary> /// This function will determine if the Financial Username /password/Financiera /// combination is valid /// </summary> /// <param name="userName">User name</param> /// <param name="password">Password (not hashed)</param> /// <param name="financialInstitution">Financiera</param> /// <param name="fullName">Full name of the user</param> /// <returns>True if all data is valid, false if it is not.</returns> /// <exception cref="ZiblerBusinessComponentsException"/> public bool AuthenticateFinancialUser(string userName, string password, string financialInstitution, out string fullName) { try { //DAO to access stored information IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); /* Get the financial user from the given financialInstitution */ FinancialUser financialUser = financialUserDAO.FindByUserNameFinancialInst (userName, financialInstitution); /* Set the full name to empty */ fullName = ""; //If no user was found, then return false. if (financialUser == null) return false; string hashedPwd = Encryption.CreateHash (password); if (financialUser.Active == true) { if (financialUser.Username == userName) { if (financialUser.UserPassword == hashedPwd) { //TODO: Remove check. /* There is no need to check for the financial institution * again since it was done while retrieving the financialUser */ if (financialUser.FinancialInstitution.Name == financialInstitution) { /* Assign the full name */ fullName = financialUser.FullName; return true; } } } } /* If the user is not active, or his password or user name does not match * then return false */ return false; } /* 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; } }
/// <summary> /// Creates a new Loan Request Evaluations /// </summary> /// <param name="loanRequest">loanRequest</param> /// <param name="evaluations">evaluations</param> public void CreateNewLoanRequestEvaluations(LoanRequest loanRequest, string[,] evaluations) { try { //Clear the existing evaluations loanRequest.LoanRequestEvaluations.Clear (); for (int i = 0; i < evaluations.GetLength (0); i++) { ZiblerBusinessObjects.Loans.LoanRequestEvaluation newEvaluation = new LoanRequestEvaluation (); newEvaluation.Concept = evaluations[i,0]; newEvaluation.Complies = Convert.ToBoolean (evaluations[i,1]); //Add the evaluation loanRequest.AddLoanRequestEvaluation (newEvaluation); } if (loanRequest.MiscLoanRequestInformation.CreditReportRating == "-Seleccione una opción-") { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgNoCreditScoreSelected); } //Since the status was updated, then we call this function to make sure //all the other data is ok. UpdateLoanRequestInformation (loanRequest.Client.FinancialInstitution.Name, loanRequest); } /* 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; } }
/// <summary> /// Verifies a Financial User against the given roles. If the user /// belongs to at least one role, then the function will return true. If /// the user does not belong to any role, then it will return false. /// </summary> /// <param name="userName">User name</param> /// <param name="financialInstitution">Financiera</param> /// <param name="roles">Roles to be verified</param> /// <returns>True or false</returns> /// <exception cref="ZiblerBusinessComponentsException"/> public bool AuthorizeFinancialUserToRoles(string userName, string financialInstitution, IList<string> roles) { try { //DAO to access stored information IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); FinancialUser financialUser = financialUserDAO.FindByUserNameFinancialInst (userName, financialInstitution); //If no user was found, then return false. if (financialUser == null) return false; if (financialUser.Active == true) { if (financialUser.Username == userName) { if (financialUser.FinancialInstitution.Name == financialInstitution) { //Loop through all the roles that this user has access to foreach (ApplicationRole role in financialUser.ApplicationRoles) { //Verify against the given roles foreach (string comparissonRole in roles) { if (role.Name == comparissonRole) { //Return true as long as at least //one role matches return true; } } } } } } return false; } /* 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; } }
/// <summary> /// Creates a new Loan Request Transaction Log Entry /// </summary> /// <param name="loanRequest">loanRequest</param> /// <param name="transactionLog">transactionLog entry</param> public void CreateNewLoanRequestTransactionLogEntry(LoanRequest loanRequest, TransactionLogEntry transactionLog) { try { //Verify we are in a valid state if (loanRequest.LoanRequestStatus != LoanRequestStatus.Aprobada && loanRequest.LoanRequestStatus != LoanRequestStatus.Corriente && loanRequest.LoanRequestStatus != LoanRequestStatus.Vencida && loanRequest.LoanRequestStatus != LoanRequestStatus.ExtraJudicial && loanRequest.LoanRequestStatus != LoanRequestStatus.JudicialAltoRiesgo && loanRequest.LoanRequestStatus != LoanRequestStatus.Pagada) { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgCannotAddTransactionLogEntry); } /* Not that this will actually get all entries in the database for the Entry Logs */ loanRequest.AddTransactionLogEntry (transactionLog); } /* 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; } }
/// <summary> /// Generates the new password. /// </summary> /// <param name="financialInstitutionName">Name of the financial institution.</param> /// <param name="userName">The userName.</param> /// <param name="email">The email.</param> /// <returns>Generated password (not hashed)</returns> public string FinancialUserGenerateNewPassword(string financialInstitutionName, string userName, string email) { try { //DAO to access stored information IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); FinancialUser financialUser = financialUserDAO.FindByUserNameFinancialInst (userName, financialInstitutionName); if (financialUser == null) { throw new ZiblerBusinessComponentsException ( Resources.SecurityOperationsMsgPasswordRecoveryFailed); } else { if (financialUser.Email != email) { throw new ZiblerBusinessComponentsException ( Resources.SecurityOperationsMsgPasswordRecoveryFailed); } else { int passwordMinSize = 10; int passwordMaxSize = 11; string password = PasswordUtilities.Generate (passwordMinSize, passwordMaxSize); string hash = Encryption.CreateHash (password); financialUser.UserPassword = hash; return password; } } } /* 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; } }
/// <summary> /// Deletes a business product from a business information /// </summary> /// <param name="businessId">businessId</param> /// <param name="businessVersion">businessVersion</param> /// <param name="productId">productId</param> /// <param name="productVersion">productVersion</param> public void DeleteBusinessProduct(int businessId, int businessVersion, int productId, int productVersion) { try { //Get the two objects BusinessInformation businessInformation = GetBusinessInformation (businessId, businessVersion); if (businessInformation == null) throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); else { Product productToRemove = null; //TODO: Note that I get the whole list of items that belong to the // business Information. If there were many items I could possibly // cause some performance issues. foreach (Product existingProduct in businessInformation.Products) { if (existingProduct.Id == productId && existingProduct.Version == productVersion) { productToRemove = existingProduct; break; } } if (productToRemove == null) throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); else { businessInformation.RemoveProduct (productToRemove); } } } /* 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; } }
/// <summary> /// Returns a list of names from the roles a specific user /// is authorized for. /// </summary> /// <param name="userName">User name</param> /// <param name="financialInstitution"> Financial Institution</param> /// <returns>Roles names</returns> /// <exception cref="ZiblerBusinessComponentsException"/> public IList<string> RetrieveAuthorizedRolesNames(string userName, string financialInstitution) { try { //DAO to access stored information IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); FinancialUser financialUser = financialUserDAO.FindByUserNameFinancialInst (userName, financialInstitution); //If no user was found, then return false. if (financialUser == null) return null; IList<string> rolesNames = new List<string> (); if (financialUser.Active == true) { if (financialUser.Username == userName) { if (financialUser.FinancialInstitution.Name == financialInstitution) { //Loop through all the roles that this user has access to foreach (ApplicationRole role in financialUser.ApplicationRoles) { rolesNames.Add (role.Name); } } } } return rolesNames; } /* 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; } }
/// <summary> /// Delete Financial User /// </summary> /// <param name="finUserId">finUserId</param> /// <param name="finUserVer">finUserVer</param> public void DeleteFinancialUser(int finUserId, int finUserVer) { try { IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); FinancialUser financialUser = financialUserDAO.FindByIdAndVersion (finUserId, finUserVer); if (financialUser == null) throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); /* Check to see how many administradores are in the system */ int numberOfAdministradores = financialUserDAO.GetTotalOfAdministradores ( financialUser.FinancialInstitution.Name); bool remove = true; if (numberOfAdministradores <= MIN_NUMBER_ADMINISTRADORES) { /* Only one administrador left in the system */ foreach (ApplicationRole role in financialUser.ApplicationRoles) { /* If this user is the administrador, indicate * we cannot remove it */ if (role.Name == "Administrador") { remove = false; break; } } } if (remove) { //TODO: Not sure if I can just do the reference to the financial institution // from the Loan Bracket object FinancialInstitution financialInstitution = financialInstitutionDAO.GetFinancialInstitutionByName ( financialUser.FinancialInstitution.Name); financialInstitution.RemoveFinancialUser (financialUser); } else { throw new ZiblerBusinessComponentsException ( Resources.FinancialUserOperationsMsgFinancialUserNeedsAtLeastOneAdministradorAutorizador); } } /* 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; } }
/// <summary> /// Get A Financial Institution and memberships using the Id /// </summary> /// <param name="finInstId">finInstId</param> /// <returns>FinancialInstitution</returns> public FinancialInstitution GetFinancialInstitutionAndMemberships(int finInstId) { try { //Retrieve the client from the database. IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); FinancialInstitution financialInstitution = financialInstitutionDAO.GetFinancialInstitutionAndMemberships (finInstId); if (financialInstitution == null) throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); else { return financialInstitution; } } /* 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; } }
/// <summary> /// Retuns a Financial User based on the id, /// along with all its associated roles /// </summary> /// <param name="financialUserId">Financial User Id for the Financial User needed</param> /// <returns>Financial User</returns> public FinancialUser GetFinancialUserWithAssociations(int financialUserId) { try { IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); FinancialUser financialUser = financialUserDAO.GetFinancialUserWithAssociations ( financialUserId); if (financialUser == null) throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); else { return financialUser; } } /* 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; } }
/// <summary> /// Updates the Financial Institution in the system /// </summary> /// <param name="finInstToUpdate">finInstToUpdate</param> public void UpdateFinancialInstitution(FinancialInstitution finInstToUpdate) { try { IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); /* Just persist in the DB */ financialInstitutionDAO.MakePersistent (finInstToUpdate); } /* 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; } }
/// <summary> /// Update the FinancialUser and save it to the system /// </summary> /// <param name="financialUserToUpdate">FinancialUser to be updated</param> /// <param name="applicationRoleIds">List of application roles to be associated to this financial User</param> /// <exception cref="ZiblerBusinessComponentsException" /> public void UpdateFinancialUser(FinancialUser financialUserToUpdate, IList<int> applicationRoleIds) { try { IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); IFinancialUserDAO financialUserDAO = _daoFactory.GetFinancialUserDAO (); IApplicationRoleDAO applicationRoleDAO = _daoFactory.GetApplicationRoleDAO (); string oldUserName = financialUserDAO.GetFinancialUserUsername ( financialUserToUpdate.Id); string oldPassword = financialUserDAO.GetFinancialUserPassword ( financialUserToUpdate.Id); int numberOfAdministradores = financialUserDAO.GetTotalOfAdministradores ( financialUserToUpdate.FinancialInstitution.Name); //Variables used to verify the user must have at least one specific role bool mustBeAdministrador = false; if (oldUserName == "") throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); //Verify the minimum number of Aministradores users. if (numberOfAdministradores <= MIN_NUMBER_ADMINISTRADORES) { //Get all the available application roles. Note that these are not FinancialInstitution specific. //TODO: Perhaps in the future these should be financial institution specific. foreach (ApplicationRole role in financialUserToUpdate.ApplicationRoles) { if (role.Name == "Administrador") { mustBeAdministrador = true; break; } } } //Determine if we should check for the user name. bool checkForUserName = true; if (oldUserName == financialUserToUpdate.Username) checkForUserName = false; //If the user name has been changed, then we verified that the new one //is not already in the system. if (checkForUserName) { if (financialInstitutionDAO.FinancialUserExists ( financialUserToUpdate.FinancialInstitution.Name, financialUserToUpdate.Username)) { throw new ZiblerBusinessComponentsException ( Resources.FinancialUserOperationsMsgFinancialUserExists); } } //Remove all and just read the ones that should be associated. financialUserToUpdate.ApplicationRoles.Clear (); //Get all the application roles. //TODO: There are not too many application roles, however this may cause issues // in future releases when application roles are defined by the financial institution IList<ApplicationRole> applicationRoles = applicationRoleDAO.FindAll (); //Before we proceed to associate the application role to the user, we verify //if there should be administrator/autorizador in the list of selected Ids if (mustBeAdministrador) { bool administradorFound = false; foreach (int applicationRoleId in applicationRoleIds) { foreach (ApplicationRole role in applicationRoles) { if (role.Id == applicationRoleId) { if (role.Name == "Administrador") administradorFound = true; } } } if (mustBeAdministrador) { if (!administradorFound) { throw new ZiblerBusinessComponentsException ( Resources.FinancialUserOperationsMsgFinancialUserNeedsAtLeastOneAdministradorAutorizador); } } } /* If the old password is different, it means they changed it, so * go ahead and encrypt the new password, otherwise don't do anything */ if (oldPassword != financialUserToUpdate.UserPassword) { //Hash the password. Encryption.EncryptProperties (financialUserToUpdate); } //Add the roles since we did not throw any exception foreach (ApplicationRole applicationRole in applicationRoles) { if (applicationRoleIds.Contains (applicationRole.Id)) financialUserToUpdate.AddApplicationRole (applicationRole); } financialUserDAO.MakePersistent (financialUserToUpdate); } /* 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; } }
/// <summary> /// Creates a new financial institution in the system. /// </summary> /// <param name="newFinancialInst">New financial institution</param> public void CreateNewFinancialInstitution(FinancialInstitution newFinancialInst) { try { IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); /* Check the name is not repeated */ FinancialInstitution finInstExists = financialInstitutionDAO.GetFinancialInstitutionByName ( newFinancialInst.Name); if (finInstExists != null) throw new ZiblerBusinessComponentsException ( Resources.FinancialInstitutionOperationsMsgFinancialInstitutionExists); /* Add default miscellaneous parameters */ newFinancialInst.MiscellaneousParameters = new MiscellaneousParameters (); newFinancialInst.MiscellaneousParameters.ContractFirstClause = "ESTA ES LA PRIMERA CLAUSULA DEL CONTRATO"; newFinancialInst.MiscellaneousParameters.EnforceLoanBracketsInRequests = false; newFinancialInst.MiscellaneousParameters.LogUserActions = false; newFinancialInst.MiscellaneousParameters.RejectionLetterText = "Los factores que determinaron el rechazo de la " + "solicitud de crédito son, que no cumple con " + "los parámetros establecidos por nuestro " + "sistema crediticio"; /* Persist the financial institution */ financialInstitutionDAO.MakePersistent (newFinancialInst); } /* 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; } }
/// <summary> /// Updates an existing loan in a loan request. /// </summary> /// <param name="financialInstitutionName">financialInstitution</param> /// <param name="workingCapitalLoan">workingCapitalLoan</param> /// <param name="interestRateId">interestRateId</param> /// <remarks>This function will update the Credit Line amounts only if the /// loan request has been completed.</remarks> public void UpdateLoanRequestLoanInformation(string financialInstitutionName, Loan loan, int interestRateId, int loanId, int loanVersion) { try { IFinancialInstitutionDAO financialInstitutionDAO = _daoFactory.GetFinancialInstitutionDAO (); IInterestRateDAO interestRateDAO = _daoFactory.GetInterestRateDAO (); ILoanDAO loanDAO = _daoFactory.GetLoanDAO (); //Before anything happens, lets verify the Id's match the given loan Id. if ((loan.Id != loanId) || (loan.Version != loanVersion)) { throw new ZiblerBusinessComponentsException (Resources.RecordNotFound); } /* Check that the loan has a valid amount */ if (loan.LoanedAmount <= 0) { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgInvalidLoanAmount); } //If it is an Administrator, they may choose to leave the Start Date Blank //so the system will determine the Start Date automatically, however, they //may still want to override the default parameters, that is why I check for //the Interest Rate Id. Interest Rate Id won't be reported if they have not //selected one. if (loan.StartDate == null && interestRateId == 0) { FinancialInstitution financialInstitution = financialInstitutionDAO.GetFinancialInstitutionByName ( financialInstitutionName); //Look for the Loan Bracket. if (!financialInstitution.LoanBrackets.IsEmpty) { //We need to know what was the last request from the client //to whom the Loan Request belongs to. //TODO: It may be a better idea to calculate the max amount // using the database, rather than retrieven the records and // performing the operation here. Client client = loan.LoanRequest.Client; decimal maxTotalAmount = 0m; foreach (LoanRequest existingLoanRequest in client.LoanRequests) { /* Any loan request that has been approved is ok. The system allows * them to register loan requests even if they have not fully * paid the previous ones */ if (existingLoanRequest.LoanRequestStatus == LoanRequestStatus.Aprobada || existingLoanRequest.LoanRequestStatus == LoanRequestStatus.Corriente || existingLoanRequest.LoanRequestStatus == LoanRequestStatus.Vencida || existingLoanRequest.LoanRequestStatus == LoanRequestStatus.ExtraJudicial || existingLoanRequest.LoanRequestStatus == LoanRequestStatus.JudicialAltoRiesgo || existingLoanRequest.LoanRequestStatus == LoanRequestStatus.Pagada) { decimal loanReqTotalAmount = 0.0m; foreach (Loan existingLoan in existingLoanRequest.Loans) { loanReqTotalAmount = loanReqTotalAmount + existingLoan.LoanedAmount; } //If this is higher, then use it. if (loanReqTotalAmount > maxTotalAmount) maxTotalAmount = loanReqTotalAmount; } } //Order the loan brackets IList<LoanBracket> orderLoanBrackets = new List<LoanBracket> (); //Copy the list to a structure that will make it easier to work with. foreach (LoanBracket existingLoanBracket in financialInstitution.LoanBrackets) { orderLoanBrackets.Add (existingLoanBracket); } // TODO: Improve sorting algorithm // Sorting: Bubble Sort for (int i = orderLoanBrackets.Count - 1; i >= 0; i--) { for (int j = 1; j <= i; j++) { if (orderLoanBrackets[j - 1].MinimumAmount > orderLoanBrackets[j].MinimumAmount) { LoanBracket temp = orderLoanBrackets[j - 1]; orderLoanBrackets[j - 1] = orderLoanBrackets[j]; orderLoanBrackets[j] = temp; } } } decimal maxAmountAllowed = 0; decimal minAmountAllowed = 0; LoanParameter loanParameterToUse = null; //It is a new loan request, then use the lowest bracket if (maxTotalAmount <= 0) { //Take the first loan bracket. I would not be here //if there was not at least one bracket. maxAmountAllowed = orderLoanBrackets[0].MaximumAmount; minAmountAllowed = orderLoanBrackets[0].MinimumAmount; foreach (LoanParameter loanParamInBracket in orderLoanBrackets[0].LoanParameters) { if (loanParamInBracket.LoanType == loan.LoanType) { loanParameterToUse = loanParamInBracket; break; } } } else { bool bracketFound = false; //Search for the appropriate bracket. for (int i = 0; i < orderLoanBrackets.Count; i++) { decimal currentMaxAmnt = orderLoanBrackets[i].MaximumAmount; decimal currentMinAmnt = orderLoanBrackets[i].MinimumAmount; //If we have found the bracket for the maximum amount //the user has ever borrowed, then we step up to the next //bracket. if (maxTotalAmount <= currentMaxAmnt && maxTotalAmount >= currentMinAmnt) { //indicate we have found a bracket for the max amount //ever borrowd bracketFound = true; //If there is another Loan Bracket if (i + 1 <= orderLoanBrackets.Count) { maxAmountAllowed = orderLoanBrackets[i + 1].MaximumAmount; minAmountAllowed = orderLoanBrackets[i + 1].MinimumAmount; foreach (LoanParameter loanParamInBracket in orderLoanBrackets[i + 1].LoanParameters) { if (loanParamInBracket.LoanType == loan.LoanType) { loanParameterToUse = loanParamInBracket; break; } } } else { //If there are no more brackets //use this one. maxAmountAllowed = orderLoanBrackets[i].MaximumAmount; minAmountAllowed = orderLoanBrackets[i].MinimumAmount; foreach (LoanParameter loanParamInBracket in orderLoanBrackets[i].LoanParameters) { if (loanParamInBracket.LoanType == loan.LoanType) { loanParameterToUse = loanParamInBracket; break; } } } } } //If there are brackets registered in the system //but we could not find one which would fit the maximum //amount the client have ever requested then, we will simply //use the first one. We will then leave it up to an //administrator to change the loan amounts. if (!bracketFound) { //Take the first loan bracket. maxAmountAllowed = orderLoanBrackets[0].MaximumAmount; minAmountAllowed = orderLoanBrackets[0].MinimumAmount; foreach (LoanParameter loanParamInBracket in orderLoanBrackets[0].LoanParameters) { if (loanParamInBracket.LoanType == loan.LoanType) { loanParameterToUse = loanParamInBracket; break; } } } } //Now that we have the data we will use for max/min amounts //and parameters we have to run a check to make sure the user //is within the min and max parameters. decimal amntAlrdyRqsted = 0m; foreach (Loan requestLoan in loan.LoanRequest.Loans) { //Only account for the loans that are not the same. //other wise I will end up counting twice. if (requestLoan.Id != loan.Id) amntAlrdyRqsted = amntAlrdyRqsted + requestLoan.LoanedAmount; } decimal amntCheck = loan.LoanedAmount + amntAlrdyRqsted; //if we are within boundaries if (amntCheck <= maxAmountAllowed && amntCheck >= minAmountAllowed) { if (loanParameterToUse == null) //There no loan parameters setup for the loan bracket throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgNoParameterExistsForLoanBracket); //Setup the parameters for the loan. loan.AmortizationTableType = loanParameterToUse.AmortizationTableType; loan.GracePeriod = loanParameterToUse.GracePeriod; loan.GrossEarningsMargin = loanParameterToUse.GrossEarningsMargin; loan.NumberOfAmortizations = loanParameterToUse.NumberOfAmortizations; loan.OverdueRateFactor = loanParameterToUse.OverdueRateFactor; loan.OverdueRateAmount = loanParameterToUse.OverdueRateAmount; loan.PaymentFrequency = loanParameterToUse.PaymentFrequency; //Now get the interest rate loan.InterestRate = loanParameterToUse.InterestRate; /* Clear any previous commissions */ loan.ClearAllApplicableCommissions (); //Get the applicable commissions foreach (LoanCommission commissionToApply in loanParameterToUse.LoanCommissions) { LoanApplicableCommission newCommission = new LoanApplicableCommission (); newCommission.Amount = commissionToApply.Amount; newCommission.Concept = commissionToApply.Concept; newCommission.RateOverAmount = commissionToApply.RateOverAmount; loan.AddLoanApplicableCommission (newCommission); } } else { throw new ZiblerBusinessComponentsException ( String.Format ( Resources.LoanRequestOperationsMsgAmountOutOfBoundariesForBracket, minAmountAllowed.ToString ("C"), maxAmountAllowed.ToString ("C"))); } } /* There are no brackets */ else { bool defaultParamFound = false; //If the loan bracket was not found, look for the default parameters foreach (LoanParameter existingParam in financialInstitution.LoanParameters) { //Look for the default parameter for this type of loan. if (existingParam.IsDefault && existingParam.LoanType == loan.LoanType) { defaultParamFound = true; loan.AmortizationTableType = existingParam.AmortizationTableType; loan.GracePeriod = existingParam.GracePeriod; loan.GrossEarningsMargin = existingParam.GrossEarningsMargin; loan.NumberOfAmortizations = existingParam.NumberOfAmortizations; loan.OverdueRateFactor = existingParam.OverdueRateFactor; loan.OverdueRateAmount = existingParam.OverdueRateAmount; loan.PaymentFrequency = existingParam.PaymentFrequency; //Now get the interest rate loan.InterestRate = existingParam.InterestRate; /* Clear any applicable commissions */ loan.ClearAllApplicableCommissions (); //Get the applicable commissions foreach (LoanCommission commissionToApply in existingParam.LoanCommissions) { LoanApplicableCommission newCommission = new LoanApplicableCommission (); newCommission.Amount = commissionToApply.Amount; newCommission.Concept = commissionToApply.Concept; newCommission.RateOverAmount = commissionToApply.RateOverAmount; loan.AddLoanApplicableCommission (newCommission); } break; } } //There are no Default parameters if (!defaultParamFound) { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgNoDefaultParameterExists); } } } /* Use the parameters entered by the user. */ else { InterestRate interestRate = interestRateDAO.FindById (interestRateId); //No interest rate is available if (interestRate == null) { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgNoInterestRateExists); } loan.InterestRate = interestRate; } //After we have updated the loan information we need to update //the Credit Line amounts. //To do that we need to get the loan old amount first, to verify //if there is a new amount that we need to update. decimal oldAmount = loanDAO.GetOldLoanAmount (loan.Id); //If the amounts are different, then we will go ahead //and update the Credit Line. if (oldAmount != loan.LoanedAmount) { /* Update the loan request no matter what state it is. */ if (loan.LoanRequest.CreditLine != null) { CreditLine loanRequestCreditLine = loan.LoanRequest.CreditLine; //First we verify the status of the credit line. Only //active credit lines can be associated with LoanRequests if (loanRequestCreditLine.CreditLineStatus == CreditLineStatus.Suspendida) { throw new ZiblerBusinessComponentsException ( Resources.CreditLineOperationsMsgCreditLineMustBeActiveForAssociation); } /* Determine what values in the credit line to update based on the * status of the loan request */ if (loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.Capturada || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.Condicionada || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.EnCaptura || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.ExpedienteIntegrado) { //Restore credit line balance loanRequestCreditLine.AmountInRequestedLoans = loanRequestCreditLine.AmountInRequestedLoans - oldAmount; loanRequestCreditLine.AvailableAmount = loanRequestCreditLine.AvailableAmount + oldAmount; //If there is not enough money in the credit line to associate // we raise an exception indicating the problem. if (loanRequestCreditLine.AvailableAmount < loan.LoanedAmount) { throw new ZiblerBusinessComponentsException ( Resources.CreditLineOperationsMsgNotEnoughMoneyInCreditLine); } //Update credit line with new numbers. loanRequestCreditLine.AmountInRequestedLoans = loanRequestCreditLine.AmountInRequestedLoans + loan.LoanedAmount; loanRequestCreditLine.AvailableAmount = loanRequestCreditLine.AvailableAmount - loan.LoanedAmount; } else if (loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.Aprobada || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.Corriente || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.ExtraJudicial || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.JudicialAltoRiesgo || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.Vencida) { loanRequestCreditLine.AmountInAuthorizedLoans = loanRequestCreditLine.AmountInAuthorizedLoans - oldAmount; loanRequestCreditLine.AvailableAmount = loanRequestCreditLine.AvailableAmount + oldAmount; //If there is not enough money in the credit line to associate // we raise an exception indicating the problem. if (loanRequestCreditLine.AvailableAmount < loan.LoanedAmount) { throw new ZiblerBusinessComponentsException ( Resources.CreditLineOperationsMsgNotEnoughMoneyInCreditLine); } loanRequestCreditLine.AmountInAuthorizedLoans = loanRequestCreditLine.AmountInAuthorizedLoans + loan.LoanedAmount; loanRequestCreditLine.AvailableAmount = loanRequestCreditLine.AvailableAmount - loan.LoanedAmount; } } } /* Now lets update the payment schedule for the loan for those loans * that have been approved already */ if (loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.Aprobada || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.Corriente || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.ExtraJudicial || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.JudicialAltoRiesgo || loan.LoanRequest.LoanRequestStatus == LoanRequestStatus.Vencida) { //TODO: Should I do this here, or when they print the pagare. ZiblerFinanceUtilities util = new ZiblerFinanceUtilities (); AmortizationFactory amrtztnFctry = new AmortizationFactory (); if (loan.StartDate == null) loan.StartDate = loan.LoanRequest.LoanAuthorizationDate; else if (loan.StartDate != loan.LoanRequest.LoanAuthorizationDate) { throw new ZiblerBusinessComponentsException ( Resources.LoanRequestOperationsMsgLoanStartDateAndAuthorizationDateAreNotEqual); } /* After setting the checks and setting the start date, then calculate the end * date */ /* Calculate the Last payment date for this loan */ DateTime endDate = util.GetPaymentNumberDate ( Convert.ToDateTime (loan.StartDate), loan.NumberOfAmortizations, loan.PaymentFrequency, Country.Mexico); loan.EndDate = endDate; /* Calculate the payments for this loan, and save them to the database. * This is to ease the report operations later */ Amortization amortization = amrtztnFctry.CreateAmortization ( loan.AmortizationTableType, loan.LoanedAmount, loan.NumberOfAmortizations, loan.PaymentFrequency, 0, loan.GracePeriod, loan.StartDate.Value, 0); //Calculate the amortization. amortization.CalculateAmortizationTable (); /* Add the payment dates */ util.AddAmortizationPaymentDates (amortization.AmortizationTable, amortization.StartDate, amortization.PaymentFrequency, Country.Mexico); /* Remove all payment schedules. This will guarantee that only * the correct information will be stored in the database */ loan.RemoveAllPaymentSchedules (); /* Add the Payment Schedule */ foreach (AmortizationEntry entry in amortization.AmortizationTable) { PaymentSchedule newSchedule = new PaymentSchedule (); newSchedule.PaymentDate = entry.Date; newSchedule.PaymentNumber = entry.Number; loan.AddPaymentSchedule (newSchedule); } } } /* 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; } }