using BuddyFinance.Common.Concepts; using BuddyFinance.Common.Encryption; using BuddyFinance.Integration.Mappers; using BuddyFinance.Integration.Models; using BuddyFinance.Integration.Models.Enums; using BuddyFinance.Integration.Models.ManageCash; using BuddyFinance.Model; using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Linq; /*Created : Manamela Tumelo * 03 November 17 * */ namespace BuddyFinance.Integration { public class ManageCashIntergrator : BaseIntegrator { public CashWithdrawalsResult CashWithdrawals(int? profileId = null) { var result = new CashWithdrawalsResult(); try { using (var db = new BuddyFinanceDBEntities()) { var withdrawalhistory = profileId == null ? db.CashWithdrawals.ToList() : db.CashWithdrawals.Where(t => t.ProfileId == profileId).ToList(); if (withdrawalhistory != null) { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.AvailableFunds = db.Profiles.Find(profileId)?.AvailableFunds ?? 0; result.Result = !withdrawalhistory.Any() ? new List() : withdrawalhistory.ToList().ConvertAll(m => new Models.ManageCash.CashWithdrawal { Id = m.Id, Amount = m.Amount, ProfileId = m.ProfileId, Date = m.Date, Status = m.StatusId, Comment = m.Comment, //BankingDetail = new Models.BankingDetail //{ // ProfileId = m.Profile.BankingDetail.ProfileId, // AccountName =m.Profile.BankingDetail.BankName, // AccountNumber = m.Profile.BankingDetail.AccountNumber, // BranchCode = m.Profile.BankingDetail.BranchCode, // AccountType = m.Profile.BankingDetail.AccountType, //} //BankDetailsID = m.BankDetailsID, // BankingDetail = m.Profile.BankingDetail == null ? null //: new Models.BankingDetail //{ // AccountName = m.Profile.BankingDetail.AccountName, // AccountNumber = m.Profile.BankingDetail.AccountNumber, // AccountType = m.Profile.BankingDetail.AccountType, // BankName = m.Profile.BankingDetail.BankName, // BranchCode = m.Profile.BankingDetail.BranchCode, // BranchName = m.Profile.BankingDetail.BranchName, //}, Profile = new Models.Profiles.Profile { ProfileId = m.ProfileId, Name = m.Profile.Name, Surname = m.Profile.Surname, FullNames = m.Profile.Name + " " + m.Profile.Surname, ProfileNumber = m.Profile.ProfileNumber }, User = m.User?.Name ?? m.User?.Profile?.Name + " " + m.User?.Surname ?? m.User?.Profile?.Surname, WithdrawalStatus = new Status { Id = m.StatusId, Description = m.CashWithdrawalStatus.Description }, RewiewDate = m.ReviewDate }); } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "No Withdrawals found."; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public CashDepositsResult CashDeposits(int? profileId = null) { var result = new CashDepositsResult(); try { using (var db = new BuddyFinanceDBEntities()) { var cashDepositHistory = profileId == null ? db.CashDeposits.ToList() : db.CashDeposits.Where(t => t.ProfileId == profileId).ToList(); //if (withdrawalhistory.Any()) //{ result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = !cashDepositHistory.Any() ? new List() : cashDepositHistory.ToList().ConvertAll(m => new Models.ManageCash.CashDeposit { Id = m.Id, Amount = m.Amount, ProfileId = m.ProfileId, Date = m.Date, Comment = m.Comment, Profile = new Models.Profiles.Profile { ProfileId = m.ProfileId, Name = m.Profile.Name, Surname = m.Profile.Surname, FullNames = m.Profile.Name + " " + m.Profile.Surname, ProfileNumber = m.Profile.ProfileNumber }, UserId = m.UserId, User = m.User?.Name ?? m.User?.Profile?.Name + " " + m.User?.Surname ?? m.User?.Profile.Surname }); } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public BaseResult Funds(int profileId) { var response = new BaseResult(); try { using (var db = new BuddyFinanceDBEntities()) { var diposits = db.CashDeposits.Where(m => m.ProfileId == profileId).ToList(); var withdrawals = db.CashWithdrawals.Where(m => m.ProfileId == profileId).ToList(); response.ErrorCode = (int)ResponseCodes.Success; response.ErrorMessage = "Sucess"; response.Result = new ProfileFundsModel { Diposits = !diposits.Any() ? new List() : diposits.ConvertAll(m => new Models.ManageCash.CashDeposit { Id = m.Id, Date = m.Date, ProfileId = m.ProfileId, Amount = m.Amount, Comment = m.Comment, }), Withdrawals = !withdrawals.Any() ? new List() : withdrawals.ConvertAll(m => new Models.ManageCash.CashWithdrawal { Id = m.Id, Date = m.Date, ProfileId = m.ProfileId, WithdrawalStatus = new Status { Id = m.StatusId, Description = m.CashWithdrawalStatus.Description }, Amount = m.Amount, BankingDetail = m.Profile.BankingDetail.ToViewModel(), Comment = m.Comment, Status = m.StatusId, RewiewDate = m.ReviewDate }) }; } } catch (Exception ex) { response.ErrorCode = (int)ResponseCodes.Exception; response.ErrorMessage = "Could not load profile funds"; response.ExceptionString = GetExeptionString(ex); } return response; } //Get Availble Funds and display it public GetManageAvailableCash ManageAvailableCash(int id) { var result = new GetManageAvailableCash(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(id); if (profile != null) { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = profile.AvailableFunds; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Not Found"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } //Get Cashdeposits Funds and display it public GetManageCashDeposit ManageCashDeposit(int id) { var result = new GetManageCashDeposit(); try { using (var db = new BuddyFinanceDBEntities()) { var cashdeposits = db.CashDeposits.Where(t => t.ProfileId == id).ToList(); var cashdeposit = cashdeposits.Sum(t => t.Amount); //if (cashdeposit != 0) //{ result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = cashdeposit; //} //else //{ // result.ErrorCode = (int)ResponseCodes.NotFound; // result.ErrorMessage = "Not Found"; //} } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } //Get Cashdeposits Funds and display it :Tumelo 07 02 2017 public GetManageCashWithdrawal ManageCashWithdrawal(int id) { var result = new GetManageCashWithdrawal(); try { using (var db = new BuddyFinanceDBEntities()) { var cashwithdrawals = db.CashWithdrawals.Where(t => t.ProfileId == id && t.StatusId != (int)CashWithdrawalEnum.Cancelled && t.StatusId != (int)CashWithdrawalEnum.Rejected).Sum(t => t.Amount); if (cashwithdrawals != 0) { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = cashwithdrawals; } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Not Found"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } //Load Cash into Profile Available funds and cash deposits public CashDepositResult SaveFundsToProfile(int id, double amount, string userId, string comment) { var result = new CashDepositResult(); var depositAmount = amount; try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(id); var buddyFianceProfile = db.Profiles.Find(Constants.BuddyFinanceProfileId); //.ToList().Find(m => m.ProfileTypeId == (int)ProfileTypeEnum.BuddyFinance); if (profile != null) { var dep = new Model.CashDeposit { ProfileId = id, Date = DateTime.Now, Amount = depositAmount, Comment = comment ?? "Account Credit", UserId = userId.ToDecryptedInt() }; var tx = new Model.Transaction { Amount = depositAmount, Description = "Cash Deposit - " + profile.ProfileNumber, Reference = profile.ProfileNumber, TransactionDate = DateTime.Now, ProfileId = profile.Id, TransactionStatusId = (int)TransactionStatusEnum.Success, TransactionTypeId = (int)TransactionTypeEnum.Credit, ProfileTypeId = (int)ProfileTypeEnum.Lender }; if (profile.IdentificationTypeId == (int)ProfileTypeEnum.Lender && !profile.CashDeposits.Any()) { var fee = _fees[FeeTypesEnum.ApplicationFee]; tx.TransactionFees.Add(new Model.TransactionFee { FeeAmount = fee.Amount, FeeTypeId = fee.Id, }); tx.Description = "Cash Deposit: Application fee deducted"; var bfTx = new Model.Transaction { Amount = fee.Amount, Description = "Application Fee for profile - " + profile.ProfileNumber, Reference = profile.ProfileNumber, TransactionDate = DateTime.Now, ProfileId = Constants.BuddyFinanceProfileId, TransactionStatusId = (int)TransactionStatusEnum.Success, TransactionTypeId = (int)TransactionTypeEnum.Credit, ProfileTypeId = (int)ProfileTypeEnum.BuddyFinance }; db.Transactions.Add(bfTx); db.Transactions.Add(new Transaction { Amount = fee.Amount, ProfileId = profile.Id, TransactionTypeId = (int)TransactionTypeEnum.Debit, Description = "Profile Application fee", TransactionDate = DateTime.Now, TransactionStatusId = (int)TransactionStatusEnum.Success, Reference = profile.ProfileNumber, ProfileTypeId = (int)ProfileTypeEnum.Lender }); profile.AvailableFunds -= fee.Amount; buddyFianceProfile.AvailableFunds += fee.Amount; } profile.AvailableFunds += depositAmount; db.CashDeposits.Add(dep); db.Transactions.Add(tx); db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = profile.AvailableFunds; var user = db.Users.Find(userId.ToDecryptedInt()); result.CashDeposit = new { Date = dep.Date.ToString("d MMMM yyyy hh:mm tt"), Amount = dep.Amount.ToString("C2"), profile.ProfileNumber, ProfileName = profile.FullNames, User = user?.Name + " " + user?.Surname, Comment = dep.Comment }; } 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; } // withdraw cash withdrawal public GetCashWithdrawalRequest WithdrawalRequest(ManageCashModel manageCashModel) { var result = new GetCashWithdrawalRequest(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Set().Find(manageCashModel.ProfileId); if (profile != null) { var withdrawalrequest = db.CashWithdrawals.Find(manageCashModel.ProfileId);// ?? new ManageCashModel(); if (manageCashModel.ProfileId != 0) //updating { profile.AvailableFunds += manageCashModel.AvailableFunds; db.SaveChanges(); if (withdrawalrequest.Id == 0) db.CashWithdrawals.Add(withdrawalrequest); else db.Entry(withdrawalrequest).State = EntityState.Modified; } } 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; } //request cash withdrawal :Tumelo public ValidateWithdrawalRequestResult ValidateWithdrawalRequest(WithdrawalRequestModel model) { var response = new ValidateWithdrawalRequestResult(); try { if (!string.IsNullOrWhiteSpace(model.ProfileId_)) model.ProfileId = model.ProfileId_.ToDecryptedInt(); using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(model.ProfileId); var requested = model.Amount.ToString("N2"); var appendmsg = ""; if (profile.AvailableFunds < model.Amount) { model.Amount = profile.AvailableFunds; appendmsg = $" has been adjusted to the available balance of R {model.Amount.ToString("N2")} and"; } var fee = _fees[FeeTypesEnum.WithdrawalFee]; var feeAmount = model.Amount <= fee.Basis ? fee.Amount : model.Amount * fee.Percentage; if (profile.AvailableFunds < (model.Amount + feeAmount)) { var validAmt = model.Amount - feeAmount; response.Result = false; response.ErrorCode = 0; response.ErrorMessage = $"Withdrawal amount of R {requested}{appendmsg} will be processed less withdrawal fee. Available amount is R {validAmt.ToString("N2")}"; response.ValidatedAmount = validAmt; return response; } else { response.Result = true; response.ValidatedAmount = model.Amount + feeAmount; response.ErrorCode = 0; } } } catch (Exception ex) { response.ErrorCode = (int)ResponseCodes.Exception; response.ErrorMessage = ex.Message; } return response; } public WithdrawalRequestResult RequestCashWithdrawal(WithdrawalRequestModel model) { var response = new WithdrawalRequestResult(); try { if (!string.IsNullOrWhiteSpace(model.ProfileId_)) model.ProfileId = model.ProfileId_.ToDecryptedInt(); using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(model.ProfileId); if (profile != null) { if (profile.AvailableFunds < model.Amount) model.Amount = profile.AvailableFunds; var fee = _fees[FeeTypesEnum.WithdrawalFee]; var feeAmount = model.Amount <= fee.Basis ? fee.Amount : model.Amount * fee.Percentage; if (profile.BankingDetail == null) { response.MustUpdateBanking = true; response.ErrorCode = (int)ResponseCodes.NotFound; response.ErrorMessage = "Sorry you can not make cash withdrawal request until you update your banking details on your profile."; } else { if (model.Amount <= 99) { response.ErrorCode = (int)ResponseCodes.Exception; response.ErrorMessage = "The minimum withdrawal amount you can request is R 100."; } else { if ((profile.AvailableFunds - model.Amount) >= 0) { var request = model.MapToEntityModel(model.Amount); if (profile.AvailableFunds >= model.Amount) { if (request.Id == 0) db.CashWithdrawals.Add(request); else db.Entry(request).State = EntityState.Modified; db.SaveChanges(); response.ErrorCode = (int)ResponseCodes.Success; response.ErrorMessage = "Success"; var mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[amount]", model.Amount.ToString("N2")}, }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.CashWithdrawal.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, "Request Cash Withdrawal | Buddy Finance", null); } else { response.ErrorCode = (int)ResponseCodes.Failure; response.ErrorMessage = "Insufficient Funds. If you have any inactive Loan offer(S), you can delete them and try withdraw again."; } } else { response.ErrorCode = (int)ResponseCodes.Failure; response.ErrorMessage = "Insufficient Funds. If you have any in active Loan offer(S), you can delete them and try withdraw again."; } } } } else { response.ErrorCode = (int)ResponseCodes.NotFound; response.ErrorMessage = "Profile Not Found"; } } } catch (Exception ex) { response.ErrorCode = (int)ResponseCodes.Exception; response.ErrorMessage = ex.Message; } return response; } //cash Withdrawal History public CashWithdrawalsResult CashWithdrawalsResult(int profileId) { var result = new CashWithdrawalsResult(); try { using (var db = new BuddyFinanceDBEntities()) { var withdrawalhistory = db.CashWithdrawals.Where(t => t.ProfileId == profileId).OrderByDescending(t => t.Date).ToList(); //if (withdrawalhistory.Any()) //{ result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = !withdrawalhistory.Any() ? new List() : withdrawalhistory.ToList().ConvertAll(m => new Models.ManageCash.CashWithdrawal { Id = m.Id, Amount = m.Amount, ProfileId = m.ProfileId, Date = m.Date, Status = m.StatusId, Comment = m.Comment, RewiewDate = m.ReviewDate, //BankDetailsID = m.BankDetailsID, BankingDetail = new Models.BankingDetail { AccountName = m.Profile.BankingDetail.AccountName, AccountNumber = m.Profile.BankingDetail.AccountNumber, AccountType = m.Profile.BankingDetail.AccountType, BankName = m.Profile.BankingDetail.BankName, //BranchCode = m.Profile.BankingDetail.BranchCode, //BranchName = m.Profile.BankingDetail.BranchName, } }); } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } //Accept cash withdrawal requests Modified :Tumelo 29 Nov 17 public AcceptCashWithdrawal AcceptCashWithdrawal(int id, int currentUserId) { var result = new AcceptCashWithdrawal(); try { using (var db = new BuddyFinanceDBEntities()) { var withdraw = db.CashWithdrawals.Find(id); if (withdraw != null) { var profile = db.Profiles.Find(withdraw.ProfileId); var buddyProfile = db.Profiles.Find(Constants.BuddyFinanceProfileId); var fee = _fees[FeeTypesEnum.WithdrawalFee]; var feeAmount = withdraw.Amount <= fee.Basis ? fee.Amount : withdraw.Amount * fee.Percentage; var withdrawalAmount = profile.AvailableFunds >= (withdraw.Amount + feeAmount) ? withdraw.Amount : withdraw.Amount - feeAmount; if (profile.AvailableFunds >= withdrawalAmount) { profile.CashWithdrawal = profile.CashWithdrawal ?? 0; profile.AvailableFunds -= withdrawalAmount; profile.CashWithdrawal += (withdrawalAmount + feeAmount); withdraw.ReviewDate = DateTime.Now; withdraw.ReviewerId = currentUserId; withdraw.StatusId = (int)CashWithdrawalEnum.Approved; var tx = new Transaction { Amount = withdrawalAmount, Description = "Cash withdrawal - " + profile.ProfileNumber, Reference = profile.ProfileNumber, TransactionDate = DateTime.Now,//loanoffer.DateCreated, ProfileId = withdraw.ProfileId, ProfileTypeId = (int)ProfileTypeEnum.Lender, TransactionStatusId = (int)TransactionStatusEnum.Success, TransactionTypeId = (int)TransactionTypeEnum.Debit, }; db.Transactions.Add(tx); db.Transactions.Add(new Transaction { Amount = feeAmount, Description = "Cash withdrawal Fee - " + profile.ProfileNumber, Reference = profile.ProfileNumber, TransactionDate = DateTime.Now, ProfileId = withdraw.ProfileId, ProfileTypeId = (int)ProfileTypeEnum.Lender, TransactionStatusId = (int)TransactionStatusEnum.Success, TransactionTypeId = (int)TransactionTypeEnum.Credit, }); profile.AvailableFunds -= feeAmount; if (buddyProfile != null) buddyProfile.AvailableFunds += feeAmount; db.Transactions.Add(new Transaction { Amount = feeAmount, Description = "Cash withdrawal Fee - " + profile.ProfileNumber, Reference = profile.ProfileNumber, TransactionDate = DateTime.Now, ProfileId = buddyProfile.Id, ProfileTypeId = (int)ProfileTypeEnum.BuddyFinance, TransactionStatusId = (int)TransactionStatusEnum.Success, TransactionTypeId = (int)TransactionTypeEnum.Credit, }); db.SaveChanges(); var mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[amount]", $"{withdrawalAmount.ToString("N2")}" } }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.CashWithdrawalApproved.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, "Cash Withdrawal Approved | Buddy Finance", null); var withdral_ = db.CashWithdrawals.Find(withdraw.Id); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.NewStatusMessage = withdral_.CashWithdrawalStatus.Description + " on " + withdral_.ReviewDate.GetValueOrDefault().ToString("dd MMM yyyy hh:mm tt"); result.Actor = db.Users.Find(currentUserId).Name; } else { //profile do not have sufficient funds result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = "Insufficient Funds"; //send mail to profile holder stating that their availble funds is not enough var mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[amount]", $"{(int)withdraw.Amount}" } }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.CashWithdrawalRejected.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, "Cash Withdrawal Rejected | Buddy Finance", null); } //db.SaveChanges(); } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Cash withdrawal not found"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } public CancelCashWithdrawaRequest CancelCashWithdrawalRequest(int id) { var result = new CancelCashWithdrawaRequest(); try { using (var db = new BuddyFinanceDBEntities()) { var withdraw = db.CashWithdrawals.Find(id); if (withdraw != null) { var profile = db.Profiles.Find(withdraw.ProfileId); withdraw.StatusId = (int)CashWithdrawalEnum.Cancelled; db.SaveChanges(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; //send mail to profile holder :cash withdrawal request have been cancelled //var mailDetails = new Dictionary // { // { "[names]", $"{profile.Name} {profile.Surname}" }, // { "[amount]", $"{(int)withdraw.Amount}" } // }; //var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempates.CashWithdrawalRejected.ToString() + ".txt"); //var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); //_notifications.SendEmail(profile.EmailAddress, emailBody, "", null); } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Cash withdrawal request not found."; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } //display all cash withdrawal requests public CashWithdrawalsResult WithdrawalRequests() { var result = new CashWithdrawalsResult(); try { using (var db = new BuddyFinanceDBEntities()) { var withdrawalhistory = db.CashWithdrawals.ToList(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = !withdrawalhistory.Any() ? new List() : withdrawalhistory.ToList().ConvertAll(m => new Models.ManageCash.CashWithdrawal { Id = m.Id, Amount = m.Amount, ProfileId = m.ProfileId, Date = m.Date, Status = m.StatusId, Comment = m.Comment, RewiewDate = m.ReviewDate, //BankDetailsID = m.BankDetailsID, BankingDetail = new Models.BankingDetail { AccountName = m.Profile.BankingDetail.AccountName, AccountNumber = m.Profile.BankingDetail.AccountNumber, AccountType = m.Profile.BankingDetail.AccountType, BankName = m.Profile.BankingDetail.BankName, //BranchCode = m.Profile.BankingDetail.BranchCode, //BranchName = m.Profile.BankingDetail.BranchName, }, Profile = new Models.Profiles.Profile { ProfileNumber = m.Profile.ProfileNumber, Name = m.Profile.Name, Surname = m.Profile.Surname, FullNames = m.Profile.Name + " " + m.Profile.Surname, CashDeposit = m.Profile.CashDeposit ?? 0, CashWithdrawal = m.Profile.CashWithdrawal ?? 0 } }); } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; } return result; } //Incomplete code: Buddy finance can not reject cash with drawal request at this moment .Tumelo public RejectCashWithdrawalRequest RejectCashWithdrawalRequest(int id, int currentUserId, string rejectReason) { var result = new RejectCashWithdrawalRequest(); try { using (var db = new BuddyFinanceDBEntities()) { var withdrawl = db.CashWithdrawals.Find(id); if (withdrawl != null) { result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; withdrawl.ReviewDate = DateTime.Now; withdrawl.ReviewerId = currentUserId; withdrawl.Comment = rejectReason; withdrawl.StatusId = (int)CashWithdrawalEnum.Rejected; db.SaveChanges(); var profile = db.Profiles.Find(withdrawl.ProfileId); if (profile != null) { //deduct x amount for withdrawal and add it ass transaction } //send email for rejection :( var mailDetails = new Dictionary { { "[names]", $"{profile.Name} {profile.Surname}" }, { "[amount]", $"{(int)withdrawl.Amount}" } }; var templateText = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TemplatesPath"] + NotificationTempate.CashWithdrawalRejected.ToString() + ".txt"); var emailBody = mailDetails.Aggregate(templateText, (item, m) => item.Replace(m.Key, m.Value)); _notifications.SendEmail(profile.EmailAddress, emailBody, "Cashwithdrawal Rejected | Buddy Finance", null); } else { result.ErrorCode = (int)ResponseCodes.NotFound; result.ErrorMessage = "Not found"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; //throw; } return result; } public ManualDeductionsResult ManualDeductions(int? profileId = null) { var result = new ManualDeductionsResult(); try { using (var db = new BuddyFinanceDBEntities()) { var deductions = profileId == null ? db.ManualDeductions.ToList() : db.ManualDeductions.Where(m => m.ProfileId == profileId).ToList(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = !deductions.Any() ? new List() : deductions.ConvertAll(m => new Models.ManageCash.ManualDeduction { Id = m.Id, Amount = m.Amount, DeductionDate = m.DeductionDate, Description = m.Description, ProfileId = m.ProfileId, Profile = m.Profile.FullNames, ProfileNumber = m.Profile.ProfileNumber, UserId = m.UserId, User = m.User?.Name ?? m.User?.Profile?.Name + " " + m.User?.Surname ?? m.User?.Profile.Surname }); } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; result.ExceptionString = GetExeptionString(ex); } return result; } public ManualDeductionResult SaveManualDeduction(Models.ManageCash.ManualDeduction manualDeduction) { var result = new ManualDeductionResult(); try { using (var db = new BuddyFinanceDBEntities()) { var profile = db.Profiles.Find(manualDeduction.ProfileId); if (profile != null && profile.AvailableFunds >= manualDeduction.Amount) { var deduction = db.ManualDeductions.Find(manualDeduction.Id) ?? new Model.ManualDeduction(); deduction.Amount = manualDeduction.Amount; deduction.Description = manualDeduction.Description; deduction.ProfileId = manualDeduction.ProfileId; deduction.UserId = manualDeduction.UserId; deduction.DeductionDate = DateTime.Now; if (deduction.Id == 0) { db.ManualDeductions.Add(deduction); profile.AvailableFunds -= manualDeduction.Amount; } else { db.Entry(deduction).State = EntityState.Modified; } db.SaveChanges(); #region Transactions db.Transactions.Add(new Transaction { Amount = manualDeduction.Amount, Description = manualDeduction.Description, ProfileId = profile.Id, ProfileTypeId = (int)ProfileTypeEnum.Lender, TransactionDate = DateTime.Now, TransactionTypeId = (int)TransactionTypeEnum.Debit, Reference = "Manual Deduction: " + deduction.Id, TransactionStatusId = (int)TransactionStatusEnum.Success }); db.Transactions.Add(new Transaction { Amount = manualDeduction.Amount, Description = manualDeduction.Description, ProfileId = Constants.BuddyFinanceProfileId, ProfileTypeId = (int)ProfileTypeEnum.BuddyFinance, TransactionDate = DateTime.Now, TransactionTypeId = (int)TransactionTypeEnum.Credit, Reference = "Manual Deduction: " + deduction.Id, TransactionStatusId = (int)TransactionStatusEnum.Success }); db.SaveChanges(); #endregion var deduction_ = db.ManualDeductions.Find(deduction.Id); db.Entry(deduction_).Reference("Profile").Load(); db.Entry(deduction_).Reference("User").Load(); result.ErrorCode = (int)ResponseCodes.Success; result.ErrorMessage = "Success"; result.Result = deduction.Id; result.ManualDeduction = new { DeductionDate = deduction_.DeductionDate.ToString("d MMM yyyy hh:mm"), Amount = deduction_.Amount.ToString("C2"), deduction_.Profile.ProfileNumber, Profile = deduction_.Profile.FullNames, User = deduction_.User?.Name ?? deduction_.User?.Profile?.Name + " " + deduction_.User?.Surname ?? deduction_.User?.Profile.Surname }; } else { result.ErrorCode = (int)ResponseCodes.ValidationError; result.ErrorMessage = "Profile not found or has insufficient funds"; } } } catch (Exception ex) { result.ErrorCode = (int)ResponseCodes.Exception; result.ErrorMessage = ex.Message; result.ExceptionString = GetExeptionString(ex); } return result; } } }