using BuddyFinance.Common.Encryption; using BuddyFinance.Common.Helpers; using BuddyFinance.Integration.Models; using BuddyFinance.Integration.Models.Enums; using BuddyFinance.Integration.Models.LoanOffers; using BuddyFinance.Integration.Models.LoanRequests; using BuddyFinance.Model; using Microsoft.VisualBasic; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; /* Created: 31 Aug 17 * Author: Tumelo * */ namespace BuddyFinance.Integration { public class LoanRequestIntegrator : BaseIntegrator { private new NotificationsIntegrator _notifications = new NotificationsIntegrator(); private ScoringIntegrator _scoringIntegrator = new ScoringIntegrator(); //Request loan public RequestLoanResult RequestLoan(RequestLoanRequest request) { request.BorrowerId = request.BorrowerId_.ToDecryptedInt(); var results = new RequestLoanResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Set().FirstOrDefault(m => m.Id == request.BorrowerId); if (request.Amount > 499) { if (profile.BankingDetail != null) { var offerIds = request.Offers.Select(m => m.LoanOfferId); var offers = db.LoanOffers.Where(m => offerIds.Contains(m.Id)).ToList(); var loanrequest = new LoanRequest { Amount = request.Amount, FirstPaymentDate = DateTime.Today.GetNextPaymentDate(), RequestedDate = DateTime.Now, Term = request.Term, TermTypeId = request.TermTypeId, BorrowerId = request.BorrowerId, LoanRequestStatusId = (int)LoanRequestStatusEnum.New, LoanRequestOffers = offers.Select(m => new LoanRequestOffer { //Comments = m.Comments, RequestDate = DateTime.Now, OfferStausId = (int)OfferStatusEnum.RequestSent, LoanOfferId = m.Id, // LoanRequestId = m.LoanRequestId, }).ToList() }; db.LoanRequests.Add(loanrequest); db.SaveChanges(); loanrequest.ReferenceNumber = ReferenceNumberGenerator.Generate(loanrequest.Id); db.SaveChanges(); if (profile != null) { var mailDetails = new Dictionary { { "[borrowerId]",profile.ProfileNumber }, {"[names]",profile.FullNames }, { "[reference]", loanrequest.ReferenceNumber}, { "[amount]", loanrequest.Amount.ToString("N2")}, //{ "[loanofferid]",loanreques} { "[loanofferrequestamount]", loanrequest.Amount.ToString()}, }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.LoanRequestRef.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, "Loan Request | Buddy Finance", null); } foreach (var offerRequest in request.Offers) { var offer = db.LoanOffers.Find(offerRequest.LoanOfferId); var lender = offer.Profile; var termType = db.TermTypes.Find(loanrequest.TermTypeId); //send email to lender; var mailDetails = new Dictionary { {"[names]", $"{profile.Name} {profile.Surname}" }, {"[lender]", lender.FullNames}, {"[amount]", loanrequest.Amount.ToString("N2")}, {"[interest]",offer.InterestRate.ToString()}, {"[duration]",$"{loanrequest.Term} {termType.Description}" }, {"[loanofferrequest]",loanrequest.Amount.ToString("N2") }, {"[borrowerId]", profile.ProfileNumber} }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.LoanOfferRequest.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(lender.EmailAddress, emailBody, "Loan Request | Buddy Finance", null); } results.Result = new NewLoanRequestResult { ReferenceNumber = loanrequest.ReferenceNumber, Id = loanrequest.Id }; results.ErrorMessage = "Success"; results.ErrorCode = (int)ResponseCodes.Success; } else { results.MustUpdateBanking = true; results.ErrorCode = (int)ResponseCodes.NotFound; results.ErrorMessage = "Sorry you cannot make a loan request until you update your banking details on your profile."; } } else { results.ErrorCode = (int)ResponseCodes.NotFound; results.ErrorMessage = "Loan Request less than 500 not allowed."; } } } catch (Exception ex) { results.ErrorCode = (int)ResponseCodes.Exception; results.ErrorMessage = ex.Message; } return results; } public GetLoanRequestsResult GetLoanRequests() { var result = new GetLoanRequestsResult(); try { using (var db = new BuddyFinanceDBEntities()) { var loanRequest = db.LoanRequests.OrderBy(i => i.RequestedDate).ToList().ConvertAll(m => new LoanRequestModel() { Amount = m.Amount, FirstPaymentDate = m.FirstPaymentDate, RequestedDate = m.RequestedDate, LoanRequestStatusId = m.LoanRequestStatusId, Term = m.Term, TermTypeId = m.TermTypeId, Id = m.Id, BorrowerId = m.BorrowerId, TermType = new Models.TermType { Id = m.TermType.Id, Description = m.TermType.Description }, Status = new Models.Status { Id = m.LoanRequestStatus.Id, Description = m.LoanRequestStatus.Description }, Offers = m.LoanRequestOffers.Select(k => new LoanRequestOfferModel { Id = k.Id, Comments = k.Comments, RequestDate = DateTime.Now, OfferStausId = (int)OfferStatusEnum.RequestSent, IsActive = k.IsActive, Status = new Models.Status { Id = k.OfferStatus.Id, Description = k.OfferStatus.Description }, LoanOfferId = k.LoanOfferId, LoanRequestId = k.LoanRequestId, }).ToList() }); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = loanRequest; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public GetLoanRequestsResult GetLoanRequests(int profileId) { var result = new GetLoanRequestsResult(); try { using (var db = new BuddyFinanceDBEntities()) { // var profilescore; var serviceFee = _fees[FeeTypesEnum.ServiceFee]; var initiationFee = _fees[FeeTypesEnum.LoanInitiationFee]; var loanRequests = new List(); db.LoanRequests.Where(m => m.BorrowerId == profileId) .OrderByDescending(i => i.RequestedDate) .ToList().ForEach(m => { var request = new LoanRequestModel { Amount = m.Amount, FirstPaymentDate = m.FirstPaymentDate, RequestedDate = m.RequestedDate, LoanRequestStatusId = m.LoanRequestStatusId, Term = m.Term, TermTypeId = m.TermTypeId, Id = m.Id, Id_ = m.Id.ToEncryptedString(), BorrowerId = m.BorrowerId, ReferenceNumber = m.ReferenceNumber, TermType = new Models.TermType { Id = m.TermType.Id, Description = m.TermType.Description }, Status = new Models.Status { Id = m.LoanRequestStatus.Id, Description = m.LoanRequestStatus.Description }, Offers = new List() }; m.LoanRequestOffers.ToList().ForEach(k => { //initiationFee.Amount = m.Amount > 1000 ? 1000 * (initiationFee.Percentage) // : m.Amount * initiationFee.Percentage; //var initialPayment = Financial.Pmt(k.LoanOffer.InterestRateInPercent / GlobalSetup.InterestType, m.Term, -m.Amount) + serviceFee.Amount + initiationFee.Amount; //var monthlyPayment = Financial.Pmt(k.LoanOffer.InterestRateInPercent / GlobalSetup.InterestType, m.Term, -m.Amount) + serviceFee.Amount; //var total = initialPayment + (monthlyPayment * (m.Term - 1)); initiationFee.Amount = m.Amount > 1000 ? initiationFee.AmountForPercentUse + (m.Amount * initiationFee.Percentage) : initiationFee.Amount; var interestAmount = m.Amount * k.LoanOffer.InterestRateInPercent; var interestPerMonth = (interestAmount / 6); var Total = (interestPerMonth * m.Term) + (serviceFee.Amount * m.Term) + initiationFee.Amount + m.Amount; var monthlyPayment = (Total / m.Term); var offer = new LoanRequestOfferModel { Id = k.Id, Comments = k.Comments, RequestDate = DateTime.Now, OfferStausId = (int)OfferStatusEnum.RequestSent, Status = new Models.Status { Id = k.OfferStatus.Id, Description = k.OfferStatus.Description }, LoanOfferId = k.LoanOfferId, LoanRequestId = k.LoanRequestId, Lender = k.LoanOffer.Profile.FullNames, interest = k.LoanOffer.InterestRate, InitialPayment = initiationFee.Amount, TotalPayment = Total, MonthlyPayment = monthlyPayment, LoanOffer = new Models.LoanOffers.LoanOfferModel { Lender = new Models.Profiles.Profile { Name = m.Profile.Name, Surname = m.Profile.Surname, ProfileNumber = m.Profile.ProfileNumber, }, } //get saved score and display it on the modal if only it exist. //ProfileScore = db.ProfileCreditRatingScores.Where(t => t.LoanRequestOffer.LoanRequestId == ) //ProfileScore = k.ProfileCreditRatingScores.Select(k = new ProfileCreditRatingScore //{ // DerivedScore = k. //}), }; request.Offers.Add(offer); }); loanRequests.Add(request); }); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = loanRequests; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = ex.Message; } return result; } public GetLoanRequestResult GetLoanRequest(int loanRequestID) { var getLoanRequestResult = new GetLoanRequestResult(); try { using (var db = new BuddyFinanceDBEntities()) { //var loanRequest = db.LoanRequests.FirstOrDefault(m => m.Id == loanRequestID); // var serviceFee = _fees[FeeTypesEnum.ServiceFee]; //var initiationFee = _fees[FeeTypesEnum.LoanInitiationFee]; //if (loanRequest != null) //{ // getLoanRequestResult.ErrorCode = (int)ResponseCodes.Success; // getLoanRequestResult.ErrorMessage = "Success"; // getLoanRequestResult.Result = new LoanRequestModel // { // Amount = loanRequest.Amount, // FirstPaymentDate = loanRequest.FirstPaymentDate, // RequestedDate = loanRequest.RequestedDate, // LoanRequestStatusId = loanRequest.LoanRequestStatusId, // Term = loanRequest.Term, // TermTypeId = loanRequest.TermTypeId, // Id = loanRequest.Id, // BorrowerId = loanRequest.BorrowerId, // TermType = new Models.TermType // { // Id = loanRequest.TermType.Id, // Description = loanRequest.TermType.Description // }, // Status = new Models.Status // { // Id = loanRequest.LoanRequestStatus.Id, // Description = loanRequest.LoanRequestStatus.Description // }, // Offers = loanRequest.LoanRequestOffers.Select(m => new LoanRequestOfferModel // { // Id = m.Id, // Amount = loanRequest.Amount, // Comments = m.Comments, // RequestDate = DateTime.Now, // OfferStausId = (int)OfferStatusEnum.RequestSent, // Status = new Models.Status // { // Id = m.OfferStatus.Id, // Description = m.OfferStatus.Description // }, // Lender = m.LoanOffer.Profile.FullNames, // LoanOfferId = m.LoanOfferId, // LoanRequestId = m.LoanRequestId, // interest = m.LoanOffer.InterestRate, // }).ToList() // //loanRequest.LoanRequestOffers.ToList().ForEach(k => // //{ // // initiationFee.Amount = m.Amount > 1000 ? 1000 * (initiationFee.Percentage) // // : m.Amount * initiationFee.Percentage; // // var initialPayment = Financial.Pmt(k.LoanOffer.InterestRateInPercent / GlobalSetup.InterestType, m.Term, -m.Amount) + serviceFee.Amount + initiationFee.Amount; // // var monthlyPayment = Financial.Pmt(k.LoanOffer.InterestRateInPercent / GlobalSetup.InterestType, m.Term, -m.Amount) + serviceFee.Amount; // // var total = initialPayment + (monthlyPayment * (m.Term - 1)); // // var offer = new LoanRequestOfferModel // // { // // Id = k.Id, // // Comments = k.Comments, // // RequestDate = DateTime.Now, // // OfferStausId = (int)OfferStatusEnum.RequestSent, // // Status = new Models.Status // // { // // Id = k.OfferStatus.Id, // // Description = k.OfferStatus.Description // // }, // // LoanOfferId = k.LoanOfferId, // // LoanRequestId = k.LoanRequestId, // // Lender = k.LoanOffer.Profile.FullNames, // // interest = k.LoanOffer.InterestRate, // // InitialPayment = initialPayment, // // TotalPayment = total, // // MonthlyPayment = monthlyPayment, // // }; // //}); // }; //} var serviceFee = _fees[FeeTypesEnum.ServiceFee]; var initiationFee = _fees[FeeTypesEnum.LoanInitiationFee]; //var loanRequests = new LoanRequestModel(); var loanRequests = db.LoanRequests.FirstOrDefault(m => m.Id == loanRequestID); //var Offers = new List(); if (loanRequests != null) { getLoanRequestResult.Result = new LoanRequestModel { Amount = loanRequests.Amount, FirstPaymentDate = loanRequests.FirstPaymentDate, RequestedDate = loanRequests.RequestedDate, LoanRequestStatusId = loanRequests.LoanRequestStatusId, Term = loanRequests.Term, TermTypeId = loanRequests.TermTypeId, Id = loanRequests.Id, Id_ = loanRequests.Id.ToEncryptedString(), BorrowerId = loanRequests.BorrowerId, Borrower = new Models.Profiles.Profile { ProfileNumber = loanRequests.Profile.ProfileNumber, }, TermType = new Models.TermType { Id = loanRequests.TermType.Id, Description = loanRequests.TermType.Description }, Status = new Models.Status { Id = loanRequests.LoanRequestStatus.Id, Description = loanRequests.LoanRequestStatus.Description }, Offers = new List(), }; loanRequests.LoanRequestOffers.ToList().ForEach(k => { initiationFee.Amount = loanRequests.Amount > 1000 ? initiationFee.AmountForPercentUse + (loanRequests.Amount * initiationFee.Percentage) : initiationFee.Amount; var interestAmount = loanRequests.Amount * k.LoanOffer.InterestRateInPercent; var interestPerMonth = (interestAmount / 6); var Total = (interestPerMonth * loanRequests.Term) + (serviceFee.Amount * loanRequests.Term) + initiationFee.Amount + loanRequests.Amount; var monthlyPayment = (Total / loanRequests.Term); //var initialPayment = Financial.Pmt(k.LoanOffer.InterestRateInPercent / GlobalSetup.InterestType, loanRequests.Term, -loanRequests.Amount) + serviceFee.Amount + initiationFee.Amount; //var monthlyPayment = Financial.Pmt(k.LoanOffer.InterestRateInPercent / GlobalSetup.InterestType, loanRequests.Term, -loanRequests.Amount) + serviceFee.Amount; // var initialPayment //var total = initialPayment + (monthlyPayment * (loanRequests.Term - 1)); var offer = new LoanRequestOfferModel { Id = k.Id, Comments = k.Comments, RequestDate = DateTime.Now, OfferStausId = (int)OfferStatusEnum.RequestSent, IOU_Accepted = k.IOU_Accepted, Status = new Models.Status { Id = k.OfferStatus.Id, Description = k.OfferStatus.Description }, LoanOfferId = k.LoanOfferId, LoanRequestId = k.LoanRequestId, Lender = k.LoanOffer.Profile.FullNames, interest = k.LoanOffer.InterestRate, InitialPayment = initiationFee.Amount, TotalPayment = Total, MonthlyPayment = monthlyPayment, LoanOffer = new LoanOfferModel { Lender = new Models.Profiles.Profile { Name = k.LoanOffer.Profile.Name, Surname = k.LoanOffer.Profile.Surname, ProfileNumber = k.LoanOffer.Profile.ProfileNumber, }, } }; getLoanRequestResult.Result.Offers.Add(offer); }); getLoanRequestResult.ErrorCode = (int)ResponseCodes.Success; getLoanRequestResult.ErrorMessage = "Success"; // getLoanRequestResult.Result = loanRequests; } else { getLoanRequestResult.ErrorCode = (int)ResponseCodes.NotFound; getLoanRequestResult.ErrorMessage = "Not found"; } } } catch (Exception ex) { getLoanRequestResult.ErrorCode = (int)ResponseCodes.Exception; getLoanRequestResult.ErrorMessage = ex.Message; } return getLoanRequestResult; } public AcceptLoanRequest AcceptLoanRequests(int loanRequestOfferId) { var acceptLoanRequest = new AcceptLoanRequest(); try { using (var db = new BuddyFinance.Model.BuddyFinanceDBEntities()) { var loanRequestOffer = db.LoanRequestOffers.Find(loanRequestOfferId); if (loanRequestOffer != null) { //change offer status if (loanRequestOffer.OfferStatus.Id == (int)OfferStatusEnum.RequestAccepted) { var request = loanRequestOffer.LoanRequest; var offer = loanRequestOffer.LoanOffer; if (offer.Balance >= request.Amount) { if (request.Amount <= offer.Balance) { loanRequestOffer.LoanOffer.Balance -= request.Amount; db.SaveChanges(); } var loanCalculatorResult = base.LoanCulculator(new Models.Profiles.LoanCalculatorModel { Amount = request.Amount, Duration = request.Term, Interest = offer.InterestRate }).Result; var loan = new BuddyFinance.Model.Loan { LoanAmount = request.Amount, LoanRequestId = loanRequestOffer.LoanRequestId, FirstRepaymentDate = loanCalculatorResult.FirstPaymentDate, LoanDuration = request.Term, TermTypeId = loanRequestOffer.LoanOffer.TermTypeId, BorrowerId = request.BorrowerId, LoanOfferId = loanRequestOffer.LoanOfferId, LoanStatusId = (int)LoanStatusEnum.Pending, CreatedDate = DateTime.Now, MonthlyInstallmentAmount = loanCalculatorResult.MonthlyPayment, InitialPaymentAmount = loanCalculatorResult.InitialPayment, TotalPayment = loanCalculatorResult.TotalPayment, }; db.Loans.Add(loan); loanRequestOffer.LoanRequest.LoanRequestStatusId = (int)LoanRequestStatusEnum.Approved; loanRequestOffer.OfferStausId = (int)OfferStatusEnum.OfferAccepted; loanRequestOffer.IOU_Accepted = true; var message = "The offer is not accepted"; foreach (var offer__ in request.LoanRequestOffers.Where(m => m.Id != loanRequestOfferId).ToList()) { offer__.OfferStausId = (int)OfferStatusEnum.Reject; db.SaveChanges(); var mailDetail = new Dictionary { { "[names]", $"{offer__.LoanOffer.Profile.Name} {offer__.LoanOffer.Profile.Surname}" }, { "[id]", $"{offer__.LoanOffer.Id}"}, { "[comment]", $"{message}"} }; var templateTexts = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.LoanOfferReject.ToString() + ".txt"); var emailBod = mailDetail.Aggregate(templateTexts, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(offer__.LoanOffer.Profile.EmailAddress, emailBod, "Loan Offer Status | Buddy Finance", null); } if (loanRequestOffer.LoanOffer.Balance > 0 && loanRequestOffer.LoanOffer.Balance < 500) { // loanRequestOffer.LoanOffer.Balance -= loanRequestOffer.LoanOffer.Balance; var balance = loanRequestOffer.LoanOffer.Balance; // loanRequestOffer.LoanOffer.Profile.AvailableFunds += balance; loanRequestOffer.LoanOffer.Balance -= loanRequestOffer.LoanOffer.Balance; //save offer transaction var transactionsInt = new TransactionsIntegrator(); var addResult = transactionsInt.SaveTransaction(new Models.Transactions.Transaction { TransactionId = 0, Amount = balance, Description = "Available balance credited for loan offer ID:" + loanRequestOffer.LoanOffer.Id, Reference = "", TransactionDate = DateTime.Now,//loanoffer.DateCreated, ProfileId = loanRequestOffer.LoanOffer.ProfileId, TransactionStatusId = (int)TransactionStatusEnum.Success, TransactionTypeId = (int)TransactionTypeEnum.Credit, ProfileTypeId = (int)ProfileTypeEnum.Lender }); db.SaveChanges(); //db.SaveChanges(); //send email + check if tx was added var mailDetailsLender = new Dictionary { { "[names]", $"{loanRequestOffer.LoanOffer.Profile.Name} {loanRequestOffer.LoanOffer.Profile.Surname}" }, { "[amount]",balance.ToString("N2") }, { "[id]", loanRequestOffer.LoanOffer.Id.ToString()} }; var templateTextlender = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.LoanOfferRefund.ToString() + ".txt"); var emailBodylender = mailDetailsLender.Aggregate(templateTextlender, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(loanRequestOffer.LoanOffer.Profile.EmailAddress, emailBodylender, "Loan Offer Refund | Buddy Finance", null); } db.SaveChanges(); var mailDetails = new Dictionary { { "[names]", $"{request.Profile.Name} {request.Profile.Surname}" }, { "[lender]", loanRequestOffer.LoanOffer.Profile.FullNames}, { "[loanofferamount]", loanRequestOffer.LoanOffer.Amount.ToString("N2")}, { "[loanrequestamount]", loanRequestOffer.LoanRequest.Amount.ToString("N2")}, { "[loanofferrequest]", loanRequestOffer.LoanRequest.Id.ToString("N2") }, { "[borrowerprofile]", request.Profile.ProfileNumber} }; var templateName = loanRequestOffer.LoanRequest.Amount == loanRequestOffer.LoanOffer.Amount ? NotificationTempate.AcceptLoanOffer : NotificationTempate.AcceptLoanOfferB; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + templateName.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(loanRequestOffer.LoanOffer.Profile.EmailAddress, emailBody, "Loan Offer Status | Buddy Finance", null); acceptLoanRequest.Result = true; acceptLoanRequest.ErrorCode = (int)ResponseCodes.Success; acceptLoanRequest.ErrorMessage = "Success"; } else { loanRequestOffer.OfferStausId = (int)OfferStatusEnum.NoFunds; loanRequestOffer.LoanRequest.LoanRequestStatusId = (int)LoanRequestStatusEnum.Expired; db.SaveChanges(); acceptLoanRequest.ErrorCode = (int)ResponseCodes.NotFound; acceptLoanRequest.ErrorMessage = "sorry you accepted late, the offer is taken."; var mailDetails = new Dictionary { { "[names]", $"{request.Profile.Name} {request.Profile.Surname}" }, }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.LateOfferAcceptancy.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(request.Profile.EmailAddress, emailBody, "Late offer Acceptancy | Buddy Finance", null); //db.SaveChanges(); //send email + check if tx was added } } else { acceptLoanRequest.ErrorCode = (int)ResponseCodes.NotFound; acceptLoanRequest.ErrorMessage = " Sorry the offer is not accepted by the Lender."; } //create loan (loanRequestID) } else { acceptLoanRequest.ErrorCode = (int)ResponseCodes.NotFound; acceptLoanRequest.ErrorMessage = "Not found"; } } } catch (Exception ex) { acceptLoanRequest.ErrorCode = (int)ResponseCodes.Exception; acceptLoanRequest.ErrorMessage = ex.Message; } return acceptLoanRequest; } /// /// Get Loan Requests for Lender's offers /// ss /// Lender profile Id /// public GetLoanRequestsResult GetLenderLoanRequests(int profileId) { var result = new GetLoanRequestsResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Lenders.Find(profileId); if (profile != null) { var profileOffers = profile.LoanOffers.Select(m => m.Id).ToList(); var loanRequest = db.LoanRequests.Where(m => m.LoanRequestOffers.Any(n => profileOffers.Contains(n.LoanOfferId))) .Select(m => new LoanRequestModel { Amount = m.Amount, FirstPaymentDate = m.FirstPaymentDate, RequestedDate = m.RequestedDate, LoanRequestStatusId = m.LoanRequestStatusId, Term = m.Term, TermTypeId = m.TermTypeId, Id = m.Id, BorrowerId = m.BorrowerId, TermType = new Models.TermType { Id = m.TermType.Id, Description = m.TermType.Description }, Status = new Models.Status { Id = m.LoanRequestStatus.Id, Description = m.LoanRequestStatus.Description }, Offers = m.LoanRequestOffers.Where(n => profileOffers.Contains(n.LoanOfferId)).Select(k => new LoanRequestOfferModel { Id = k.Id, Comments = k.Comments, RequestDate = DateTime.Now, OfferStausId = (int)OfferStatusEnum.RequestSent, Status = new Models.Status { Id = k.OfferStatus.Id, Description = k.OfferStatus.Description }, LoanOfferId = k.LoanOfferId, LoanRequestId = k.LoanRequestId, }).ToList() }); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = loanRequest.ToList(); } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = ex.Message; } return result; } public BaseResult> BorrowerLoanRequests(string profileId_) { var response = new BaseResult> { Result = new List() }; try { int profileId = profileId_.ToDecryptedInt(); using (var db = new BuddyFinanceDBEntities()) { var loanRequests = db.LoanRequests.Where(m => m.BorrowerId == profileId).ToList(); response.Result = loanRequests.ConvertAll(m => new LoanRequestListModel { Id = m.Id, Id_ = m.Id.ToEncryptedString(), Amount = m.Amount, ReferenceNumber = m.ReferenceNumber, RequestedDate = m.RequestedDate, LoanRequestStatusId = m.LoanRequestStatusId, Term = m.Term, TermTypeId = m.TermTypeId, TermType = new Models.TermType { Id = m.TermType.Id, Description = m.TermType.Description }, Status = new Models.Status { Id = m.LoanRequestStatus.Id, Description = m.LoanRequestStatus.Description }, TotalRquestAccepted = m.LoanRequestOffers.Count(n => n.OfferStausId == (int)OfferStatusEnum.RequestAccepted) }).ToList(); var preLoanReqs = db.PreLoanRequests.Where(m => m.BorrowerId == profileId).ToList(); response.Result.AddRange( preLoanReqs.ConvertAll(m => new LoanRequestListModel { IsPreRequest = true, Id = m.Id, Id_ = m.Id.ToEncryptedString(), Amount = m.Amount, ReferenceNumber = m.ReferenceNumber, RequestedDate = m.RequestedDate, LoanRequestStatusId = m.LoanRequestStatusId, Term = m.Term, TermTypeId = m.TermTypeId, TermType = new Models.TermType { Id = m.TermType.Id, Description = m.TermType.Description }, Status = new Models.Status { Id = m.LoanRequestStatus.Id, Description = m.LoanRequestStatus.Description }, AvaiableOffers = db.LoanOffers.Count(t => t.Balance >= m.Amount && (t.Term >= m.Term && t.TermTypeId == m.TermType.Id) && t.IsDeleted == false) }) ); } } catch (Exception ex) { response.ErrorCode = (int)ResponseCodes.Exception; response.ErrorMessage = ex.Message; response.ExceptionString = GetExeptionString(ex); } return response; } } }