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.Integration.Models.Profiles; using BuddyFinance.Integration.Utils; using BuddyFinance.Model; using Microsoft.VisualBasic; using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Linq; namespace BuddyFinance.Integration { public class ProfilesIntegrator : BaseIntegrator { public GetProfileResult GetProfile(int profileId) { var result = new GetProfileResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(profileId); if (profile != null) { result.Result = Mappers.Profiles.MapFromModel(profile); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "success"; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = $"Could not find profile with id {profileId}"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public GetProfileResult GetProfileByUser(string username) { var result = new GetProfileResult(); try { using (var db = new BuddyFinanceDBEntities()) { var user = db.Users.FirstOrDefault(m => m.UserName.Equals(username)); if (user != null) result = GetProfile(user.ProfileId); else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Profile not found"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public GetProfileNotificationsResult GetNotifications(string profileId_) { var result = new GetProfileNotificationsResult(); try { var profileId = profileId_.ToDecryptedInt(); using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(profileId); if (profile != null) { result.Result = new List(); if (profile.Borrower != null) { // get matching offers for Loan Request Applications var offersIntegrator = new LoanOffersIntergrator(); db.PreLoanRequests.Where(m => m.BorrowerId == profileId).ToList().ForEach(loanRequestApplication => { var offersCount = offersIntegrator.GetLoanOffersByAmount(new Models.GetOffersModel { Amount = loanRequestApplication.Amount, Term = loanRequestApplication.Term, TermType = new Models.TermType { Id = loanRequestApplication.TermTypeId, Description = loanRequestApplication.TermType?.Description }, ProfileId = loanRequestApplication.BorrowerId, ProfileId_ = profileId_ }).Result?.Count ?? 0; if (offersCount > 0) { result.Result.Add(new UserNotification { Id = loanRequestApplication.Id, Id_ = loanRequestApplication.Id.ToEncryptedString(), Title = "Offers Available", Type = UserNotificationTypeEnum.LoanOfferRequestOffers, Description = (offersCount == 1 ? offersCount + " offer" : offersCount + " offers") + " available for Loan Request Application '" + loanRequestApplication.ReferenceNumber + "'" }); } }); // get Loan Offer Request accepted by Lender that is pending to be accepted by Borrower var pendingLoanReqestOffers = db.LoanRequestOffers.Where(m => m.OfferStausId == (int)OfferStatusEnum.RequestAccepted && m.LoanRequest.BorrowerId == profileId) .ToList().Select(m => new UserNotification { Id = m.LoanRequestId, Id_ = m.LoanRequestId.ToEncryptedString(), Title = "Pending Acceptancy", Type = UserNotificationTypeEnum.AcceptLoanOfferRequest, Description = "Reqest Offer for Request '" + m.LoanRequest.ReferenceNumber + "' accepted by Lender" }); result.Result.AddRange(pendingLoanReqestOffers); } if (profile.Lender != null) { // get new offer requests var newOofferRequests = db.LoanRequestOffers.Where(m => m.LoanOffer.ProfileId == profileId && m.OfferStausId == (int)OfferStatusEnum.RequestSent); newOofferRequests.ToList().ForEach(offerRequest => { result.Result.Add(new UserNotification { Id = offerRequest.LoanOfferId, Id_ = offerRequest.LoanOfferId.ToEncryptedString(), Title = "Offer Requested", Type = UserNotificationTypeEnum.LoanOfferRequested, Description = "Loan offer of R" + offerRequest.LoanOffer.Amount + " (" + offerRequest.LoanOffer.InterestRate + "% interest) requested by " + offerRequest.LoanRequest.Profile?.ProfileNumber + " at R" + offerRequest.LoanRequest.Amount }); }); } } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Profile not found"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult ReviewAccount(ReviewProfileModel model) { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(model.ProfileId.ToDecryptedInt()); if (profile != null) { string subject; string templatePath; Dictionary mailDetails; if (model.Approve == true) { if (model.ProfileTypeId == (int)ProfileTypeEnum.Lender) profile.Lender.StatusId = (int)ProfileStatusEnum.Approved; if (model.ProfileTypeId == (int)ProfileTypeEnum.Borrower) profile.Borrower.StatusId = (int)ProfileStatusEnum.Approved; db.SaveChanges(); subject = "Account Approved | Buddy Finance"; templatePath = ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.ProfileApproval.ToString() + ".txt"; mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[email]", $"{profile.EmailAddress}"}, { "[url]", ConfigurationManager.AppSettings["LoginUrl"]}, { "[ref]", $"{profile.ProfileNumber}"}, { "[comments]", model.Comments} }; var templateText = System.IO.File.ReadAllText(templatePath); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, subject, null); } else { if (model.ProfileTypeId == (int)ProfileTypeEnum.Lender) profile.Lender.StatusId = (int)ProfileStatusEnum.Rejected; if (model.ProfileTypeId == (int)ProfileTypeEnum.Borrower) profile.Borrower.StatusId = (int)ProfileStatusEnum.Rejected; db.SaveChanges(); subject = "Account Rejected | Buddy Finance"; templatePath = ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.ProfileRejected.ToString() + ".txt"; mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[comments]", $"{model.Comments}"}, //{ "[defaultpassword]", $"{profile.Users.FirstOrDefault()?.Password }" }, { "[url]", ConfigurationManager.AppSettings["LoginUrl"]} }; } } return new BaseResult((int)ResponseCodes.Success, ""); } } public BaseResult SuspendAccount(SuspendProfileAccountModel model) { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(model.ProfileId.ToDecryptedInt()); if (profile != null) { string subject; string templatePath; Dictionary mailDetails; if (model.Suspend == true) { var accountType = ""; if (model.ProfileTypeId == (int)ProfileTypeEnum.Lender) { profile.Lender.StatusId = (int)ProfileStatusEnum.Suspended; accountType = "Lend Account"; } if (model.ProfileTypeId == (int)ProfileTypeEnum.Borrower) { profile.Borrower.StatusId = (int)ProfileStatusEnum.Suspended; accountType = "Borrow Account"; } db.SaveChanges(); subject = "Account Suspended | Buddy Finance"; templatePath = ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.AccountSuspended.ToString() + ".txt"; mailDetails = new Dictionary { { "[accountType]", accountType}, { "[reason]", model.Comments} }; var templateText = System.IO.File.ReadAllText(templatePath); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, subject, null); } else { var accountType = ""; if (model.ProfileTypeId == (int)ProfileTypeEnum.Lender) { profile.Lender.StatusId = (int)ProfileStatusEnum.Approved; accountType = "Lend Account"; } if (model.ProfileTypeId == (int)ProfileTypeEnum.Borrower) { profile.Borrower.StatusId = (int)ProfileStatusEnum.Approved; accountType = "Borrow Account"; } db.SaveChanges(); subject = "Account Re-Activated | Buddy Finance"; templatePath = ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.AccountUnsuspended.ToString() + ".txt"; mailDetails = new Dictionary { { "[accountType]", accountType}, { "[reason]", model.Comments} }; } } return new BaseResult((int)ResponseCodes.Success, ""); } } public BaseResult
GetAddress(int addressId) { using (var db = new BuddyFinanceDBEntities()) { var addr = db.ProfileAddresses.Find(addressId); var address = new Models.Address { AddressId = addr.Id, Line1 = addr.Line1, Line2 = addr.Line2, AddressTypeId = addr.AddressTypeId, AddressType = new Models.AddressType { Id = addr.AddressTypeId, Description = addr.AddressType.Description }, City = addr.City, //CountryId = addr.CountryId, //Country = new Models.Country //{ // Id = addr.CountryId.GetValueOrDefault(), // CountryCode = addr.Country?.CountryCode, // Description = addr.Country?.CountryName //}, PostalCode = addr.PostalCode, ProvinceId = addr.ProvinceId, Province = addr.Province == null ? null : new Models.Province { Id = addr.Province.Id, Description = addr.Province?.Description }, AddressProfileId = addr.ProfileId }; return new BaseResult
{ ErrorCode = (int)ResponseCodes.Success, ErrorMessage = "Success", Result = address }; } } public BaseResult> GetAddresses(int profileId) { using (var db = new BuddyFinanceDBEntities()) { var addresses = new List
(); var addressTypes = db.AddressTypes.ToList(); foreach (var type in addressTypes) { var addr = db.ProfileAddresses.FirstOrDefault(m => m.AddressTypeId == type.Id && m.ProfileId == profileId && !m.IsDeleted); if (addr == null) addresses.Add(new Address { AddressTypeId = type.Id, AddressType = new Models.AddressType { Id = type.Id, Description = type.Description }, AddressProfileId = profileId }); else addresses.Add(new Models.Address { AddressId = addr.Id, Line1 = addr.Line1, Line2 = addr.Line2, AddressTypeId = addr.AddressTypeId, AddressType = new Models.AddressType { Id = addr.AddressTypeId, Description = addr.AddressType.Description }, City = addr.City, //CountryId = addr.CountryId, //Country = new Models.Country //{ // Id = addr.CountryId.GetValueOrDefault(), // CountryCode = addr.Country?.CountryCode, // Description = addr.Country?.CountryName //}, PostalCode = addr.PostalCode, ProvinceId = addr.ProvinceId, Province = addr.Province == null ? null : new Models.Province { Id = addr.Province.Id, Description = addr.Province.Description }, AddressProfileId = profileId }); } return new BaseResult> { ErrorCode = (int)ResponseCodes.Success, ErrorMessage = "Success", Result = addresses }; } } public SaveProfileResult SaveProfile(Models.Profiles.Profile profile) { try { using (var db = new BuddyFinanceDBEntities()) { var pr = db.Profiles.Find(profile.ProfileId); if (pr != null) { // pr.ProfileTypeId = profile.ProfileTypeId; pr.Name = profile.Name; pr.Surname = profile.Surname; pr.Title = profile.Title; pr.EmailAddress = profile.EmailAddress.ToLower(); pr.ContactNumber = profile.ContactNumber; pr.GenderId = profile.GenderId; pr.DateOfBirth = profile.DateOfBirth; pr.CountryOfBirthId = profile.CountryOfBirth.Id; pr.IdentificationNumber = profile.IdentificationNumber; pr.IdentificationTypeId = profile.IdentificationType.Id; pr.EthnicityId = profile.Ethnicity.Id; pr.TaxRegistered = profile.TaxRegistered; pr.AvailableFunds = (double)profile.AvailableFunds; if (profile.BankingDetails != null) { var bankingDetail = pr.BankingDetail ?? new BuddyFinance.Model.BankingDetail(); bankingDetail.AccountName = profile.BankingDetails.AccountName; bankingDetail.AccountNumber = profile.BankingDetails.AccountNumber; bankingDetail.AccountType = profile.BankingDetails.AccountType; //bankingDetail.BranchCode = profile.BankingDetails.BranchCode; bankingDetail.BankName = profile.BankingDetails.BankName; //bankingDetail.BranchName = profile.BankingDetails.BranchName; pr.BankingDetail = bankingDetail; } if (profile.TaxInformation != null) { var taxInfo = pr.TaxInformation ?? new BuddyFinance.Model.TaxInformation(); taxInfo.TaxCountryId = profile.TaxInformation.TaxCountry.Id; taxInfo.TaxNumber = profile.TaxInformation.TaxNumber; taxInfo.TaxIdentificationTypeId = profile.TaxInformation.TaxIdentificationType.Id; pr.TaxInformation = taxInfo; } pr.SourceOfIncomeId = profile.SourceOfIncome.Id; pr.OtherSourceOfIncome = profile.OtherSourceOfIncome; if (profile.FicaCompliance != null) { var ficaCompliance = pr.FicaCompliance ?? new BuddyFinance.Model.FicaCompliance(); ficaCompliance.FicaStatusId = profile.FicaCompliance.FicaStatusId; ficaCompliance.VerificationDate = profile.FicaCompliance.VerificationDate; pr.FicaCompliance = ficaCompliance; } if (profile.EmploymentDetail != null) { var employment = pr.EmploymentDetail ?? new BuddyFinance.Model.EmploymentDetail(); employment.NetMonthlyIncome = profile.EmploymentDetail.NetMonthlyIncome; employment.GrossMonthlyIncome = profile.EmploymentDetail.GrossMonthlyIncome; employment.SalaryDay = profile.EmploymentDetail.SalaryDay; //employment.EmploymentStatus = profile.EmploymentDetail.EmploymentStatus; employment.EmploymentStartDate = profile.EmploymentDetail.EmploymentStartDate; employment.EmploymentEndDate = profile.EmploymentDetail.EmploymentEndDate; employment.BillingDay = profile.EmploymentDetail.BillingDay; //employment.EmployerContactNumber = profile.EmploymentDetail.EmployerContactNumber; employment.EmployerNumber = profile.EmploymentDetail.EmployerNumber; // employment.EmploymentTypeId = profile.EmploymentDetail.EmploymentTypeId; pr.EmploymentDetail = employment; } foreach (var addr in profile.Addresses) { if (pr.ProfileAddresses.Any(i => i.Id == addr.AddressId)) { // update var address = pr.ProfileAddresses.First(i => i.Id == addr.AddressId); address.Id = addr.AddressId; address.Line1 = addr.Line1; address.Line2 = addr.Line2; address.AddressTypeId = addr.AddressType.Id; address.City = addr.City; //address.CountryId = addr.Country.Id; address.PostalCode = addr.PostalCode; address.ProvinceId = addr.Province.Id; address.ProfileId = pr.Id; db.Entry(address).State = EntityState.Modified; } else { pr.ProfileAddresses.Add(new ProfileAddress { Id = addr.AddressId, Line1 = addr.Line1, Line2 = addr.Line2, AddressTypeId = addr.AddressTypeId, City = addr.City, //CountryId = addr.CountryId, PostalCode = addr.PostalCode, ProvinceId = addr.ProvinceId, ProfileId = pr.Id }); } } db.Entry(pr).State = EntityState.Modified; db.SaveChanges(); return new SaveProfileResult { Result = new Models.Profiles.Profile(), ErrorCode = (int)ResponseCodes.Success, ErrorMessage = "Succesful" }; } else { return new SaveProfileResult { Result = new Models.Profiles.Profile() { ProfileId = pr.Id }, ErrorCode = (int)ResponseCodes.NotFound, ErrorMessage = "User with " + pr.Id.ToString() + " Not found." }; } } } catch (Exception ex) { return new SaveProfileResult { ErrorCode = (int)ResponseCodes.Exception, ErrorMessage = "An error has occurred. Exception: " + ex.Message }; } } public BaseResult> GetDocuments(int profileId) { using (var db = new BuddyFinanceDBEntities()) { var documents = db.ProfileDocuments.Where(m => m.ProfileId == profileId && !m.IsDeleted).ToList() .ConvertAll(m => new Models.Document { DocumentTypeId = m.DocumentTypeId, DocumentType = new Models.DocumentType { Id = m.DocumentType.Id, Description = m.DocumentType.Description }, DocumentId = m.Id, FileId = m.FileId, ProfileId = m.ProfileId, UploadedDate = m.UploadedDate, FileData = new Models.Files.FileData { Id = m.FileData.Id, Contents = Convert.ToBase64String(m.FileData.Contents), ContentType = m.FileData.ContentType, Size = m.FileData.Size, FileName = m.FileData.FileName, FileUrl = m.FileData.FileUrl } }); return new BaseResult> { ErrorCode = (int)ResponseCodes.Success, ErrorMessage = "Success", Result = documents }; } } public ProfileSummaryResult Summary(string profileId_) { var profileId = profileId_.ToDecryptedInt(); var result = new ProfileSummaryResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(profileId); if (profile != null) { if (profile.Borrower != null) { result.Result.Loans = profile.Borrower.Loans.Select(m => new LoanModel { LoanAmount = m.LoanAmount, Id = m.Id, LoanStatusId = m.LoanStatusId, Status = new Status { Id = m.LoanStatusId, Description = m.LoanStatus?.Description } }).ToList(); result.Result.LoanRequests = profile.Borrower.LoanRequests.Select(m => new LoanRequestModel { Amount = m.Amount, Id = m.Id, LoanRequestStatusId = m.LoanRequestStatusId, Status = new Status { Id = m.LoanRequestStatusId, Description = m.LoanRequestStatus?.Description } }).ToList(); } if (profile.Lender != null)//lender { result.Result.AvailableFunds = profile.AvailableFunds; //result.Result.TotalCashDeposit = !db.CashDeposits.Any(t => t.ProfileId == profile.Id) ? 0 // : db.CashDeposits.Where(t => t.ProfileId == profile.Id).Sum(m => m.Amount); //result.Result.TotalCashWithdrawal = !db.CashWithdrawals.Any(t => t.ProfileId == profile.Id) ? 0 // : db.CashWithdrawals.Where(t => t.ProfileId == profile.Id // && t.StatusId != (int)CashWithdrawalEnum.Cancelled // && t.StatusId != (int)CashWithdrawalEnum.Rejected) // .Sum(t => t.Amount); result.Result.TotalCashDeposit = !profile.CashDeposits.Any() ? 0 : profile.CashDeposits.Sum(m => m.Amount); result.Result.TotalCashWithdrawal = !profile.CashWithdrawals.Any() ? 0 : profile.CashWithdrawals.Where(t => t.StatusId != (int)CashWithdrawalEnum.Cancelled && t.StatusId != (int)CashWithdrawalEnum.Rejected) .Sum(t => t.Amount); result.Result.LoanOffers = new List(); profile.Lender.LoanOffers.ToList().ForEach(loanOffer => { var offer = new LoanOfferModel { Id = loanOffer.Id, //Id_=loanOffer.Id.ToEncryptedString(), LenderId = loanOffer.ProfileId, Lender = new Models.Profiles.Profile { Title = loanOffer.Profile.Title, Name = loanOffer.Profile.Name, Surname = loanOffer.Profile.Surname }, Amount = loanOffer.Amount, Balance = loanOffer.Balance, InterestRate = loanOffer.InterestRate, Term = loanOffer.Term, TermType = new Models.TermType { Description = loanOffer.TermType.Description, Id = loanOffer.TermType.Id }, IsActive = loanOffer.IsActive, DateCreated = loanOffer.DateCreated, ExpiryDate = loanOffer.ExpiryDate, LoanRequestOffers = loanOffer.LoanRequestOffers.ToList().ConvertAll(m => new LoanRequestOfferModel { Id = m.Id, RequestDate = m.RequestDate, LoanOfferId = m.LoanOfferId, LoanRequestId = m.LoanRequestId, Comments = m.Comments, OfferStausId = m.OfferStausId, Status = new Models.Status { Id = m.OfferStatus.Id, Description = m.OfferStatus.Description }, Amount = m.LoanRequest.Amount, Borrower = m.LoanRequest.Profile.ProfileNumber, IsActive = m.IsActive, //BorrowerProfile = new Models.Profiles.Profile //{ // ProfileNumber = m.LoanRequest.Profile.ProfileNumber, // FullNames = m.LoanRequest.Profile.FullNames, // HasExistingScore = db.ProfileCreditRatingScores.Any(n => n.BorrowerId == m.LoanRequest.BorrowerId) //} }) }; result.Result.LoanOffers.Add(offer); }); } } else { result.Result = new ProfileSummary(); } result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; result.ExceptionString = GetExeptionString(ex); } return result; } private Model.Country ResolveCountry(Models.Country country) { if (country == null) return null; using (var db = new BuddyFinanceDBEntities()) { if (!string.IsNullOrEmpty(country.CountryCode)) { return db.Countries.FirstOrDefault(i => i.CountryCode == country.CountryCode); } return new BuddyFinance.Model.Country { CountryName = country.Description }; } } private Model.Ethnicity ResolveEthnicity(Models.Ethnicity ethnicity) { if (ethnicity == null) return null; using (var db = new BuddyFinanceDBEntities()) { if (!string.IsNullOrEmpty(ethnicity.Description)) { return db.Ethnicities.FirstOrDefault(x => x.Description == ethnicity.Description); } return new BuddyFinance.Model.Ethnicity { Description = ethnicity.Description }; } } public GetProfilesResult GetAllProfiles() { var result = new GetProfilesResult(); try { using (var db = new BuddyFinanceDBEntities()) { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = Mappers.Profiles.MapFromListModel(db.Profiles.ToList()); result.ProfileType = ""; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = "" + ex; } return result; } //lender or borrowers public GetProfilesResult GetProfiles(int ProfileTypeId) { var result = new GetProfilesResult(); try { using (var db = new BuddyFinanceDBEntities()) { //var profiles = db.Profiles.Where(p => p.ProfileTypeId == ProfileTypeId).ToList(); result.Result = Mappers.Profiles.MapFromListModel(db.Profiles.Where(m => ProfileTypeId == (int)ProfileTypeEnum.Lender ? (m.Lender != null) : (m.Borrower != null)).ToList()); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.ProfileType = db.ProfileTypes.Find(ProfileTypeId)?.Description; //if (profiles != null) //{ // result.Result = profiles.Select(p => new Models.Profiles.Profile // { // ProfileId = p.Id, // Name = p.Name, // Surname = p.Surname, // EmailAddress = p.EmailAddress, // ContactNumber = p.ContactNumber, // DateOfBirth = p.DateOfBirth, // ProfileNumber = p.ProfileNumber, // AvailableFunds = (decimal)p.AvailableFunds, // IdentificationNumber = p.IdentificationNumber, // OtherSourceOfIncome = p.OtherSourceOfIncome, // Title = p.Title, // Gender = new Models.Gender // { // Id = p.Gender.Id, // Description = p.Gender.Description // }, // Ethnicity = new Models.Ethnicity // { // id = p.Ethnicity.Id, // Ethncity = p.Ethnicity.Description // }, // IdentificationType = new Models.IdentificationType // { // Id = p.IdentificationType.Id, // Description = p.IdentificationType.Description, // }, // ProfileType = new Models.ProfileType // { // ProfileTypeId = p.ProfileTypeId, // Name = p.ProfileType.Description // }, // CountryOfBirth = new Models.Country // { // CountryId = p.Country.Id, // Description = p.Country.CountryName, // CountryCode = p.Country.CountryCode // }, // ProfileStatus = new Models.Status // { // Id = p.ProfileStatus.Id, // Description = p.ProfileStatus.Description // }, // BankingDetails = new Models.BankingDetail // { // Id = p.BankingDetail.Id, // AccountName = p.BankingDetail.AccountName, // AccountNumber = p.BankingDetail.AccountNumber, // AccountType = p.BankingDetail.AccountType, // BranchCode = p.BankingDetail.BranchCode, // BankName = p.BankingDetail.BankName, // BranchName = p.BankingDetail.BranchName, // }, // TaxInformation = new Models.TaxInformation // { // Id = p.TaxInformation.Id, // TaxCountryId = p.TaxInformation.TaxCountryId, // TaxNumber = p.TaxInformation.TaxNumber, // TaxIdentificationTypeId = p.TaxInformation.TaxIdentificationTypeId, // }, // EmploymentDetail = new Models.EmploymentDetail // { // Id = p.EmploymentDetail.Id, // NetMonthlyIncome = (double)p.EmploymentDetail.NetMonthlyIncome, // GrossMonthlyIncome = (double)p.EmploymentDetail.GrossMonthlyIncome, // SalaryDay = p.EmploymentDetail.SalaryDay, // EmployerName = p.EmploymentDetail.EmployerName, // EmploymentStartDate = (System.DateTime)p.EmploymentDetail.EmploymentStartDate, // EmploymentEndDate = (System.DateTime)p.EmploymentDetail.EmploymentEndDate, // EmployerContactNumber = p.EmploymentDetail.EmployerContactNumber, // EmployerNumber = p.EmploymentDetail.EmployerNumber, // }, // EmploymentStatus = new Models.EmploymentStatus // { // Id = p.EmploymentStatus.Id, // Description = p.EmploymentStatus.Description // }, // SourceOfIncome = new Models.SourceOfIncome // { // Id = p.SourceOfIncome.Id, // Description = p.SourceOfIncome.Description // }, // Documents = p.ProfileDocuments.ToList().ConvertAll(m => new Models.Document // { // DocumentTypeId = m.DocumentTypeId, // Id = m.Id, // FileId = m.FileId, // UploadedDate = m.UploadedDate, // FileData = new Models.Files.FileData // { // Id = m.FileData.Id, // Contents = Convert.ToBase64String(m.FileData.Contents), // ContentType = m.FileData.ContentType, // Size = m.FileData.Size, // FileName = m.FileData.FileName, // FileUrl = m.FileData.FileUrl // } // }) // }).ToList(); //result.Result = Mappers.Profiles.MapFromListModel(db.Profiles.ToList()); //result.ErrorCode = (int)ResponseCodes.Success; //result.ErrorMessage = "Success"; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = "" + ex; } return result; } //email didnt go through on my second test. public ApproveProfileResult ApproveProfile(int profileId, bool approve, string rejectReason, int userId) { try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(profileId); if (profile != null) { var approval = db.ProfileApprovals.Find(profileId) ?? new ProfileApproval(); approval.ReviewDate = DateTime.Now; approval.ReviewerId = userId; string subject; string templatePath; Dictionary mailDetails; if (approve == true) { profile.StatusId = (int)ProfileStatusEnum.Approved; //profile.BillingDate = DateTime.Now; profile.LastBillDate = DateTime.Now; if (profile.Lender != null) profile.Lender.StatusId = (int)ProfileStatusEnum.Approved; if (profile.Borrower != null) profile.Borrower.StatusId = (int)ProfileStatusEnum.Approved; approval.ProfileStatusId = (int)ProfileStatusEnum.Approved; approval.RejectReason = null; var user = profile.Users.FirstOrDefault(); if (user != null) { user.IsActive = true; db.Entry(user).State = EntityState.Modified; } subject = "Application Approved | Buddy Finance"; templatePath = ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.ProfileApproval.ToString() + ".txt"; var info = ""; if (profile.Lender != null) { info = "
" + " Deposit funds into the following account using [ref] as reference. " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "
Banking Details
Legal entity name: Thorough Capital
Bank: Standard Bank
Account name: Buddy Finance
Branch Name: Greenstone
Branch Code: 016342
Account Number: 023420367
Swift Address: SBZA ZA JJ
"; } mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[email]", $"{profile.EmailAddress}"}, { "[url]", ConfigurationManager.AppSettings["LoginUrl"]}, { "[ref]", $"{profile.ProfileNumber}"}, { "[ADDITIONALINFO]", info} }; var templateText = System.IO.File.ReadAllText(templatePath); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, subject, null); //if (profile.ProfileType.Id == (int)ProfileTypeEnum.Borrower) //{ // templatePath = ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.ProfileApprovalBorrower.ToString() + ".txt"; // mailDetails = new Dictionary // { // { "[names]", $"{profile.Name} {profile.Surname}" }, // { "[email]", $"{profile.EmailAddress}"}, // //{ "[defaultpassword]", $"{profile.Users.FirstOrDefault()?.Password }" }, // { "[url]", ConfigurationManager.AppSettings["LoginUrl"]} // }; // var templateText = System.IO.File.ReadAllText(templatePath); // var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); // _notifications.SendEmail(profile.EmailAddress, emailBody, subject, null); //} } else { profile.StatusId = (int)ProfileStatusEnum.Rejected; if (profile.Lender != null) profile.Lender.StatusId = (int)ProfileStatusEnum.Rejected; if (profile.Borrower != null) profile.Borrower.StatusId = (int)ProfileStatusEnum.Rejected; approval.ProfileStatusId = (int)ProfileStatusEnum.Rejected; approval.RejectReason = rejectReason; subject = "Application Rejected | Buddy Finance"; templatePath = ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.ProfileRejected.ToString() + ".txt"; mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[rejectReason]", $"{rejectReason}"}, //{ "[defaultpassword]", $"{profile.Users.FirstOrDefault()?.Password }" }, { "[url]", ConfigurationManager.AppSettings["LoginUrl"]} }; } profile.ProfileApproval = approval; db.Entry(profile).State = EntityState.Modified; db.SaveChanges(); var hash = profile.Id.ToEncryptedString(); var password = PasswordHelper.GeneratePassword(hash, out string plainTexPsss); if (!profile.Users.Any()) { var userAccount = new User { ProfileId = profile.Id, UserName = profile.EmailAddress, MustChangePassword = false, Password = password, PasswordHash = hash, IsActive = true, RoleId = (int)UserRoleEnum.Buddy }; db.Users.Add(userAccount); db.SaveChanges(); } //SEND EMAIL //send profile verification email .. //link to api/registrations/verify(token) // var token_ = TokenManager.Generate(result.Result); //profile Number // var url = Url.Link("Default", new { Controller = "Registration", Action = "Verify", token = token_, profileNumber = result.Result }); // url = url.Replace("Registration", "api/Registration"); return new ApproveProfileResult { ErrorCode = (int)ResponseCodes.Success, ErrorMessage = "Success", Result = true }; } else { return new ApproveProfileResult { ErrorCode = (int)ResponseCodes.NotFound, ErrorMessage = $"Could not find rpofile with id {profileId}", Result = true }; } } } catch (Exception ex) { return new ApproveProfileResult { ErrorCode = (int)ResponseCodes.Exception, ErrorMessage = ex.Message }; } } public BaseResult Suspend(SuspendProfileModel model) { var returnValue = new BaseResult { Result = false }; try { using (var db = new BuddyFinanceDBEntities()) { var id = model.ProfileId.ToDecryptedInt(); var profile = db.Profiles.Find(id); if (profile != null) { var suspension = db.ProfileSuspensions.Find(model.ProfileId.ToDecryptedInt()) ?? new ProfileSuspension(); if (model.Suspend == true) { profile.StatusId = (int)ProfileStatusEnum.Suspended; suspension.Reason = model.Comments; suspension.StartDate = DateTime.Now; suspension.EndDate = DateTime.Now.AddDays(30); suspension.ReviewerId = model.UserId.ToDecryptedInt(); profile.ProfileSuspension = suspension; //db.SaveChanges(); // profile.ProfileApproval = new ProfileApproval() { ProfileStatusId = (int)ProfileStatusEnum.Approved }; } else { profile.StatusId = (int)ProfileStatusEnum.Approved; profile.ProfileSuspension = null; //db.SaveChanges(); } db.Entry(profile).State = EntityState.Modified; db.SaveChanges(); var mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[email]", $"{profile.EmailAddress}"}, { "[reason]", $"{model.Comments}"}, }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.ProfileSuspended.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, "Account Suspended | Buddy Finance", null); return new ApproveProfileResult { ErrorCode = (int)ResponseCodes.Success, ErrorMessage = "Success", Result = true }; } else { return new ApproveProfileResult { ErrorCode = (int)ResponseCodes.NotFound, ErrorMessage = $"Could not find profile", Result = false }; } } } catch (Exception ex) { returnValue.ErrorCode = (int)ResponseCodes.Exception; returnValue.ErrorMessage = ex.Message; } return returnValue; } //update profile info public BaseResult Update(Models.Profiles.Profile profile) { try { using (var db = new BuddyFinanceDBEntities()) { var pr = db.Profiles.Find(profile.ProfileId); if (pr != null) { pr.Name = profile.Name; pr.Surname = profile.Surname; pr.Title = profile.Title; pr.EmailAddress = profile.EmailAddress; pr.ContactNumber = profile.ContactNumber; pr.IdentificationNumber = profile.IdentificationNumber; pr.GenderId = profile.Gender.Id; //Or regenerate from ID number ?? pr.DateOfBirth = profile.DateOfBirth; //Or regenerate " " pr.IdentificationTypeId = (int)IdentificationTypeEnum.IdentityDocument; //profile.IdentificationType.Id; db.Entry(pr).State = EntityState.Modified; db.SaveChanges(); return new BaseResult { Result = true, ErrorCode = (int)ResponseCodes.Success, ErrorMessage = "Succesful" }; } else { return new BaseResult { Result = false, ErrorCode = (int)ResponseCodes.NotFound, ErrorMessage = "User with " + pr.Id.ToString() + " Not found." }; } } } catch (Exception ex) { return new BaseResult { ErrorCode = (int)ResponseCodes.Exception, ErrorMessage = "An error has occurred. Exception: " + ex.Message }; } } public UpdateAddressResult UpdateAddress(Models.Address address) { var result = new UpdateAddressResult(); try { using (var db = new BuddyFinanceDBEntities()) { var updateAddress = db.ProfileAddresses.Find(address.AddressId) ?? new ProfileAddress(); updateAddress.AddressTypeId = address.AddressTypeId; updateAddress.Line1 = address.Line1; updateAddress.Line2 = address.Line2; updateAddress.City = address.City; updateAddress.ProvinceId = address.ProvinceId; updateAddress.PostalCode = address.PostalCode; //updateAddress.CountryId = address.CountryId; updateAddress.ProfileId = address.AddressProfileId; if (updateAddress.Id == 0) db.ProfileAddresses.Add(updateAddress); else db.Entry(updateAddress).State = EntityState.Modified; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = updateAddress.Id; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult UpdateAddresses(List addresses) { var result = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { foreach (var address in addresses) { var updateAddress = db.ProfileAddresses.Find(address.AddressId) ?? new ProfileAddress(); updateAddress.AddressTypeId = address.AddressType.Id; updateAddress.Line1 = address.Line1; updateAddress.Line2 = address.Line2; updateAddress.City = address.City; updateAddress.ProvinceId = address.Province.Id; updateAddress.PostalCode = address.PostalCode; //updateAddress.CountryId = address.Country.Id; updateAddress.ProfileId = address.AddressProfileId; if (updateAddress.Id == 0) db.ProfileAddresses.Add(updateAddress); else db.Entry(updateAddress).State = EntityState.Modified; } db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = addresses.First().AddressProfileId; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult RemoveAddress(int addressId) { var returnValue = new BaseResult { Result = false }; try { using (var db = new BuddyFinanceDBEntities()) { var address = db.ProfileAddresses.Find(addressId); if (address != null) { address.IsDeleted = true; db.SaveChanges(); returnValue.ErrorCode = (int)ResponseCodes.Success; returnValue.ErrorMessage = "Success"; } else { returnValue.ErrorCode = (int)ResponseCodes.NotFound; returnValue.ErrorMessage = "Address could not be found"; } } } catch (Exception ex) { returnValue.ErrorCode = (int)ResponseCodes.Exception; returnValue.ErrorMessage = ex.Message; } return returnValue; } public BaseResult RemoveDocument(int documentId) { var returnValue = new BaseResult { Result = false }; try { using (var db = new BuddyFinanceDBEntities()) { var socument = db.ProfileDocuments.Find(documentId); if (socument != null) { socument.IsDeleted = true; db.SaveChanges(); returnValue.ErrorCode = (int)ResponseCodes.Success; returnValue.ErrorMessage = "Success"; returnValue.Result = true; } else { returnValue.ErrorCode = (int)ResponseCodes.NotFound; returnValue.ErrorMessage = "Document could not be found"; } } } catch (Exception ex) { returnValue.ErrorCode = (int)ResponseCodes.Exception; returnValue.ErrorMessage = ex.Message; } return returnValue; } public BaseResult UpdateDocuments(List documents) { var result = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { var errorMessage = ""; try { foreach (var document in documents) { var updateDocument = db.ProfileDocuments.Find(document.DocumentId) ?? new ProfileDocument(); updateDocument.ProfileId = document.ProfileId; updateDocument.DocumentTypeId = document.DocumentType.Id; updateDocument.UploadedDate = updateDocument.Id == 0 ? DateTime.Now : document.UploadedDate; updateDocument.FileData = db.FileDatas.Find(document.FileId) ?? new FileData(); updateDocument.FileData.Contents = Convert.FromBase64String(document.FileData.Contents); updateDocument.FileData.ContentType = document.FileData.ContentType; updateDocument.FileData.FileName = document.FileData.FileName; updateDocument.FileData.FileUrl = document.FileData.FileUrl; updateDocument.FileData.Size = document.FileData.Size; if (updateDocument.Id == 0) db.ProfileDocuments.Add(updateDocument); else db.Entry(updateDocument).State = EntityState.Modified; } db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = documents.First().ProfileId; } catch (FormatException ex) { errorMessage += $"Documents could not be updated. {ex.Message}"; } catch (ArgumentNullException ex) { errorMessage += $"Documents could not be updated. {ex.Message}"; } if (errorMessage != "") { result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = errorMessage; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public UpdateDocumentResult UpdateDocument(Models.Document document) { var result = new UpdateDocumentResult(); try { using (var db = new BuddyFinanceDBEntities()) { var errorMessage = ""; try { var updateDocument = db.ProfileDocuments.Find(document.DocumentId) ?? new ProfileDocument(); updateDocument.ProfileId = document.ProfileId; updateDocument.DocumentTypeId = document.DocumentTypeId; updateDocument.UploadedDate = updateDocument.Id == 0 ? DateTime.Now : document.UploadedDate; updateDocument.FileData = db.FileDatas.Find(document.FileId) ?? new FileData(); updateDocument.FileData.Contents = Convert.FromBase64String(document.FileData.Contents); updateDocument.FileData.ContentType = document.FileData.ContentType; updateDocument.FileData.FileName = document.FileData.FileName; updateDocument.FileData.FileUrl = document.FileData.FileUrl; updateDocument.FileData.Size = document.FileData.Size; if (updateDocument.Id == 0) db.ProfileDocuments.Add(updateDocument); else db.Entry(updateDocument).State = EntityState.Modified; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = updateDocument.Id; } catch (FormatException ex) { errorMessage += $"Document could not be updated. {ex.Message}"; } catch (ArgumentNullException ex) { errorMessage += $"Document could not be updated. {ex.Message}"; } if (errorMessage != "") { result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = errorMessage; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult UpdateDetails(Models.Profiles.ProfileDetails profileDetails) { var result = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(profileDetails.ProfileId) ?? new Model.Profile { StatusId = (int)ProfileStatusEnum.New, ProfileNumber = RegistrationsHelper.GenerateProfileNumber(profileDetails.ProfileTypeId), BillingDate = DateTime.Now, LastBillDate = DateTime.Now, }; if (profile.Id == 0) { if (db.Users.Any(m => m.UserName.Equals(profileDetails.EmailAddress))) { result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = "Email address already in use"; return result; } } profile.Name = profileDetails.Name; profile.Surname = profileDetails.Surname; profile.EmailAddress = profileDetails.EmailAddress; profile.ContactNumber = profileDetails.ContactNumber; profile.IdentificationNumber = profileDetails.IdentificationNumber; profile.LendServiceAccount = profileDetails.LendServiceAccount; profile.BorrowServiceAccount = profileDetails.BorrowServiceAccount; if (profileDetails.BorrowServiceAccount == true) { if (profile.Borrower == null) { profile.Borrower = new Model.Borrower { ProfileTypeId = (int)ProfileTypeEnum.Borrower, BorrowerNumber = profile.ProfileNumber, StatusId = profile.StatusId == (int)ProfileStatusEnum.New ? (int)ProfileStatusEnum.New : (int)ProfileStatusEnum.Pending, }; } } else if (profileDetails.BorrowServiceAccount == false) { if (profile.Borrower != null) { if (profile.StatusId == (int)ProfileStatusEnum.New) profile.Borrower = null; else profile.Borrower.StatusId = (int)ProfileStatusEnum.Deactivated; } } if (profileDetails.LendServiceAccount == true) { if (profile.Lender == null) { profile.Lender = new Model.Lender { ProfileTypeId = (int)ProfileTypeEnum.Borrower, LenderNumber = profile.ProfileNumber, StatusId = profile.StatusId == (int)ProfileStatusEnum.New ? (int)ProfileStatusEnum.New : (int)ProfileStatusEnum.Pending, }; } } else if (profileDetails.LendServiceAccount == false) { if (profile.Lender != null) { if (profile.StatusId == (int)ProfileStatusEnum.New) profile.Lender = null; else profile.Lender.StatusId = (int)ProfileStatusEnum.Deactivated; } } if (profile.Id == 0) db.Profiles.Add(profile); else db.Entry(profile).State = EntityState.Modified; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = profile.Id; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult Submit(int profileId) { var result = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(profileId); if (profile != null) { profile.StatusId = (int)ProfileStatusEnum.Pending; if (profile.Lender != null) profile.Lender.StatusId = (int)ProfileStatusEnum.Pending; if (profile.Borrower != null) profile.Borrower.StatusId = (int)ProfileStatusEnum.Pending; var password = new Random(100000).Next(999999).ToString(); var hash = profile.Id.ToEncryptedString(); db.Users.Add(new User { UserName = profile.EmailAddress.ToLower(), ProfileId = profile.Id, Name = profile.Name, Surname = profile.Surname, SignUpDate = DateTime.Now, MustChangePassword = true, IsActive = false, Password = password.Encrypt(hash), PasswordHash = hash, RoleId = (int)UserRoleEnum.Buddy }); db.SaveChanges(); var token_ = TokenManager.Generate(profile.EmailAddress); var url = ConfigurationManager.AppSettings["VerifyUrl"].Replace("_token", token_); var mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[url]", url}, { "[username]",profile.EmailAddress }, { "[password]",$"Temp Password (Please change when logged in): {password}" }, { "[profileNumber]", profile.ProfileNumber } }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.ProfileRegistered.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, "Account Created - Buddy Finance", null); result.Result = Mappers.Profiles.MapFromModel(profile); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "success"; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = $"Could not find profile with id {profileId}"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public UpdateBankingDetailsResult UpdateBankingDetails(Models.BankingDetail bankingDetails) { var result = new UpdateBankingDetailsResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(bankingDetails.ProfileId); if (profile != null) { var updateBankingDetails = profile.BankingDetail ?? new BuddyFinance.Model.BankingDetail(); updateBankingDetails.AccountName = bankingDetails.AccountName; updateBankingDetails.AccountType = bankingDetails.AccountType; updateBankingDetails.AccountNumber = bankingDetails.AccountNumber; updateBankingDetails.BankName = bankingDetails.BankName; //updateBankingDetails.BranchCode = bankingDetails.BranchCode; //updateBankingDetails.BranchName = bankingDetails.BranchName; //if (updateBankingDetails.Id == 0) // db.BankingDetails.Add(updateBankingDetails); //else // db.Entry(updateBankingDetails).State = EntityState.Modified; profile.BankingDetail = updateBankingDetails; db.Entry(profile).State = EntityState.Modified; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = profile.Id; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Could not find profile with the specified ID"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult UpdateNextOfKin(Models.Profiles.NextOfKin nextOfKin) { var result = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(nextOfKin.ProfileId); if (profile != null) { var updateNextOfKin = profile.NextOfKin ?? new BuddyFinance.Model.NextOfKin(); updateNextOfKin.Name = nextOfKin.NextOfKinName; updateNextOfKin.ContactNumber = nextOfKin.NextOfKinContactNumber; updateNextOfKin.RelationshipType = nextOfKin.RelationshipType; updateNextOfKin.Income = nextOfKin.Income; profile.NextOfKin = updateNextOfKin; db.Entry(profile).State = EntityState.Modified; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = profile.Id; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Could not find profile with the specified ID"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public UpdateEmploymentResult UpdateEmployment(Models.EmploymentDetail employmentDetail) { var result = new UpdateEmploymentResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(employmentDetail.ProfileId); if (profile != null) { profile.EmploymentStatusId = employmentDetail.EmploymentStatusId; Model.EmploymentDetail updateEmploymentDetails = profile.EmploymentDetail ?? new BuddyFinance.Model.EmploymentDetail(); ; //if (employmentDetail.EmploymentStatusId == (int)EmploymentStatusEnum.Unemployed) //{ // //updateEmploymentDetails = new Model.EmploymentDetail // //{ // //updateEmploymentDetails.GrossMonthlyIncome = employmentDetail.GrossMonthlyIncome // // profile.BillingDate = employmentDetail.BillingDate ?? DateTime.Now; // //}; //} //else //{ //updateEmploymentDetails = profile.EmploymentDetail ?? new BuddyFinance.Model.EmploymentDetail(); //if (employmentDetail.EmploymentStatusId == (int)EmploymentStatusEnum.Student // || employmentDetail.EmploymentStatusId == (int)EmploymentStatusEnum.Unemployed) //{ // updateEmploymentDetails = new Model.EmploymentDetail // { // GrossMonthlyIncome = employmentDetail.GrossMonthlyIncome // }; //} //else //{ // updateEmploymentDetails.SalaryDay = employmentDetail.SalaryDay; // if (employmentDetail.EmploymentStatusId == (int)EmploymentStatusEnum.SelfEmployed) // { // //updateEmploymentDetails = new Model.EmploymentDetail // //{ // // GrossMonthlyIncome = employmentDetail.GrossMonthlyIncome, // // EmployerName = employmentDetail.EmployerName // //}; // } // else // { // updateEmploymentDetails.EmployerContactNumber = employmentDetail.EmployerContactNumber; updateEmploymentDetails.BillingDay = employmentDetail.BillingDay; updateEmploymentDetails.SalaryDay = employmentDetail.SalaryDay; updateEmploymentDetails.EmployerName = employmentDetail.EmployerName; updateEmploymentDetails.EmployerNumber = employmentDetail.EmployerNumber; updateEmploymentDetails.EmploymentEndDate = employmentDetail.EmploymentEndDate; updateEmploymentDetails.EmploymentStartDate = employmentDetail.EmploymentStartDate; updateEmploymentDetails.GrossMonthlyIncome = employmentDetail.GrossMonthlyIncome; updateEmploymentDetails.NetMonthlyIncome = employmentDetail.NetMonthlyIncome; updateEmploymentDetails.EmploymentTypeId = employmentDetail.EmploymentTypeId; //if (employmentDetail.EmploymentTypeId == (int)EmploymentTypeEnum.Permanent) //{ // updateEmploymentDetails.EmploymentTypeId = employmentDetail.EmploymentTypeId; //} //else //{ // updateEmploymentDetails.EmploymentTypeId = null; // //updateEmploymentDetails.EmploymentType = null; //} // } //} //} profile.EmploymentDetail = updateEmploymentDetails; db.Entry(profile).State = EntityState.Modified; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = profile.Id; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Could not find profile with the specified ID"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public UpdateTaxInformationResult UpdateTaxInformation(Models.TaxInformation taxInformation) { var result = new UpdateTaxInformationResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(taxInformation.ProfileId); if (profile != null) { profile.TaxRegistered = taxInformation.IsTaxRegistered; //if (taxInformation.IsTaxRegistered) //{ // var updatetaxInformation = profile.TaxInformation ?? new BuddyFinance.Model.TaxInformation(); // updatetaxInformation.TaxCountryId = (int)CountryEnum.SouthAfrica; //taxInformation.TaxCountry.Id; // updatetaxInformation.TaxIdentificationTypeId = taxInformation.TaxIdentificationType.Id; // updatetaxInformation.TaxNumber = taxInformation.TaxNumber; // profile.TaxInformation = updatetaxInformation; // db.SaveChanges(); //} //else //{ // profile.TaxInformation = null; //} //db.Entry(profile).State = EntityState.Modified; //db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = profile.Id; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Could not find profile with the specified ID"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult UpdateFica(Models.FicaCompliance ficaCompliance) { var result = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(ficaCompliance.ProfileId); if (profile != null) { var compliance = profile.FicaCompliance ?? new BuddyFinance.Model.FicaCompliance(); compliance.FicaStatusId = ficaCompliance.FicaStatus.Id; compliance.VerificationDate = ficaCompliance.VerificationDate; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = profile.Id; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "profile not found or does not exist."; //result.Result = false; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = "Failed to update Fica Compliance. "; result.ExceptionString = GetExeptionString(ex); } return result; } public GetProfileEarnings GetProfileEarning(int profileId) { var result = new GetProfileEarnings(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(profileId); if (profile != null) { double.TryParse(profile.EmploymentDetail?.GrossMonthlyIncome.ToString(), out double profileGross); Model.LoanEarningBracket earnings; Model.LoanTermBracket loanTerm; var earningList = db.LoanEarningBrackets.OrderBy(x => x.MinAmount).ToList(); var termList = db.LoanTermBrackets.OrderBy(m => m.MinAmount).ToList(); if (!earningList.Any() || !termList.Any()) { return new GetProfileEarnings { ErrorCode = (int)ResponseCodes.NotFound, ErrorMessage = "Could not find profile earning bracket" }; } var lowest = earningList.First(); if (profileGross < lowest.MinAmount) //Gross income not provided (EmploymentDetail.GrossMonthlyIncome is nullable) { earnings = lowest; loanTerm = termList.FirstOrDefault(m => lowest.MinAmount >= m.MinAmount); //arnings == null ? null : db.LoanTermBrackets.FirstOrDefault(n => earnings.MinAmount >= n.MinAmount && earnings.MinAmount <= n.MaxAmount); } else { earnings = earningList.Last(m => profileGross >= m.MinAmount); loanTerm = termList.Last(m => earnings.QualifyingAmount >= m.MaxAmount); // earnings = earningList.FirstOrDefault(x => x.MinAmount >= profileGross); // earnings = db.LoanEarningBrackets.ToList()//.OrderBy(m => m.MaxAmount).ToList() // .FirstOrDefault(n => profileGross >= n.MinAmount && profileGross <= n.MaxAmount); // db.LoanEarningBrackets.ToList().FirstOrDefault(n => n.MinAmount >= profileGross && n.MaxAmount <= profileGross); //&& n.MaxAmount <= profile.EmploymentDetail.GrossMonthlyIncome //loanTerm = db.LoanTermBrackets.FirstOrDefault(n => profileGross >= n.MinAmount && profileGross <= n.MaxAmount); } if (earnings == null || loanTerm == null) { result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = "Could find profile earnings. Please make sure Gross Monthly income is supplied on your employment details"; } else { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = new ProfileEarningsModel { LoanTerm = new Models.LoanOffers.LoanTermBracket { Id = loanTerm.Id, MinAmount = loanTerm.MinAmount, MaxAmount = loanTerm.MaxAmount, Duration = loanTerm.Duration }, Earnings = new Models.LoanOffers.LoanEarningBracket { Id = earnings.Id, MaxAmount = earnings.MaxAmount, QualifyingAmount = earnings.QualifyingAmount, MinAmount = earnings.MinAmount } }; } } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Profile not found."; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = "" + ex; } return result; } public GetProfileEarnings GetEarning() { var result = new GetProfileEarnings(); try { using (var db = new BuddyFinanceDBEntities()) { Model.LoanEarningBracket earnings; Model.LoanTermBracket loanTerm; earnings = db.LoanEarningBrackets.OrderBy(m => m.MinAmount).First(); loanTerm = earnings == null ? null : db.LoanTermBrackets.FirstOrDefault(n => earnings.MinAmount >= n.MinAmount && earnings.MinAmount <= n.MaxAmount); if (earnings == null || loanTerm == null) { result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = "Could find profile earnings"; } else { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = new ProfileEarningsModel { LoanTerm = new Models.LoanOffers.LoanTermBracket { Id = loanTerm.Id, MinAmount = loanTerm.MinAmount, MaxAmount = loanTerm.MaxAmount, Duration = loanTerm.Duration }, Earnings = new Models.LoanOffers.LoanEarningBracket { Id = earnings.Id, MaxAmount = earnings.MaxAmount, QualifyingAmount = earnings.QualifyingAmount, MinAmount = earnings.MinAmount } }; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = "" + ex; } return result; } public new BaseResult LoanCulculator(LoanCalculatorModel model) { return base.LoanCulculator(model); } public BaseResult ContactUs(Contact model) { var result = new BaseResult(); try { var mailDetails = new Dictionary { {"[names]",model.Name +" - " + model.Surname}, {"[Email]",model.Email }, {"[Subject]",model.Subject }, {"[Message]",model.Massege }, }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.ContactUs.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(ConfigurationManager.AppSettings["ContactUsEmail"], emailBody, "Contact Us Enquiry | Buddy Finance", null); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult Activate(int profileId, int type) { var result = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(profileId); if (profile != null) { NotificationTempate notificationType; string subject; if (type == (int)ProfileTypeEnum.Borrower) { notificationType = NotificationTempate.BorrowerAccountActivated; subject = "Borrower Account Activated"; if (profile.Borrower == null) { profile.Borrower = new Model.Borrower { ProfileTypeId = (int)ProfileTypeEnum.Borrower, BorrowerNumber = RegistrationsHelper.BorrowerPrefix + profile.ProfileNumber, StatusId = (int)ProfileStatusEnum.Pending }; } else { profile.Borrower.StatusId = (int)ProfileStatusEnum.Pending; } } else { notificationType = NotificationTempate.LenderAccountActivated; subject = "Lender Account Activated"; if (profile.Lender == null) { profile.Lender = new Model.Lender { ProfileTypeId = (int)ProfileTypeEnum.Lender, LenderNumber = RegistrationsHelper.LenderPrefix + profile.ProfileNumber, StatusId = (int)ProfileStatusEnum.Pending }; } else { profile.Lender.StatusId = (int)ProfileStatusEnum.Pending; } } db.SaveChanges(); var mailDetails = new Dictionary { {"[names]",profile.Name +" - " + profile.Surname}, {"[Email]",profile.EmailAddress }, {"[Cellphone]",profile.ContactNumber }, }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + notificationType + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, subject + " | Buddy Finance", null); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = true; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "profile not found or does not exist."; result.Result = false; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } } }