using BuddyFinance.Common.Encryption; using BuddyFinance.Integration.Logging; using BuddyFinance.Integration.Models; using BuddyFinance.Integration.Models.Enums; using BuddyFinance.Integration.Models.Registration; using BuddyFinance.Integration.Utils; using BuddyFinance.Model; using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity.Infrastructure; using System.Linq; /*Created 01 Sept 17 Tumelo * * */ namespace BuddyFinance.Integration { public class RegistrationIntegrator : BaseIntegrator { /// /// Create a new profile /// /// Profile data /// public RegistrationResult Register(NewProfileModel newProfile) { //model must have been validated before call to this method var registrationResult = new RegistrationResult(); try { //referenced entities must exist first using (var db = new BuddyFinanceDBEntities()) { if (db.Users.Any(m => m.UserName.Equals(newProfile.EmailAddress))) { registrationResult.ErrorCode = (int)ResponseCodes.ValidationError; registrationResult.ErrorMessage = "Email address already in use"; return registrationResult; } var profileDetails = new Profile() { ProfileNumber = RegistrationsHelper.GenerateProfileNumber(newProfile.ProfileTypeId), //Title = newProfile.Title, Name = newProfile.Name, Surname = newProfile.Surname, EmailAddress = newProfile.EmailAddress.ToLower(), ContactNumber = newProfile.ContactNumber, DateOfBirth = newProfile.DateOfBirth, GenderId = newProfile.GenderId, IdentificationNumber = newProfile.IdentificationNumber, //ProfileTypeId = newProfile.ProfileTypeId, //EthnicityId = newProfile.EthnicityId, //SourceOfIncomeId = newProfile.SourceOfIncomeId, EmploymentStatusId = newProfile.EmploymentDetail.EmploymentStatusId, //OtherSourceOfIncome = newProfile.OtherSourceOfIncome, CountryOfBirthId = (int)CountryEnum.SouthAfrica, IdentificationTypeId = (int)IdentificationTypeEnum.IdentityDocument, StatusId = (int)ProfileStatusEnum.Pending, FicaCompliance = new Model.FicaCompliance { FicaStatusId = (int)FicaStatusEnum.NotCompliant, VerificationDate = null }, //BillingDate = newProfile.ProfileTypeId == (int)ProfileTypeEnum.Lender ? newProfile.EmploymentDetail?.BillingDate ?? DateTime.Now : DateTime.Now, LastBillDate = DateTime.Now, //TaxRegistered = newProfile.TaxRegistered }; if (newProfile.ProfileTypeId == (int)ProfileTypeEnum.Lender) { profileDetails.LendServiceAccount = true; profileDetails.Lender = new Lender { ProfileTypeId = newProfile.ProfileTypeId, LenderNumber = profileDetails.ProfileNumber, StatusId = (int)ProfileStatusEnum.Pending, }; } else if (newProfile.ProfileTypeId == (int)ProfileTypeEnum.Borrower) { profileDetails.BorrowServiceAccount = true; profileDetails.Borrower = new Borrower { ProfileTypeId = newProfile.ProfileTypeId, BorrowerNumber = profileDetails.ProfileNumber, StatusId = (int)ProfileStatusEnum.Pending, }; } if (newProfile.BankingDetail != null) { profileDetails.BankingDetail = new Model.BankingDetail() { BankName = newProfile.BankingDetail.BankName, AccountName = newProfile.BankingDetail.AccountName, AccountNumber = newProfile.BankingDetail.AccountNumber, AccountType = newProfile.BankingDetail.AccountType, }; } if (newProfile.NextOfKin != null) { profileDetails.NextOfKin = new NextOfKin { Name = newProfile.NextOfKin.NextOfKinName, ContactNumber = newProfile.NextOfKin.NextOfKinContactNumber, RelationshipType = newProfile.NextOfKin.RelationshipType, }; } //List unemployedStatues = new List { (int)EmploymentStatusEnum.Student, (int)EmploymentStatusEnum.Unemployed }; //if (!unemployedStatues.Contains(newProfile.EmploymentStatusId)) //{ var defaultDate = new DateTime(1900, 01, 01); //Default Date in js if (newProfile.EmploymentDetail != null) { profileDetails.EmploymentDetail = new BuddyFinance.Model.EmploymentDetail() { //EmployerContactNumber = newProfile.EmploymentDetail.EmployerContactNumber, EmployerName = newProfile.EmploymentDetail.EmployerName, EmployerNumber = newProfile.EmploymentDetail.EmployerNumber, EmploymentEndDate = newProfile.EmploymentDetail.EmploymentEndDate <= defaultDate ? null : newProfile.EmploymentDetail.EmploymentEndDate, EmploymentStartDate = newProfile.EmploymentDetail.EmploymentStartDate <= defaultDate ? null : newProfile.EmploymentDetail.EmploymentStartDate, SalaryDay = newProfile.EmploymentDetail.SalaryDay, BillingDay = newProfile.EmploymentDetail.BillingDay, EmploymentTypeId = newProfile.EmploymentDetail.EmploymentTypeId == 0 ? null : newProfile.EmploymentDetail.EmploymentTypeId, GrossMonthlyIncome = newProfile.EmploymentDetail.GrossMonthlyIncome }; } //} //if (newProfile.TaxRegistered) //{ // profileDetails.TaxInformation = new BuddyFinance.Model.TaxInformation() // { // TaxCountryId = (int)CountryEnum.SouthAfrica, //newProfile.TaxInformation.TaxCountryId, // TaxIdentificationTypeId = newProfile.TaxInformation.TaxIdentificationTypeId, // TaxNumber = newProfile.TaxInformation.TaxNumber // }; //} if (newProfile.Addresses != null && newProfile.Addresses.Any()) { profileDetails.ProfileAddresses = newProfile.Addresses.ConvertAll(m => new ProfileAddress { AddressTypeId = m.AddressType.Id, Line1 = m.Line1, Line2 = m.Line2, City = m.City, PostalCode = m.PostalCode, ProvinceId = m.Province.Id, //CountryId = m.Country.Id CountryId = (int)CountryEnum.SouthAfrica }); } var errors = new List(); if (newProfile.Documents != null && newProfile.Documents.Any()) { profileDetails.ProfileDocuments = new List(); newProfile.Documents.ForEach(m => { byte[] contents; try { contents = Convert.FromBase64String(m.FileData.Contents); profileDetails.ProfileDocuments.Add(new ProfileDocument { DocumentTypeId = m.DocumentType.Id, UploadedDate = DateTime.Now, FileData = new FileData { FileName = m.FileData.FileName, Contents = contents, ContentType = m.FileData.ContentType, Size = m.FileData.Size, FileUrl = "" // ?!! } }); } catch (Exception ex) { errors.Add(ex.Message); } }); } if (errors.Any()) { var message = ""; errors.ForEach(m => { message += m + "\n"; }); registrationResult.ErrorCode = (int)ResponseCodes.ValidationError; registrationResult.ErrorMessage = message; } else { db.Profiles.Add(profileDetails); db.SaveChanges(); //Create User Account try { var hash = profileDetails.Id.ToEncryptedString(); db.Users.Add(new User { UserName = profileDetails.EmailAddress.ToLower(), ProfileId = profileDetails.Id, //tumelo: 12 Jan 18 Name = profileDetails.Name, Surname = profileDetails.Surname, SignUpDate = DateTime.Now, //MustChangePassword = true, MustChangePassword = false, IsActive = false, Password = newProfile.Password.Encrypt(hash), PasswordHash = hash, // RoleId = newProfile.ProfileTypeId RoleId = (int)UserRoleEnum.Buddy //newProfile.ProfileTypeId == (int)ProfileTypeEnum.Lender //? (int)UserRoleEnum.Buddy //: (int)UserRoleEnum.Buddy }); db.SaveChanges(); registrationResult.VerificationToken = TokenManager.Generate(profileDetails.EmailAddress); registrationResult.ErrorCode = (int)ResponseCodes.Success; registrationResult.ErrorMessage = "Success"; registrationResult.Result = profileDetails.ProfileNumber; //send profile verification email .. var token_ = registrationResult.VerificationToken;// TokenManager.Generate(result.Result); var url = ConfigurationManager.AppSettings["VerifyUrl"].Replace("_token", token_);// Url.Link("Default", new { Controller = "Registration", Action = "Verify", token = token_, profileNumber = result.Result }); var mailDetails = new Dictionary { { "[names]", $"{newProfile.Name} {newProfile.Surname}" }, { "[url]", url}, { "[username]",newProfile.EmailAddress }, { "[password]", "" }, { "[profileNumber]", profileDetails.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(newProfile.EmailAddress, emailBody, "Account Created - Buddy Finance", null); } catch (DbUpdateException ex) { db.Profiles.Remove(profileDetails); db.SaveChanges(); registrationResult.ErrorCode = (int)ResponseCodes.Exception; registrationResult.ErrorMessage = ex.Message; } } } } catch (Exception ex) { registrationResult.ErrorCode = (int)ResponseCodes.Exception; registrationResult.ErrorMessage = ex.Message; } return registrationResult; } public VerifyRegistrationResult VerifyRegistration(string token, string profileNumber, string username) { var result = new VerifyRegistrationResult(); if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(profileNumber)) { result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = "Invalid token"; return result; } var valid = TokenManager.ValidateToken(token, profileNumber); if (valid) { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.FirstOrDefault(m => m.ProfileNumber.Equals(profileNumber, StringComparison.OrdinalIgnoreCase)); if (profile != null) { var user = profile.Users.FirstOrDefault(m => m.UserName.Equals(username)); if (user != null) { user.IsActive = true; user.AccountVerified = true; db.SaveChanges(); result.ErrorMessage = "Profile validated"; result.Result = valid; } else { result.ErrorMessage = "Could not validate profile"; result.Result = false; } } else { result.ErrorMessage = "Could not find profile with profile number '" + profileNumber + "'."; result.Result = false; } } } else { result.ErrorMessage = "Invalid token"; result.Result = false; } return result; } public ValidateOtpResult ValidateOtp(string otp, string number) { var result = new ValidateOtpResult(); if (string.IsNullOrEmpty(otp) || string.IsNullOrEmpty(number)) { result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = "Opt or number not valid"; return result; } var valid = TokenManager.ValidateOtp(otp, number); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = valid ? "Opt valid" : "invalid otp"; result.Result = valid; return result; } public SendOtpResult SendOtp(string number) { var result = new SendOtpResult(); try { var otp = TokenManager.GenerateOtp(number); var sent = _notifications.SendOtp(otp, number); if (sent) { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = otp; } else { result.ErrorCode = (int)ResponseCodes.Failure; result.ErrorMessage = $"Could not send OTP to {number}"; } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult ReApply(string profileNumber) { var result = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.FirstOrDefault(m => m.ProfileNumber.Equals(profileNumber)); if (profile != null) { if (profile.StatusId == (int)ProfileStatusEnum.Rejected) profile.ProfileApproval = null; profile.StatusId = (int)ProfileStatusEnum.Pending; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "success"; result.Result = true; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = $"profile number \"{profileNumber}\" does not exist"; result.Result = false; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = "Application could not be resent."; //ex.Message; result.ExceptionString = GetExeptionString(ex); } return result; } } }