// Home page Controller
vendor.controller('homeCtrl', ['$rootScope', '$scope', 'appInfo', '$location', '$stateParams', 'ngDialog', '$timeout', 'Storage', '$state', '$interval', function ($rootScope, $scope, appInfo, $location, $stateParams, ngDialog, $timeout, Storage, $state, $interval) {
$scope.currentStep = -1;
$scope.tryNewBeta = TRUE;
$scope.D = {};
$rootScope.clickToOpen = _.debounce(function ($scope) {
$rootScope.agree = { 'LoginTerm': false };
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-LoginTemplate.html?v=' + RELEASE_VERSION,
controller: 'homeCtrl',
scope: $scope,
});
}, 1000);
function processLoginResponse(response) {
$rootScope.UserPermissionModule = null;
if ([200, 632].indexOf(response.ResponseCode) != -1) {
if (response.ResponseCode == 632) {
$rootScope.persistentMessage = response.Message;
Storage.setItem('persistentMessage', $rootScope.persistentMessage);
};
location.reload();
$rootScope.SignIn = response.Data;
$rootScope.SignedIn = true;
appInfo.getSocketData();
if (typeof (Storage) !== "undefined") {
Storage.setItem('SignIn', $rootScope.SignIn);
}
appInfo.getCompanyPermissions(function () {
}, {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
}, TRUE)
ngDialog.close();
if ($rootScope.EmulatedMode) {
$rootScope.EmulatedMode.UserID = $rootScope.SignIn.UserDetails.UserID;
Storage.removeItem('uaInfo');
}
if ($rootScope.SignIn.ChangePassword) {
$timeout(function () {
angular.element('#cmdChangePassword').trigger('click');
}, 1000);
}
if ($rootScope.Page.Referer) {
$location.path($rootScope.Page.Referer);
delete $rootScope.Page.Referer;
}
else
$location.path($rootScope.SignIn.LandingPage);
if ($rootScope.SignIn.ModifiedDate == '0000-00-00 00:00:00') {
ngDialog.open({
template: $rootScope.baseURL + '/partials/new-home-pages/1.html?v=' + RELEASE_VERSION,
className: 'ng-popup ngdialog-theme-default custom-width',
closeByEscape: false,
closeByDocument: false,
showClose: false
});
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$rootScope.Page.untrackLoading('signin');
}
$scope.$on('$stateChangeSuccess', function (event) {
pathParts = $location.$$url.split('/');
if (pathParts.length > 1) {
switch (pathParts[1]) {
case 'recoverpassword':
$timeout(function () { $scope.openSecond(); }, 500);
break;
case 'signout':
if ($rootScope.SignIn) {
var reqData = {
"SignOut": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
$scope.Page.trackLoading('signing-out');
appInfo.disconnectSocket();
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.SignIn = false;
Storage.clear();
clearTimeout($scope.nextNotificationCall);
if (response.Data.LandingPage) {
location.href = response.Data.LandingPage;
}
delete $rootScope.companyPermissions;
Storage.setItem('CompanyPreferences', $rootScope.CompanyPreferences);
Storage.setItem('uaInfo', $rootScope.uaInfo);
$rootScope.persistentMessage = '';
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('signing-out');
}, function () {
Storage.clear();
location.reload();
});
}
break;
case 'signin':
var EmuData = Storage.getEmulationData();
if (!_.isUndefined($rootScope.SignIn))
return;
$rootScope.SignIn = null;
if (EmuData && EmuData.emulate) {
var reqData = {
"EmulateLogin": {
"LoginSessionKey": EmuData.SignIn.LoginSessionKey,
"LoginKeyword": EmuData.emulate.LoginKeyword,
"CompanyID": EmuData.emulate.CompanyID
}
};
appInfo.getServerData(reqData).then(processLoginResponse);
} else
$scope.clickToOpen();
break;
case 'changepassword':
if ($stateParams.authToken) {
$scope.authToken = $stateParams.authToken;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-changepassword.html',
scope: $scope
});
}
}
}
});
$rootScope.openSecond = function ($scope) {
var LoginTemplate = $rootScope.baseURL + '/partials/dlg-templates/dlg-LoginTemplate.html';
$timeout(function () { ngDialog.close(LoginTemplate); }, 10);
$timeout(function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-RecoverPassword.html',
controller: 'homeCtrl',
scope: $scope,
});
}, 550);
};
$rootScope.openLoginTerm = function ($scope) {
/*var LoginTemplate = $rootScope.baseURL+'/partials/dlg-templates/dlg-LoginTermTemplate.html';
$timeout(function(){ngDialog.close(LoginTemplate);},10);*/
$timeout(function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-LoginTermTemplate.html',
className: 'ng-popup ngdialog-theme-default ng-term custom-width',
controller: 'homeCtrl',
scope: $scope,
});
}, 550);
};
$scope.resetPassword = function () {
if (checkstatus('passwordResetForm', $scope)) {
$rootScope.forgetPasswordLink($scope.userName);
ngDialog.close();
}
};
$scope.closeSecond = function () {
ngDialog.close();
};
$scope.doUserLogin = function () {
$scope.rememberMe = (typeof $scope.rememberMe != 'undefined') ? $scope.rememberMe : 0;
$('#Resolution').val(screen.width + 'x' + screen.height);
$rootScope.Page.trackLoading('signin');
if (!$scope.tryNewBeta) {
function validateForm(formData, jqForm, options) {
var status = checkstatus('loginForm', $scope);
if (!status) {
$rootScope.Page.untrackLoading('signin');
// ShowMessageGlobal('error','The amount you entered is not acceptable.');
return false;
}
}
function successResponse(obj, statusText, xhr, $form) {
if (obj.ResponseCode == '200') {
window.location = obj.UserHome;
} else {
$scope.showFlashMessage('error', obj.Message);
}
$rootScope.Page.untrackLoading('signin');
}
$('#loginForm').ajaxForm({ cache: false, dataType: 'json', beforeSubmit: validateForm, success: successResponse }).submit();
} else {
var status = checkstatus('frmAddContact', $scope);
var pa = Storage.getItem('PartialApplications');
if (status) {
var reqData = {
"SignIn": {
"Username": $scope.Login.userName,
"Password": $scope.Login.userPassword,
"DeviceType": "Web",
"SocialType": "Web",
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"DeviceID": "Web",
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"ContinueAppWizard": pa ? pa.PartialAppUID : false,
"RememberMe": $scope.rememberMe
}
};
// appInfo.setLatLong(reqData.SignIn,function(){
appInfo.getServerData(reqData).then(processLoginResponse);
// });
} else {
$rootScope.Page.untrackLoading('signin');
}
}
}
$scope.Verify = function () {
var reqData = {
"VerifyCode": {
"Code": $stateParams.authToken,
"DeviceType": "Web",
"SocialType": "Web",
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"DeviceID": "Web",
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
};
if ($rootScope.SignIn)
reqData.VerifyCode.LoginSessionKey = $rootScope.SignIn.LoginSessionKey
if ($scope.PendingDetails) {
if (!checkstatus('frmPendingDetails', $scope))
return false;
reqData.VerifyCode.PendingDetails = $scope.PendingDetails;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showSuccess = true;
$scope.message = 'Successfully Verified';
delete $scope.PendingDetails;
$scope.SignIn.UserDetails.StatusID = 2;
$scope.persistentMessage = '';
// console.log('1',$scope.SignIn.UserDetails.StatusID,$scope.persistentMessage);
} else if (response.ResponseCode == 673) {
$scope.showSuccess = true;
$scope.message = response.Message;
$scope.PendingDetails = {};
} else {
$scope.showSuccess = false;
$scope.message = response.Message;
}
if (_.isUndefined($scope.PendingDetails) || ($scope.PendingDetails && response.ResponseCode == 200)) {
$scope.timer = 5;
$timeout($scope.CountDown, 1000);
}
});
}
if ($stateParams.authToken) {
if ($rootScope.CompanyPreferences)
$scope.Verify();
else
$scope.ProgramLoanType = $scope.CompanyPreferences.LoanType;
}
$scope.GoToHome = function (LoanType) {
$scope.ProgramLoanType = LoanType;
$state.go('calculator')
}
$scope.tabFlag = 1;
$scope.switchTab = function(tabNo) {
$scope.tabFlag = tabNo;
}
$scope.Login = { userName: "", userPassword: "" }; return;
}])
// Verification Controller
.controller('VerificationController', ['$rootScope', '$scope', 'appInfo', '$location', '$stateParams', '$timeout', function ($rootScope, $scope, appInfo, $location, $stateParams, $timeout) {
$scope.showSuccess = false;
$scope.message = 'Verifying ..';
$scope.timer = 0;
$scope.CountDown = function () {
if ($scope.timer) {
$scope.timer--;
$timeout($scope.CountDown, 1000);
} else {
if ($rootScope.CompanyPreferences.Category == 'Company') {
if (!_.isUndefined($rootScope.SignIn.LoginSessionKey))
$location.path('/');
else
$location.path('/SignIn');
} else {
$location.path('/');
}
}
}
$scope.Verify = function () {
var reqData = {
"VerifyCode": {
"Code": $stateParams.authToken,
"DeviceType": "Web",
"SocialType": "Web",
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"DeviceID": "Web",
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
};
if ($rootScope.SignIn)
reqData.VerifyCode.LoginSessionKey = $rootScope.SignIn.LoginSessionKey
if ($scope.PendingDetails) {
if (!checkstatus('frmPendingDetails', $scope))
return false;
reqData.VerifyCode.PendingDetails = $scope.PendingDetails;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showSuccess = true;
$scope.message = 'Successfully Verified';
delete $scope.PendingDetails;
$scope.SignIn.UserDetails.StatusID = 2;
$scope.persistentMessage = '';
// console.log('1',$scope.SignIn.UserDetails.StatusID,$scope.persistentMessage);
} if (response.ResponseCode == 673) {
$scope.showSuccess = true;
$scope.message = response.Message;
$scope.PendingDetails = {};
} else {
$scope.showSuccess = false;
$scope.message = response.Message;
}
if (_.isUndefined($scope.PendingDetails) || ($scope.PendingDetails && response.ResponseCode == 200)) {
$scope.timer = 5;
$timeout($scope.CountDown, 1000);
}
});
}
if ($stateParams.authToken) {
if ($rootScope.CompanyPreferences)
$scope.Verify();
else
$rootScope.$on('company-loaded', $scope.Verify);
}
}])
// DashBoard Controller
.controller('dashboardCtrl', ['$rootScope', '$timeout', '$scope', 'appInfo', '$location', 'ngDialog', function ($rootScope, $timeout, $scope, appInfo, $location, ngDialog) {
if ($rootScope.SignIn.ChangePassword) {
$timeout(function () {
angular.element('#cmdChangePassword').trigger('click');
}, 1000);
}
$scope.getDashboardData = function () {
var reqData = {
"GetDashboardData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.applicationData = response.Data.StatusWise;
$scope.countWiseData = response.Data.CountWise;
$scope.timeWiseData = response.Data.TimeWise;
var data = new google.visualization.DataTable(response.Data.StatusWise);
data.addColumn('string', 'Name');
data.addColumn('number', 'ApplicationsCount');
data.addColumn('number', 'FinanceAmount');
data.addRows(response.Data.StatusWise);
// Set chart options
var options = {
interpolateNulls: true,
//chartArea:{left:0,top:10,width:"100%"},
legend: { position: 'bottom', maxLines: 2 }
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(angular.element('#statusWiseChart')[0]);
chart.draw(data, options);
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.getDashboardData();
// Get top 10 sales persons
$scope.getTopSalesPerson = function () {
var reqData = {
"GetTopSalesPerson": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.topSalesPersons = response.Data;
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.getTopSalesPerson();
// Get Highest Loan Seeker
$scope.getHighestLoanSeeker = function () {
var reqData = {
"GetHighestLoanSeeker": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
var options = {
interpolateNulls: true,
chartArea: { left: 0, top: 50, width: "100%" },
legend: { position: 'bottom' },
// bar: { groupWidth: "50%" },
colors: ['#990099', '#FF9900', '#E34444', '#40AC42', '#8C0000'],
vAxis: { gridlines: { count: (7) }, minValue: 0, maxValue: 60 }
};
var dataTable = google.visualization.arrayToDataTable(response.Data);
var chart = new google.visualization.ColumnChart(document.getElementById('highestLoanSeekerChart'));
chart.draw(dataTable, options);
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.getHighestLoanSeeker();
// Get Frequent Loan Seeker
$scope.getFrequentLoanSeeker = function () {
var reqData = {
"GetFrequentLoanSeeker": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
var options = {
interpolateNulls: true,
chartArea: { left: 0, top: 0, width: "100%", height: "88%" },
legend: { position: 'bottom' },
// bar: { groupWidth: "50%" },
colors: ['#990099', '#FF9900', '#E34444', '#40AC42', '#8C0000'],
// vAxis: { gridlines: { count: (7) }, minValue: 0, maxValue: 60 }
};
var dataTable = google.visualization.arrayToDataTable(response.Data);
var chart = new google.visualization.ColumnChart(document.getElementById('frequentLoanSeeker'));
chart.draw(dataTable, options);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
// Get Turn Around Time
$scope.getTurnAroundTime = function () {
var reqData = {
"GetTurnAroundTime": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Year": $rootScope.currentYear
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
var data = google.visualization.arrayToDataTable(response.Data);
var options = {
title: '',
vAxis: { format: '### Days' },
hAxis: { format: '#' },
chartArea: { left: 0, top: 0, width: "100%", height: "88%" },
legend: { position: 'bottom', alignment: 'start' },
pointSize: 5,
height: '300',
titleTextStyle: { color: '#666666', fontSize: '16', fontName: 'open_sansregular' }
};
var chart = new google.visualization.LineChart(document.getElementById('turnAroundTimeChart'));
chart.draw(data, options);
};
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.matchingApps = [];
$scope.updateMatchingAppNo = function (typed) {
$scope.matchingApps = [];
if (typed) {
var reqData = {
"suggestApplicattionNo": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ApplicationNumber": typed
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
for (var i in response.Data) {
$scope.matchingApps[i] = response.Data[i].ApplicationNumber;
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.addStreamChat = function (e) {
$scope.sharedMessage = false;
if (angular.element(e.currentTarget).hasClass('btn-share')) {
B2BMessage = ($rootScope.CompanyPreferences.Category == "Bank");
if ($scope.taggedAppNo) {
if (this.chatMessage) {
$rootScope.addChatMessage(e, this.chatMessage, $scope.taggedAppNo, B2BMessage, function () {
$scope.showFlashMessage('success', 'Message Sent');
$scope.chatMessage = $scope.taggedAppNo = null;
});
}
else {
$scope.showFlashMessage('error', 'Please Enter Chat Message');
}
}
else {
$scope.showFlashMessage('error', 'Please tag application to send message');
return false;
}
}
}
$scope.getAnalyticStats = function () {
$scope.getFrequentLoanSeeker();
$scope.getTurnAroundTime();
$scope.targetColor1 = $scope.CompanyPreferences.BetaSiteThemeSettings.color1;
$scope.targetColor2 = $scope.CompanyPreferences.BetaSiteThemeSettings.color2;
$scope.Page.Title = 'Dashboard - ' + $rootScope.CompanyPreferences.CompanyName;
}
if ($scope.CompanyPreferences) {
$scope.getAnalyticStats();
} else {
$rootScope.$on('company-loaded', $scope.getAnalyticStats);
}
$scope.changeThemeNew = function (targetColor1, targetColor2, tempUpdate) {
var color1 = $scope.targetColor1;
var color2 = $scope.targetColor2;
if (!tempUpdate) {
var reqData = {
"SetCompanyPreferences": {
"UIsettings": { "color1": color1, "color2": color2, "color3": color1, "color4": color1, "color5": color1 },
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.showFlashMessage('success', response.Message);
$rootScope.CompanyPreferences.BetaSiteThemeSettings = { "color1": color1, "color2": color2, "color3": color1, "color4": color1, "color5": color1 };
Storage.setItem('CompanyPreferences', $rootScope.CompanyPreferences);
$rootScope.updateUI();
} else {
$rootScope.showFlashMessage('error', response.Message);
}
});
}
else {
$rootScope.updateUI();
}
};
}])
// Application Controller
.controller('applicationCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage) {
$scope.getColor = $rootScope.getColor; // IE Fix
$scope.totalApplications = 0;
$scope.sentMessage = '';
$scope.firstLoad = true;
$scope.requestUnderProcess = false;
$scope.DisabledSortBy = [];
var tabbedPage = { "sAll": 1, "s20": 1, "s22": 1 };
$scope.SortByOptions = [
{ key: 'FirstName', sortByValue: 'Name' },
{ key: 'BusinessName', sortByValue: 'Business Name' },
{ key: 'FinanceAmount', sortByValue: 'Finance Amount' },
{ key: 'FinanceTenure', sortByValue: 'Finance Tenure' },
{ key: 'CreditScoreID', sortByValue: 'User Credit Score' }
];
if ($rootScope.CompanyPreferences)
loadCompanyData();
else
$rootScope.$on('company-loaded', loadCompanyData);
function loadCompanyData() {
$scope.Page.Title = 'Application - ' + $rootScope.CompanyPreferences.CompanyName;
if ($rootScope.CompanyPreferences.Category == 'Bank') {
for (var i in $scope.SortByOptions) {
if ($scope.SortByOptions[i].key == "CreditScoreID") {
$scope.SortByOptions.splice(i, 1);
}
}
};
if ($rootScope.CompanyPreferences.Category == 'Company') {
$scope.SortByOptions.push({ key: 'ApplicationDate', sortByValue: 'Creation Date' });
}
else
$scope.SortByOptions.push({ key: 'SharingDate', sortByValue: 'Sharing Date' });
if ($rootScope.SignIn.UserDetails.UserTypeID !== 4) {
appInfo.getAssociationList(function () {
//$scope.AssociationName=null;
});
};
}
$scope.resendverifyLink = function () {
reqData = {
"ResendVerificationLink": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.resetFiltersForApp = function () {
$scope.StatusFlag = 'All';
$scope.appListFilter = {
Name: null, StartDate: null, EndDate: null,
appStatus: null, BorrowerID: null, ProposalLeadID: null, ProgramID: null, ProgramName: null
};
$scope.appSort = null;
$scope.currentPage = 1;
$scope.refreshApplicationsList();
}
$scope.resetBorrowerFilters = function () {
$scope.appListFilter.ProposalLeadID = $scope.appListFilter.BorrowerID = $scope.appListFilter.Email = null;
$scope.currentPage = 1;
$scope.saveAppState(null);
$scope.refreshApplicationsList();
}
$scope.updateStatus = function (StatusID) {
$scope.StatusFlag = StatusID;
$scope.currentPage = tabbedPage["s" + $scope.StatusFlag];
if (StatusID == 'All') {
$scope.appListFilter.appStatus = null;
$scope.refreshApplicationsList();
}
else {
for (var i in $scope.StatusList) {
if ($scope.StatusList[i].StatusID == StatusID) {
$scope.appListFilter.appStatus = $scope.StatusList[i];
$scope.refreshApplicationsList();
}
}
}
}
$scope.refreshApplicationsList = function () {
$scope.Page.trackLoading('applications-list');
if (!$scope.requestUnderProcess) {
var reqData = {
"GetApplicationsList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"BorrowerID": "all"
}
};
if ($scope.appListFilter) {
reqData.GetApplicationsList.Filter = {
CompanyApplicationsFilter_StartDate: $scope.appListFilter.StartDate,
CompanyApplicationsFilter_EndDate: $scope.appListFilter.EndDate,
CompanyApplicationsFilter_Name: $scope.appListFilter.Name,
CompanyApplicationsFilter_AssociationID: ($scope.appListFilter.Association) ? $scope.appListFilter.Association.CompanyID : null,
Status: ($scope.appListFilter.appStatus) ? $scope.appListFilter.appStatus.StatusID : null,
ProposalLeadID: ($scope.appListFilter.ProposalLeadID) ? $scope.appListFilter.ProposalLeadID : null
};
if ($scope.appListFilter.BorrowerID) {
reqData.GetApplicationsList.BorrowerID = $scope.appListFilter.BorrowerID;
}
if ($scope.appListFilter.ProgramID) {
reqData.GetApplicationsList.ProgramID = $scope.appListFilter.ProgramID;
}
}
if ($scope.appSort) {
reqData.GetApplicationsList.SortBy = $scope.appSort;
}
if (!$scope.firstLoad)
$scope.saveAppState(null);
$scope.Page.trackLoading('applications-list');
$scope.Applcations = null;
$scope.totalApplications = 0;
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('applications-list');
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.Applcations = response.Data.Financerequest;
$scope.AllowedChat = response.Data.AllowedChat;
tabbedPage["s" + $scope.StatusFlag] = pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalApplications = response.Data.Paginator.total_financerequest
pagingData.numPerPage = 10;
$scope.showingApplicationtext = appInfo.getPaginationData(pagingData);
$scope.MinDate = response.Data.MinDate;
$scope.MaxDate = response.Data.MaxDate;
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.getStatusName = function (StatusID) {
var Status = null;
if (StatusID != '') {
Status = _.findWhere($scope.StatusList, { StatusID: StatusID });
if (Status)
return Status.StatusName;
}
return Status;
}
$scope.initFilters = function () {
appInfo.getSalesPersons(function () {
var appList = Storage.getItem('appList');
if (appList) {
$scope.appListFilter = {
Name: appList.Filter.Name,
StartDate: appList.Filter.StartDate,
EndDate: appList.Filter.EndDate,
BorrowerID: appList.Filter.BorrowerID,
Email: appList.Filter.Email,
appStatus: null,
Association: appList.Filter.Association,
ProposalLeadID: appList.Filter.ProposalLeadID,
ProgramID: appList.ProgramID,
ProgramName: appList.ProgramName
};
if (appList.SortBy) {
$scope.appSort = null;
for (var i in $scope.SortByOptions) {
if (angular.equals($scope.SortByOptions[i], appList.SortBy)) {
$scope.appSort = $scope.SortByOptions[i];
break;
}
}
}
if (appList.Filter.appStatus) {
$scope.appListFilter.appStatus = _.findWhere($scope.StatusList, appList.Filter.appStatus);
}
$scope.currentPage = appList.currentPage;
$scope.ProposalGUID = appList.ProposalGUID;
$scope.ProposalName = appList.ProposalName;
$scope.StatusFlag = appList.Filter.appStatus ? appList.Filter.appStatus.StatusID : 'All';
if (_.isUndefined($scope.StatusFlag)) {
$scope.StatusFlag = 'All';
}
$scope.refreshApplicationsList();
} else
$scope.resetFiltersForApp();
$scope.firstLoad = false;
});
};
appInfo.getStatusList(function () {
$scope.StatusList = $rootScope.statusList;
$scope.initFilters();
});
$scope.removeAppData = function () {
$scope.FinanceRequestID = this.application.FinanceRequestID;
$rootScope.ngConfirm("Are you sure you want to delete this application ?", function () {
var reqData = {
"RemoveAppData": {
"FinanceRequestID": $scope.FinanceRequestID,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.refreshApplicationsList();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
});
}
$scope.getSalesPersonName = function (SalesPersonID) {
var salesPerson = _.findWhere($rootScope.salesPersons, { ID: SalesPersonID });
return salesPerson ? salesPerson.Name : null;
}
$scope.saveAppState = function () {
var appList = {
"Filter": $scope.appListFilter,
"currentPage": $scope.currentPage,
"SortBy": $scope.appSort
};
Storage.setItem('appList', appList);
}
$scope.applicatiopnRating = function (Rating, FinanceRequestID) {
if ([4, 6].indexOf($rootScope.SignIn.UserDetails.UserTypeID) == -1) {
var reqData = {
"UpdateApplicationRating": {
"FinanceRequestID": FinanceRequestID,
"UserID": $rootScope.SignIn.UserDetails.UserID,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Rating": Rating
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.ApplicationDetails = response.Data;
} else {
$scope.showFlashMessage('error', response.Message);
}
});
} else {
$scope.showFlashMessage('error', 'You are not authorized for this action.');
}
}
$scope.assignApplicationPopup = function () {
$scope.selectedApplication = this.application;
if ($rootScope.CompanyPreferences.Category == 'Company') {
if (this.application.AssigneeID) {
$scope.salesPersonName = _.findWhere($rootScope.salesPersons, { ID: this.application.AssigneeID });
}
else {
$scope.salesPersonName = {};
}
}
else {
if ($scope.selectedApplication.CompanyID == $scope.CompanyPreferences.CompanyID) {
if (this.application.AssigneeID) {
$scope.salesPersonName = _.findWhere($rootScope.salesPersons, { ID: this.application.AssigneeIDBank });
}
else {
$scope.salesPersonName = {};
}
}
else {
$scope.ngConfirm('This application is shared by vendor, and the sales person is assigned based on program association. Would you like to update the association?', function () {
ngDialog.close();
Storage.setItem('ProgramDetails', { 'ProgramID': $scope.selectedApplication.ProgramID });
$location.path('/program/view/vendor-allocation');
});
return;
}
}
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-firstDialogId.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope
});
}
$scope.assignApplication = function () {
$scope.loading = true;
var OldAssignee = $rootScope.CompanyPreferences.Category == 'Company' ? $scope.selectedApplication.AssigneeID : $scope.selectedApplication.AssigneeIDBank;
var AssigneeID = null;
if (this.salesPersonName)
AssigneeID = this.salesPersonName.ID;
else if (!OldAssignee) {
$scope.showFlashMessage('error', 'Please select a sales person to assign');
return $scope.loading = false;
}
var reqData = {
"AssignApplications": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Assignments": [
{
"ApplicationNumber": $scope.selectedApplication.ApplicationNumber,
"AssigneeID": AssigneeID,
"OldAssigneeID": OldAssignee
}
],
"ApplicationsType": "Complete"
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.act['##APPLICATIONNUMBER##']) {
$scope.showFlashMessage('success', response.Data.act['##APPLICATIONNUMBER##'] + ' Application assigned to ' + response.Data.act['##AGENTNAME##']);
}
$scope.refreshApplicationsList();
}
else {
$scope.showFlashMessage('error', response.Message);
}
$scope.loading = false;
ngDialog.close();
});
}
$scope.$watch('appListFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue)
$scope.refreshApplicationsList();
}, 700));
$scope.$watch('appListFilter.StartDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.appListFilter.EndDate) {
var StartDate = new Date(newValue);
var EndDate = new Date($scope.appListFilter.EndDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.appListFilter.StartDate = null;
}
}
});
$scope.$watch('appListFilter.EndDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.appListFilter.StartDate) {
var EndDate = new Date(newValue);
var StartDate = new Date($scope.appListFilter.StartDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.appListFilter.EndDate = null;
}
}
});
$scope.filterByAssociate = function (associate) {
$scope.appListFilter.Association = associate;
$scope.refreshApplicationsList();
$scope.saveAppState(null);
};
$scope.updatePartnerAppStatus = function (StatusID) {
$scope.selectedApplication = this.application;
if (StatusID == 21) {
$scope.selectedApplication.StatusID = 21;
$scope.showDeclineRejectPopup($scope, true);
}
else {
$scope.ngConfirm('Are you sure you want to accept application?', function () {
$scope.flag = false;
$scope.appStatusUpdate();
});
}
}
$scope.appStatusUpdate = function () {
$scope.unapproveStatusFlags = '';
$scope.unapproveComment = '';
$scope.Page.trackLoading('app-status-update');
var reqData = {
"ApplicationStatusUpdate": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ApplicationStatusUpdate_ApplicationNumber": $scope.selectedApplication.ApplicationNumber,
"ApplicationStatusUpdate_Status": $scope.selectedApplication.StatusID,
"StatusFlagID": $scope.Application ? $scope.Application.unapproveStatusFlags.MarkerFlagID : null,
"Comment": $scope.Application ? $scope.Application.unapproveComment : null,
"ProgramID": $scope.selectedApplication.ProgramID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
ngDialog.close();
$scope.showFlashMessage('success', response.Message);
$scope.refreshApplicationsList();
$scope.borrowerView = true;
}
else {
$scope.showFlashMessage('error', response.Message);
}
$scope.selectedApplication.unapproveComment = null;
$scope.Page.untrackLoading('app-status-update');
});
}
$scope.cancelReject = function () {
ngDialog.close();
$scope.Application.unapproveComment = $scope.Application.unapproveStatusFlags = null;
}
$scope.myRate = 0;
$scope.closePopup = function () {
ngDialog.close();
}
$scope.dealConnectionPopup = function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-dealConnectionPopup.html',
className: 'ng-popup ngdialog-theme-default custom-width',
scope: $scope
});
}
$scope.invitationPopup = function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-invitaionPopup.html',
className: 'ng-popup ngdialog-theme-default right',
scope: $scope
});
}
}])
// Application Details Controller New
.controller('appDetailsCtrlNew', ['$rootScope', '$state', '$scope', 'appInfo', '$location', '$stateParams', 'ngDialog', 'Storage', '$timeout', '$q', function ($rootScope, $state, $scope, appInfo, $location, $stateParams, ngDialog, Storage, $timeout, $q) {
$rootScope.SeeRecordData = { maxDisplayPages: '10' };
$scope.validateData = $scope.detailsLoaded = $scope.appStatus = false;
$rootScope.uploading = false;
$scope.errorFinanceAmount = '';
$scope.blockOwnerEditing = true;
$scope.flag = false;
$scope.Business = {};
$scope.Application = {};
$scope.requiredDocumentTypeList = false;
$scope.partnerDetailView = false;
$scope.appInfo = appInfo;
$scope.currentPage = 1;
$scope.statusLogCurrentPage = 1
$scope.statusOfferLogCurrentPage = 1
$scope.notes = { noteCurrentPage: 1, totalPage: null, totalRecord: null };
$scope.noteTab = 'Application';
$scope.noteSort = {};
$scope.disableButton = true;
$scope.editEnable = true;
$scope.BlockSaveButton = false;
$scope.ShowStrip = false;
$scope.approveFull = false;
$scope.appStatusUpdateFlag = false;
$scope.changeStatusFlag = false;
$scope.Description = null;
$scope.disabledButton = "enable";
$scope.disabledIcon = "ic-disabled";
$scope.StepComplete = {};
$scope.privacyHide = true;
$scope.FilesFilter = {};
$scope.LoanData = {};
$scope.RateOption = 'BR';
/****file upload******/
$scope.showPlusButton = true;
$scope.toggleIcon = function () {
$scope.showPlusButton = $scope.showPlusButton ? false : true;
}
// Main Details Tabs
$scope.switchtab = function (tabFlag, triggerView) {
//console.log(tabFlag,triggerView);
switch (tabFlag) {
case 'documents':
$scope.refreshFileList();
$scope.refreshRequiredDocumentTypeList();
if (triggerView)
angular.element('#documentsTab').trigger('click');
break;
case 'view':
$scope.getShareApplicationPrograms();
break;
case 'message':
$scope.getChatRooms();
break;
case 'ApplicationOffers':
$('div').find('.resp-tab-content-active').hide();
$('div').removeClass('resp-tab-content-active');
$('li').removeClass('resp-tab-active');
$('body').find('#see_offers').addClass('resp-tab-active');
$('body').find('#ApplicationOffers').addClass('resp-tab-content hor_1 resp-tab-content-active');
break;
}
$scope.tabFlag = tabFlag;
}
$scope.getChatRooms = function () {
var reqData = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"filters": {
entityType: "application",
entityID: $stateParams.ApplicationNumber
}
};
appInfo.getChatRooms(reqData, function (response) {
if (response.ResponseCode == 200) {
$scope.chat.representatives = [];
$scope.Application.chatRooms = response.Data;
for (var i in response.Data) {
// $scope.keys.push(response.Data[i].chatRoomID);
// $scope.chat.rooms[response.Data[i].chatRoomID]=response.Data[i];
if (Array.isArray($scope.chat.representatives) && $scope.chat.representatives.indexOf(response.Data[i].representative.UserID) == -1)
$scope.chat.representatives.push(response.Data[i].representative.UserID);
}
appInfo.getSocketData({ 'checkOnlineUsers': $scope.chat.representatives }, function (r) {
$scope.chat.onlineUsers = r.checkOnlineUsers;
});
}
});
}
// Sub Tabs as used in documents
$scope.tabNum = 1;
$scope.setTab = function (setTab) {
$scope.tabNum = setTab;
}
$scope.tab = function (tab) {
return $scope.tabNum === tab;
}
$scope.refreshRequiredDocumentTypeList = function () {
var reqData = {
"GetRequiredDocumentTypesList": {
"ApplicationNumber": $stateParams.ApplicationNumber,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.requiredDocumentTypeList ? $scope.requiredDocumentTypeList.Paginator.current_page : 1
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.requiredDocumentTypeList = response.Data;
var pagingData = {};
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = response.Data.Paginator.total_application_documents;
pagingData.numPerPage = 10;
$scope.showingRequiredDocumentTypeText = appInfo.getPaginationData(pagingData);
if (response.Data.Paginator.total_application_documents) {
$scope.Page.documents.selectedFileActions = [
{ "icon": "icon-tooltip-edit asp-row-icon", "label": "Set Document Type", "perform": $scope.mapDocumentType }
];
if (response.Data.Paginator.total_application_documents > 10 && $scope.ApplicationStatusData.length > 1 && !$scope.requiredDocumentTypePrograms) {
reqData = {
"GetRequiredDocumentTypesPrograms": {
"ApplicationNumber": $stateParams.ApplicationNumber,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.GetRequiredDocumentTypesPrograms = response.Data;
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.callUploadDocument = function (files, errFiles, requiredDocumentType, callback) {
$scope.uploadDocument(files, errFiles, requiredDocumentType, function () {
$scope.refreshRequiredDocumentTypeList();
})
}
$scope.mapDocumentType = function (fileItem) {
$scope.selectedApplicationDocument = fileItem;
if (!$scope.requiredDocumentTypePrograms) {
$scope.getRequiredDocumentTypeList();
}
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-documentList.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
}
$scope.getRequiredDocumentTypeList = function (programID) {
var reqData = {
"GetRequiredDocumentTypesList": {
"ApplicationNumber": $stateParams.ApplicationNumber,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": -1
}
};
if (programID) {
reqData.GetRequiredDocumentTypesList.Filters = {
"ProgramID": programID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.documentTypes = response.Data;
$scope.Page.documents.documentType = null;
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.markDocumentType = function () {
var reqData = {
"MarkRequiredDocumentTypesList": {
"ApplicationNumber": $stateParams.ApplicationNumber,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ApplicationDocumentID": $scope.Page.documents.documentType.ApplicationDocumentID,
"MediaID": $scope.selectedApplicationDocument.MediaID
}
};
appInfo.getServerData(reqData).then(function (response) {
var msgClass = 'error';
if (response.ResponseCode == 200) {
$scope.refreshRequiredDocumentTypeList();
$scope.Page.documents.documentType = null;
msgClass = 'success';
ngDialog.close();
}
$scope.showFlashMessage(msgClass, response.Message);
});
}
$scope.ApplicationStatusLog = function () {
var reqData = {
"GetApplicationStatusLog": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.statusLogCurrentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.AppStatusLogData = response.Data.AppStatusLogData;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalApplicationLogs = response.Data.Paginator.applicationupdatelogs
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
};
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.ApplicationOfferLog = function () {
$scope.OfferDetailShow = false;
var reqData = {
"GetApplicationStatusLog": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.statusOfferLogCurrentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"ApplicationOffers": 'ApplicationOffers',
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
offerPagingData = [];
$scope.AppOfferLogData = response.Data.AppStatusLogData;
//console.log('Application Update Log',$scope.AppOfferLogData);
offerPagingData.currentPage = response.Data.Paginator.current_page;
offerPagingData.totalPage = response.Data.Paginator.total_pages;
offerPagingData.totalRecord = $scope.totalApplicationOfferLogs = response.Data.Paginator.applicationupdatelogs
offerPagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(offerPagingData);
};
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.getOfferDetail = function (ApplicationUpdateLogID) {
var reqData = {
"GetApplicationStatusLog": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.statusOfferLogCurrentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"ApplicationUpdateLogID": ApplicationUpdateLogID,
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.OfferDetailShow = true;
$scope.offerAdditionalDetails = response.Data.AdditionalDetails;
$scope.offerOfferDocumet = response.Data.OfferDocumet;
$scope.ProgramName = response.Data.ProgramName.Title;
$scope.OfferFinanceAmount = response.Data.AppStatusLogData[0].FinanceAmount;
};
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.cancelUnapproveDecline = function () {
ngDialog.close();
if ($scope.ApplicationDetails.ApplicationStatus.StatusID == 39 && $scope.hasAcceptedProgram) {
$scope.hasAcceptedProgram.OfferAccepted = false;
$scope.isOfferAcceptedProgram.OfferAccepted = false;
$scope.hasAcceptedProgram = undefined;
}
$scope.appStatusUpdateFlag = false;
if (!_.isEqual($scope.ApplicationDetails.ApplicationStatus, $scope.oldStatus))
$scope.changeStatusFlag = 'cancel';
$scope.ApplicationDetails.ApplicationStatus = $scope.oldStatus;
if (_.isUndefined($scope.ApplicationDetails.ApplicationStatus)) {
$scope.ApplicationDetails.ApplicationStatus = $scope.newStatus;
}
$scope.LoanData.downPayment = 0;
}
$scope.getDefaultChatWindow = function (roomCode) {
var chatRoom = {
LoginSessionKey: $scope.SignIn.LoginSessionKey,
chatTitle: $scope.CompanyPreferences.CompanyName + ' ' + $scope.ApplicationDetails.ApplicationNumber,
associatedEntityType: 'Application',
associationEntityID: $scope.ApplicationDetails.ApplicationNumber
};
if (roomCode) {
if (this.AppStatus) {
chatRoom.otherProperties = { lenderAlias: this.AppStatus.Alias, programID: this.AppStatus.ProgramID };
} else if ($scope.ApplicationStatusData && $scope.ApplicationStatusData.length) {
chatRoom.otherProperties = { lenderAlias: $scope.ApplicationStatusData[0].Alias, programID: $scope.ApplicationStatusData[0].ProgramID };
}
if (roomCode == 'VLR') {
chatRoom.otherProperties.b2bChat = true;
}
}
$scope.chat.openChatRoom(chatRoom);
}
$scope.statusInfoDialog = function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-partial-approved.html?v=' + RELEASE_VERSION,
className: 'ng-popup ngdialog-theme-default ngdialog-large',
scope: $scope,
closeByEscape: false,
closeByDocument: false,
showClose: false
});
$scope.TimePeriod = $scope.ApplicationDetails.selectedOffer.Terms;
$scope.LoanDataTimeFormat = $rootScope.TimeFormat[2];
}
var statusWatcher = function (newStatus, oldStatus) {
$scope.newStatus = newStatus;
$scope.oldStatus = oldStatus;
if (oldStatus && newStatus && $scope.changeStatusFlag != 'cancel' && [38, 21].indexOf(newStatus.StatusID) == -1) {
$scope.Description = null;
if ([56, 37].indexOf($scope.newStatus.StatusID) != -1) {
if ($scope.ApplicationStatusData[0].StatusID == 21) {
$scope.ApplicationDetails.selectedOffer = _.find($scope.ApplicationStatusData, function (offer) {
return offer.StatusID != 21;
});
if (!$scope.ApplicationDetails.selectedOffer) {
$scope.showFlashMessage('error', 'Cannot send any offer, As all the requested programs have been rejected.');
$scope.changeStatusFlag != 'cancel';
$scope.ApplicationDetails.ApplicationStatus = oldStatus;
return false;
}
} else {
$scope.ApplicationDetails.selectedOffer = $scope.ApplicationStatusData[0];
}
$scope.LoanData.approveFlag = "full";
// $scope.LoanData.approveFlag="partial";
$scope.LoanData.approvedAmount = $scope.ApplicationDetails.FinanceAmount;
$scope.onOfferedProgramSelect();
}
// if(oldStatus.StatusID==37){
/**
* Partner Side Multi Offer Condition occured Ignore the change
*/
// } else
if ([22, 20, 35].indexOf($scope.ApplicationDetails.ApplicationStatus.StatusID) == -1) {
$scope.statusInfoDialog();
} else {
$scope.changeApplicationStatusPopup();
}
}
else {
$scope.changeStatusFlag = FALSE;
}
}
$scope.setProgramData = function (programData) {
if (parseInt($scope.LoanData.approvedAmount) > parseInt(programData.MaxAmountRange)) {
$scope.LoanData.RequestedAmount = programData.MaxAmountRange;
}
}
$scope.$watch('ApplicationDetails.ApplicationStatus', statusWatcher);
$scope.changeApplicationStatusPopup = function () {
if (!$scope.appStatusUpdateFlag && $scope.newStatus.StatusID == 37) {
$scope.LoanData.approveFlag = "partial";
};
$scope.oldApplicationStatus = $scope.oldStatus;
if ($scope.oldStatus && $scope.newStatus.StatusID == 37) {
$scope.appStatusUpdate();
}
else if ([39, 22, 20, 2].indexOf($scope.ApplicationDetails.ApplicationStatus.StatusID) == -1) {
$scope.flag = false;
$scope.appStatusUpdate();
}
else if ($scope.ApplicationDetails.ApplicationStatus.StatusID == 22) {
$rootScope.showDeclineRejectPopup($scope, true);
}
else {
var msg = 'Are you sure you want to update application status to ' + $scope.newStatus.StatusName + ' ?';
msg += "
Application Once " + $scope.newStatus.StatusName + " can not be reverted back.";
$rootScope.ngConfirm(msg, function () {
$scope.flag = true;
$scope.appStatusUpdate();
}, function () {
// if($scope.ApplicationDetails.ApplicationStatus.StatusID==39 && $scope.hasAcceptedProgram){
$scope.cancelUnapproveDecline();
// }
$scope.ApplicationDetails.ApplicationStatus = $scope.oldApplicationStatus;
});
}
}
$scope.setOfferData = function (callback, matchDataArray) {
if (parseInt($scope.ApplicationDetails.FinanceAmount) > parseInt(matchDataArray.MaxAmountRange)) {
$scope.LoanData.approvedAmount = matchDataArray.MaxAmountRange;
}
if (typeof callback != 'undefined' && callback != '')
callback();
}
$scope.changeCommissionPoint = function (AppStatus) {
$scope.currentSelectedOffer = AppStatus;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-change-commission-points.html?v=' + RELEASE_VERSION,
className: 'ng-popup ngdialog-theme-default',
scope: $scope,
closeByEscape: false,
closeByDocument: false,
showClose: false
});
}
$scope.updateAppStatus = function (StatusID, forced, updateOfferFlag, programId, ApplicationUpdateLogID) {
$scope.ValidTillDate = null;
if (StatusID == 56 && !$scope.CompanyPreferences.FundingManagerID)
StatusID = 37;
switch (StatusID) {
case 13:
$scope.LoanData.approveFlag = "full";
break;
case 39:
case 57:
$scope.hasAcceptedProgram = (typeof this.$parent.AppStatus == 'undefined') ? programId : this.$parent.AppStatus;
$scope.isOfferAcceptedProgram = this.AppStatus;
$scope.ApplicationUpdateLogID = ApplicationUpdateLogID;
if (!$scope.$$phase) {
$scope.$apply();
}
break;
case 37:
$scope.refreshFileList();
$scope.refreshRequiredDocumentTypeList();
//$scope.GetApplicationDetails();
case 56:
if (updateOfferFlag) {
$scope.ApplicationDetails.selectedOffer = this.$parent.AppStatus;
$scope.statusInfoDialog();
$scope.onOfferedProgramSelect();
break;
} else {
$scope.ApplicationDetails.currentProgramID = null;
if (!$scope.ApplicationStatusData && $scope.SignIn.UserDetails.UserTypeID != 7 && $scope.CompanyPreferences.Category == "Bank" && $scope.CompanyPreferences.CompanyID == $scope.ApplicationDetails.VendorID) {
$location.path('/share-application/' + $scope.ApplicationDetails.ApplicationNumber); return;
}
}
// if(!$scope.ApplicationDetails.currentProgramID && forced && [37,56].indexOf(StatusID)!=-1 && $scope.ApplicationDetails.ApplicationStatus.StatusID==StatusID){
if (!$scope.ApplicationDetails.currentProgramID && forced && [37, 56].indexOf(StatusID) != -1 && $scope.ApplicationDetails.StatusID == StatusID) {
$scope.ApplicationDetails.ApplicationStatus = _.findWhere($scope.statusList, { StatusID: $scope.ApplicationDetails.StatusID });
statusWatcher($scope.ApplicationDetails.ApplicationStatus, $scope.ApplicationDetails.ApplicationStatus);
}
// $scope.setOfferData(function(){
// Nothing to do
// }, $scope.ApplicationStatusData[0]);
}
$scope.appStatusUpdateFlag = true;
$scope.LoanData.approvedAmount = null;
$scope.ApplicationDetails.ApplicationStatus = _.findWhere($scope.statusList, { StatusID: StatusID });
}
//$scope.TimePeriod = $scope.ApplicationDetails.selectedOffer.Terms;
//Change Time Period Function
$scope.ChangeTimePeriod = function (LoanDataTimeFormat) {
if (LoanDataTimeFormat.key !== 'M') {
$scope.TimeFormatC = LoanDataTimeFormat.key;
appInfo.getFormatStaticData(LoanDataTimeFormat.key, function () {
$scope.LoanData.FinanceTenure = null;
setTimeout(function () {
$("#loanTermYWD").trigger("chosen:updated");
}, 2000);
});
} else {
$scope.TimeFormatC = LoanDataTimeFormat.key;
}
}
$scope.partialApproveStatus = function (approvedAmount, FinanceAmount, flag) {
if (approvedAmount) {
$scope.LoanData.FinanceAmount = approvedAmount;
$scope.changeEMI($scope.LoanData);
return updateDownPayment(approvedAmount, FinanceAmount, flag);
}
$scope.LoanData.downPayment = 0;
}
function updateDownPayment(approvedAmount, FinanceAmount, flag) {
if (('' + approvedAmount).indexOf(',') != -1) {
approvedAmount = approvedAmount.replace(',', '');
}
approvedAmount = parseInt(approvedAmount);
if (flag) {
var condition = true; //(approvedAmount <= FinanceAmount);
}
else {
var condition = true; //(approvedAmount < FinanceAmount);
}
if (condition) {
$scope.disableButton = false;
return $scope.LoanData.DownPayment = $scope.LoanData.downPayment = FinanceAmount - approvedAmount
}
else {
$scope.disableButton = true;
$scope.showFlashMessage('error', 'Approved amount must be less than applied amount.');
}
}
$scope.updateProcessAmount = function (downPayment, FinanceAmount, flag) {
if (_.isString(downPayment)) {
downPayment = downPayment.replace(',', '');
}
downPayment = parseInt(downPayment);
if (downPayment < FinanceAmount) {
$scope.disableButton = false;
return $scope.LoanData.FinanceAmount = $scope.LoanData.downPayment = FinanceAmount - downPayment
}
else {
$scope.errorDownPayment = "DownPayment must be less than applied amount.";
$scope.disableButton = true;
$scope.showFlashMessage('error', 'DownPayment must be less than applied amount.');
// console.log(downPayment,FinanceAmount,$scope.LoanData.FinanceAmount);
// console.log($scope.LoanData.downPayment=FinanceAmount-$scope.LoanData.FinanceAmount);
return $scope.LoanData.DownPayment = FinanceAmount - $scope.LoanData.FinanceAmount;
}
}
$scope.showPartnerDetails = function () {
if (!$scope.fetchAssociateData) {
$scope.fetchAssociateData = true;
var targetID = null;
$scope.CompanyType = null;
if ($rootScope.CompanyPreferences.Category == "Bank") {
targetID = $scope.ApplicationDetails.VendorID;
$scope.CompanyType = 'Vendor';
} else {
targetID = $scope.ApplicationDetails.BankID;
$scope.CompanyType = 'Partner';
}
var reqData = {
"GetCompanyPreferences": {
"CompanyID": targetID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.AssociatonDetails = response.Data;
ngDialog.open({
template: 'partner-detail',
className: 'ng-popup ngdialog-theme-default',
scope: $scope,
closeByEscape: false,
closeByDocument: false
})
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.fetchAssociateData = false;
});
}
}
$scope.showResponseDetails = function (programOffer) {
// if(programOffer.StatusID!=37)
if ([56, 37].indexOf(programOffer.StatusID) == -1)
// if(programOffer.StatusID!=56)
return false;
$scope.additionalData = programOffer;
if (!_.isObject($scope.additionalData.Metadata.FinanceTenure))
$scope.additionalData.Metadata.FinanceTenure = _.findWhere($scope.appliedProgram.Terms, { Term: parseInt(programOffer.Metadata.FinanceTenure) });
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-app-additional-details-popup.html?v=' + RELEASE_VERSION,
scope: $scope,
className: 'ng-popup ngdialog-theme-default'
});
}
$scope.updatePartnerAppStatus = function (StatusID) {
// $scope.ApplicationStatusID=ApplicationStatusID;
$scope.currentAppStatusData = this.AppStatus;
$scope.ApplicationDetails.ApplicationStatus = _.findWhere($scope.statusList, { StatusID: StatusID });
// $scope.ApplicationDetails=$scope.selectedApplication=this.applcation;
if ($scope.ApplicationDetails.ApplicationStatus.StatusID == 21) {
$scope.showDeclineRejectPopup($scope, true);
}
else {
$scope.ngConfirm('Are you sure you want to accept application?', function () {
$scope.flag = false;
$scope.appStatusUpdate();
});
}
}
$scope.appStatusUpdate = function () {
if ($scope.ApplicationDetails.ApplicationStatus && [56, 37].indexOf($scope.ApplicationDetails.ApplicationStatus.StatusID) == -1/* && $scope.ApplicationDetails.ApplicationStatus.StatusID!=37*/) {
$formName = 'frmUnappove';
}
else {
$formName = 'frmApprove';
// var approvedAmount=this.LoanData.approvedAmount;
var approvedAmount = $scope.LoanData.approvedAmount;
}
if (checkstatus($formName, $scope)) {
// if(checkstatus('frmUnappove',$scope)){
$scope.loading =
$scope.unapproveStatusFlags = '';
$scope.unapproveComment = '';
if ($scope.Application.unapproveComment) {
$scope.unapproveStatusFlags = $scope.Application.unapproveStatusFlags.MarkerFlagID;
$scope.unapproveComment = $scope.Application.unapproveComment;
}
var reqData = {
"ApplicationStatusUpdate": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ApplicationStatusUpdate_ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"StatusFlagID": $scope.unapproveStatusFlags,
"Comment": $scope.unapproveComment,
"TimeFormat": (typeof $scope.TimeFormatC === 'undefined') ? 'M' : $scope.TimeFormatC,
"RateOption": $scope.RateOption,
"OfferDocumentIds": (typeof $scope.Page.documents === 'object') ? $scope.Page.documents.selectedFileIds : [],
"OfferDocumet": (typeof $scope.Page.documents.selectedFiles === 'object') ? $scope.Page.documents.selectedFiles : [],
"AmountPayable": $scope.LoanData.AmountPayable,
"ApplicationUpdateLogID": (typeof $scope.ApplicationUpdateLogID == 'undefined') ? null : $scope.ApplicationUpdateLogID,
"approveFlag":$scope.LoanData.approveFlag
}
};
if ($scope.Description) {
reqData.ApplicationStatusUpdate.Metadata = { 'Description': $scope.Description };
}
reqData.ApplicationStatusUpdate.ApplicationStatusUpdate_Status = $scope.ApplicationDetails.ApplicationStatus.StatusID;
switch ($scope.ApplicationDetails.ApplicationStatus.StatusID) {
case 21:
reqData.ApplicationStatusUpdate.ProgramID = $scope.currentAppStatusData.ProgramID;
break;
case 45:
reqData.ApplicationStatusUpdate.ProgramID = $scope.ApplicationDetails.ProgramID;
break;
}
// if($scope.SignIn.UserTypeID==7 && $scope.ApplicationDetails.ApplicationStatus.StatusID==37){
// $scope.ApplicationDetails.selectedOffer =
// }
if ($scope.ApplicationDetails.ApplicationStatus && $scope.ApplicationDetails.ApplicationStatus.StatusID && [56, 37].indexOf($scope.ApplicationDetails.ApplicationStatus.StatusID) != -1 && ($scope.ApplicationDetails.selectedOffer || $scope.ApplicationDetails.ApplicationStatus.StatusID == 37)) {
reqData.ApplicationStatusUpdate.ProgramID = $scope.ApplicationDetails.selectedOffer.ProgramID;
reqData.ApplicationStatusUpdate.FinanceTenure = $scope.LoanData.FinanceTenure.Term;
reqData.ApplicationStatusUpdate.proposedROI = $scope.LoanData.InterestRate;
reqData.ApplicationStatusUpdate.proposedCommissionPoints = $scope.LoanData.CommissionPoints;
reqData.ApplicationStatusUpdate.ValidTillDate = $scope.ValidTillDate;
}
if ([39, 57].indexOf($scope.ApplicationDetails.ApplicationStatus.StatusID) != -1) {
reqData.ApplicationStatusUpdate.ProgramID = (typeof $scope.hasAcceptedProgram == 'object') ? $scope.hasAcceptedProgram.ProgramID : $scope.hasAcceptedProgram;
}
if (approvedAmount) {
reqData.ApplicationStatusUpdate.approvedAmount = approvedAmount + '';
if (reqData.ApplicationStatusUpdate.approvedAmount.indexOf(',') != -1) {
reqData.ApplicationStatusUpdate.approvedAmount = parseInt(reqData.ApplicationStatusUpdate.approvedAmount.replace(',', ''));
}
reqData.ApplicationStatusUpdate.downPayment = $scope.LoanData.downPayment;
reqData.ApplicationStatusUpdate.requestedAmount = $scope.ApplicationDetails.FinanceAmount;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
ngDialog.close();
$scope.changeStatusFlag = 'cancel';
$scope.hiddenButton = response.Message;
$scope.ApplicationDetails.StatusProgress = Math.round(response.Data.StatusProgress);
// $scope.ApplicationStatusLog();
$scope.showFlashMessage('success', response.Message);
if ($scope.LoanData.downPayment) {
$scope.ApplicationDetails.FinanceAmount = $scope.LoanData.FinanceAmount = approvedAmount;
}
$scope.GetApplicationDetails();
} else {
$scope.showFlashMessage('error', response.Message);
// $scope.ApplicationDetails.ApplicationStatus=$scope.oldApplicationStatus;
}
$scope.loading = FALSE;
});
}
}
$scope.validateUpload = function (f) {
if ($rootScope.uploading) {
$scope.showFlashMessage('error', "Please wait,Another upload in progress.");
return false;
}
return true;
}
$scope.SelectedProgramData = {};
$scope.GetApplicationDetails = function (callback) {
var reqData = {
"GetApplicationDetails": {
"ApplicationNumber": $stateParams.ApplicationNumber,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
$scope.detailsLoaded = false;
appInfo.getServerData(reqData).then(function (response) {
if ([4, 200].indexOf(response.ResponseCode) != -1) {
$scope.flag = response.Data.preventEditing;
$scope.ApplicationDetails = response.Data.ApplicationsDetails;
$scope.AllowedChat = response.Data.AllowedChat;
if ($scope.SignIn.UserDetails.UserTypeID == 4) {
if ($scope.ApplicationDetails.isAdditionalInfoRequiredBeforeOffer) {
Storage.setItem('ApplicationData', {
"ApplicationNumber": $stateParams.ApplicationNumber,
"FetchPreOfferFields": $scope.ApplicationDetails.isAdditionalInfoRequiredBeforeOffer,
"ProgramLoanType": $scope.ApplicationDetails.ProgramLoanType
});
$state.go('additional-information');
}
if ($scope.ApplicationDetails.StatusID == 48 && $scope.ApplicationDetails.DefaultAppWorkFlow.toLowerCase() == 'experianwithchooselender') {
Storage.setItem('ApplicationData', {
"ApplicationNumber": $stateParams.ApplicationNumber,
"LoanData": {
"CreditScore": null,
"FinanceTenure": $scope.ApplicationDetails.FinanceTenure,
},
"ProgramLoanType": $scope.ApplicationDetails.ProgramLoanType
});
appInfo.getFundingProgram(function () {
$state.go('financing-offers');
}, false, {
TimeInBusinessID: $scope.ApplicationDetails.FinanceTimeInBusiness,
CreditScoreID: $scope.ApplicationDetails.CreditScoreID,
ProgramID: $scope.ApplicationDetails.ProgramID ? $scope.ApplicationDetails.ProgramID : $scope.CompanyPreferences.DefaultProgramID,
ProgramLoanType: $scope.ApplicationDetails.ProgramLoanType,
UsingDefault: FALSE
});
return;
}
}
if ($scope.ApplicationDetails.StatusID == 39) {
$scope.OfferAccepted = TRUE;
}
else {
$scope.OfferAccepted = FALSE;
}
$scope.ApplicationDetails.StatusProgress = Math.round($scope.ApplicationDetails.StatusProgress);
appInfo.getStates(function () {
$scope.Business.totalOwnership = $scope.ApplicationDetails.PercentageOwnership;
for (var i in $scope.ApplicationDetails.BusinessOwners) {
$scope.ApplicationDetails.BusinessOwners[i].StateID = _.findWhere($scope.stateData, { StateID: $scope.ApplicationDetails.BusinessOwners[i].StateID });
$scope.ApplicationDetails.BusinessOwners[i].PostalCode = $scope.ApplicationDetails.BusinessOwners[i].Postal;
$scope.Business.totalOwnership += $scope.ApplicationDetails.BusinessOwners[i].PercentageOwnership;
}
});
$scope.applicationPDFUrl = $location.$$protocol + '://' + $location.$$host + '/applications/details/1/' + $stateParams.ApplicationNumber + '.pdf';
$scope.ApplicationDetails.ApplicationStatus = _.findWhere($rootScope.statusList, { StatusID: $scope.ApplicationDetails.StatusID });
var ProgramID = ($scope.ApplicationDetails.ProgramID) ? $scope.ApplicationDetails.ProgramID : $scope.CompanyPreferences.DefaultProgramID;
if ($rootScope.CompanyPreferences.Category == 'Bank') {
appInfo.getFundingProgram(function () {
if ($scope.appliedProgram) {
var maxProgramTerm = _.last($scope.appliedProgram.Terms);
if ($scope.ApplicationDetails.FinanceTenure > maxProgramTerm.Term) {
if($scope.ApplicationDetails.StatusID != 37){
$scope.showFlashMessage('error', 'Applications FinanceTenure ' + $scope.ApplicationDetails.FinanceTenure + ' is greater then permited tenure ' + maxProgramTerm.Term + '.');
}
}
}
appInfo.getSignUpStaticData($scope.getEditMetaData, $scope.ApplicationDetails.ProgramID);
}, true, {
TimeInBusinessID: $scope.ApplicationDetails.FinanceTimeInBusiness,
CreditScoreID: $scope.ApplicationDetails.CreditScoreID,
"ProgramID": ProgramID,
ProgramLoanType: $scope.ApplicationDetails.ProgramLoanType,
UsingDefault: FALSE,
});
} else {
appInfo.getFundingProgram(function () {
appInfo.getSignUpStaticData($scope.getEditMetaData, ProgramID);
}, true, {
TimeInBusinessID: $scope.ApplicationDetails.FinanceTimeInBusiness,
CreditScoreID: $scope.ApplicationDetails.CreditScoreID,
"ProgramID": ProgramID,
ProgramLoanType: $scope.ApplicationDetails.ProgramLoanType,
UsingDefault: FALSE
});
}
if (response.ResponseCode == 4) {
$scope.showFlashMessage('error', response.Message);
}
$scope.btnText = '';
if (!$scope.ApplicationDetails.ProgramName) {
$scope.btnText = 'Share';
} else if ($scope.CompanyPreferences.Category == 'Bank') {
$scope.btnText = 'Revoke';
}
// $scope.borrowerView=([4,6].indexOf($rootScope.SignIn.UserDetails.UserTypeID)!=-1 || [20,22].indexOf($scope.ApplicationDetails.StatusID)!=-1 || $rootScope.CompanyPreferences.Category=="Bank" || ($rootScope.SignIn.UserDetails.UserTypeID==3 && $rootScope.CompanyPreferences.PlanID==1));
$scope.borrowerView = ([4, 6].indexOf($rootScope.SignIn.UserDetails.UserTypeID) != -1 || [20, 22].indexOf($scope.ApplicationDetails.StatusID) != -1);
// $scope.loading =
$scope.approved = ($scope.ApplicationDetails.ApplicationStatusID == 2);
$scope.DownPayment = $scope.ApplicationDetails.DownPayment;
if (typeof callback != 'undefined')
callback();
if ($rootScope.SignIn.UserDetails.UserTypeID != 4 && $scope.ApplicationDetails.ProgramName && $rootScope.CompanyPreferences.Category != 'Bank') {
$scope.partnerDetailView = true;
}
$scope.showAdditionalInfo();
$scope.ApplicationStatusLog();
$scope.ApplicationOfferLog();
$scope.applicationStatusBinding();
$scope.Page.documents = {
"ModuleEntityID": $stateParams.ApplicationNumber,
"ModuleName": "ApplicationDocument",
"selectedFiles": [],
"DocumentsData": [],
"selectedFileIds": [],
"FolderName": [],
"checkedFile": false,
"zipName": $stateParams.ApplicationNumber,
"filter": { "currentPage": 1 },
"removeCallback": $scope.refreshRequiredDocumentTypeList
}
$scope.switchtab($stateParams.activeTab, true);
}
else {
$scope.showFlashMessage('error', response.Message);
}
$scope.detailsLoaded = true;
$scope.changeStatusFlag = false;
});
}
$scope.acceptRejectApproval = function (flag) {
switch (flag) {
case 'accept':
$rootScope.ngConfirm("Are you sure you want to accept the changes?", function () {
$scope.Application.unapproveComment = '';
$scope.ApplicationDetails.ApplicationStatus = {};
// $scope.ApplicationDetails.ApplicationStatus.StatusID=30;
$scope.ApplicationDetails.ApplicationStatus.StatusID = 39;
$scope.appStatusUpdate();
$scope.GetApplicationDetails();
});
break
case 'reject':
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-Accept-reject-payment-details.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope,
closeByEscape: false,
closeByDocument: false
});
break;
case 'view':
angular.element("#viewPayment").trigger('click');
$scope.switchtab('Payment')
break;
}
}
$scope.RejectApproval = function () {
if (checkstatus('frmDeclined', $scope)) {
$scope.Application.unapproveStatusFlags = '';
$scope.ApplicationDetails.ApplicationStatus = {};
// $scope.ApplicationDetails.ApplicationStatus.StatusID=29;
$scope.ApplicationDetails.ApplicationStatus.StatusID = 46;
$scope.appStatusUpdate();
$scope.LoanData.FinanceAmount = $scope.ApplicationDetails.PartnerLoanData.FinanceAmount;
$scope.LoanData.DownPayment = parseInt($scope.ApplicationDetails.RequestedAmount) - parseInt($scope.ApplicationDetails.PartnerLoanData.FinanceAmount);
$scope.LoanData.FinanceTenure = _.findWhere($rootScope.appliedProgram.Terms, { Term: $scope.ApplicationDetails.PartnerLoanData.FinanceTenure });
// $scope.updatePaymentDetails();
ngDialog.close();
}
}
$scope.getShareApplicationPrograms = function (callback, StatusID) {
var reqData = {
"GetShareApplicationPrograms": {
"ApplicationNumber": $stateParams.ApplicationNumber,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
// if(StatusID){
// reqData.GetShareApplicationPrograms.StatusID = StatusID;
// }
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.ApplicationStatusData = response.Data;
if (StatusID != 37) {
$scope.ShareAppData = $scope.ApplicationStatusData;
}
$scope.FurtherActionMessage = response.Message;
var matchingTerm = null;
if ($scope.ApplicationStatusData) {
for (var i in $scope.ApplicationStatusData) {
if ($scope.ApplicationStatusData[i].Metadata && $scope.ApplicationStatusData[i].Metadata.InterestRate) {
$scope.ApplicationStatusData[i].FinanceTenure = $scope.ApplicationStatusData[i].Metadata.FinanceTenure;
$scope.ApplicationStatusData[i].appliedEMI = $scope.ApplicationStatusData[i].Metadata.AmountPayable;
$scope.ApplicationStatusData[i].appliedRate = $scope.ApplicationStatusData[i].Metadata.AppliedRate;
/*Code for show Valid Till Date - Start*/
$scope.ApplicationStatusData[i].ValidTillDate = $scope.ApplicationStatusData[i].Metadata.ValidTillDate;
/*Code for show Valid Till Date - End*/
} else {
$scope.ApplicationStatusData[i].appliedEMI = $scope.ApplicationStatusData[i].AmountPayable;
if ($scope.ApplicationStatusData[i].FinanceTenure > $scope.ApplicationStatusData[i].MaxTenure)
$scope.ApplicationStatusData[i].FinanceTenure = $scope.ApplicationStatusData[i].MaxTenure;
$scope.ApplicationStatusData[i].appliedEMI = $scope.ApplicationStatusData[i].AmountPayable;
$scope.ApplicationStatusData[i].appliedRate = $scope.ApplicationStatusData[i].AppliedRate;
// LoanData.UseCustomRate=$scope.ApplicationStatusData[i].MinRate;
// LoanData=appInfo.getCalcData(LoanData);
// $scope.ApplicationStatusData[i].minEMI=LoanData.AmountPayable;
// LoanData.UseCustomRate=$scope.ApplicationStatusData[i].MaxRate;
// LoanData=appInfo.getCalcData(LoanData);
// $scope.ApplicationStatusData[i].maxEMI=LoanData.AmountPayable;
}
}
}
if (typeof callback != 'undefined' && callback != '')
callback();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.onOfferedProgramSelect = function () {
if (!$scope.ApplicationDetails.selectedOffer.Metadata) {
$scope.LoanData.FinanceTenure = _.findWhere($scope.ApplicationDetails.selectedOffer.Terms, { Term: $scope.ApplicationDetails.selectedOffer.FinanceTenure });
$scope.LoanData.InterestRate = $scope.LoanData.FinanceTenure.Rate;
$scope.LoanData.CommissionPoints = $scope.ApplicationDetails.selectedOffer.CommissionCap;
$scope.changeEMI($scope.LoanData);
} else {
if (parseInt($scope.ApplicationDetails.FinanceAmount) > parseInt($scope.ApplicationStatusData[0].MaxAmountRange)) {
$scope.LoanData.approvedAmount = $scope.ApplicationStatusData[0].MaxAmountRange;
}
else {
$scope.LoanData.approvedAmount = $scope.ApplicationDetails.selectedOffer.Metadata.FinanceAmount;
}
$scope.LoanData.FinanceTenure = _.findWhere($scope.ApplicationDetails.selectedOffer.Terms, { Term: $scope.ApplicationDetails.selectedOffer.Metadata.FinanceTenure });
$scope.LoanData.InterestRate = $scope.ApplicationDetails.selectedOffer.Metadata.InterestRate * 100;
$scope.LoanData.CommissionPoints = $scope.ApplicationDetails.selectedOffer.Metadata.CommissionPoints;
$scope.LoanData.downPayment = $scope.LoanData.FinanceAmount - $scope.LoanData.approvedAmount;
$scope.LoanData.approveFlag = $scope.LoanData.downPayment ? 'partial' : 'full';
$scope.ValidTillDate = (new Date($scope.ApplicationDetails.selectedOffer.Metadata.ValidTillDate)).toLocaleDateString("en-US");
$scope.disableButton = false;
with ($scope.LoanData) {
$scope.EMIData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : 1,
"FinanceAmount": (approvedAmount) ? (approvedAmount + '').replace(',', '') : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (typeof FinanceTenure == 'object')) ? FinanceTenure.Term : $rootScope.CompanyPreferences.DefaultLoanTerm,
"ShowConfigurationError": (typeof preventRevert != 'undefined') ? preventRevert : true,
"CommissionPoints": CommissionPoints,
"ProgramID": $scope.ApplicationDetails.selectedOffer.ProgramID,
"UseCustomRate": InterestRate
});
}
// $scope.EMIData = $scope.changeEMI($scope.LoanData);
$scope.LoanData.AmountPayable = $scope.EMIData.AmountPayable;
if (!$scope.$$phase)
$scope.$apply();
// console.log(EMIData);
}
}
$scope.changeEMI = function (LoanData) {
if ($scope.RateOption == 'RF') {
$scope.RateOfFactor = LoanData.InterestRate;
$scope.Approvedpayment = LoanData.approvedAmount;
$scope.paymentRf = appInfo.getRateFactor($scope.RateOfFactor, $scope.Approvedpayment);
$scope.LoanData.AmountPayable = $scope.paymentRf;
} else {
with (LoanData) {
$scope.EMIData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : 1,
"FinanceAmount": (FinanceAmount) ? (FinanceAmount + '').replace(',', '') : $scope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (typeof FinanceTenure == 'object')) ? FinanceTenure.Term : $scope.CompanyPreferences.DefaultLoanTerm,
"CommissionPoints": CommissionPoints,
"ProgramID": ($scope.ApplicationDetails.selectedOffer) ? $scope.ApplicationDetails.selectedOffer.ProgramID : $scope.CompanyPreferences.DefaultProgramID,
"UseCustomRate": InterestRate,
"TimeFormat": $scope.TimeFormatC,
"approveFlag":approveFlag
});
}
$scope.LoanData.AmountPayable = $scope.EMIData.AmountPayable;
if (!$scope.$$phase)
$scope.$apply();
}
}
$scope.onOfferedProgramTermSelect = function () {
if ($scope.RateOption === 'BR') {
$scope.LoanData.InterestRate = $scope.LoanData.FinanceTenure.Rate;
$scope.changeEMI($scope.LoanData);
}
}
$scope.initLoading = function () {
$scope.Page.Title = 'Application Details - ' + $rootScope.CompanyPreferences.CompanyName;
$scope.IsCorpOnlyBusinessLoanAllowed = $rootScope.CompanyPreferences.IsCorpOnlyBusinessLoanAllowed ? 'yes' : 'no';
appInfo.getStatusList($scope.GetApplicationDetails);
}
$scope.applicationStatusBinding = function () {
// console.log(this,$scope);
if ($rootScope.CompanyPreferences.Category == "Bank") {
$scope.DisableStatus = [10, 12, 21, 22, 23, 35, 37, 38, 39, 42, 46, 47, 48];
}
else {
$scope.DisableStatus = [10, 12, 19, 20, 21, 22, 23, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48];
if (!_.isUndefined($scope.ApplicationDetails) && $scope.ApplicationDetails.StatusID != 44) {
$scope.DisableStatus.push(45);
}
}
}
$scope.getPdf = function () {
angular.element('#frmDownloadPDF').submit();
};
$scope.getEditMetaData = function () {
appInfo.getStates(function () {
appInfo.getIndustryTypes(function () {
var IndustryTypes = [];
for (var j in $rootScope.industryData) {
for (var i in $scope.ApplicationDetails.IndustryTypes)
if ($rootScope.industryData[j].IndustryTypeID == $scope.ApplicationDetails.IndustryTypes[i]) {
IndustryTypes.push($rootScope.industryData[j]);
}
}
$scope.ApplicationDetails.IndustryTypes = IndustryTypes;
appInfo.getLegalStructureName(function () {
for (var j in $rootScope.legalStructureData) {
if ($rootScope.legalStructureData[j].LegalStructureID == $scope.ApplicationDetails.LegalStructureID) {
$scope.ApplicationDetails.LegalStructure = $rootScope.legalStructureData[j];
}
}
$scope.industryRestricted = true;
$scope.blockBusinessEditing = true;
});
});
for (var j in $rootScope.stateData) {
if ($rootScope.stateData[j].StateID == $scope.ApplicationDetails.BusinessStateID)
$scope.ApplicationDetails.BusinessStateID = $rootScope.stateData[j];
if ($rootScope.stateData[j].StateID == $scope.ApplicationDetails.PersonalStateID)
$scope.ApplicationDetails.PersonalStateID = $rootScope.stateData[j];
}
for (var j in $rootScope.stateData) {
if ($rootScope.stateData[j].StateID == $scope.ApplicationDetails.MedicalLicenseStateID)
$scope.ApplicationDetails.MedicalLicenseStateID = $rootScope.stateData[j];
}
$scope.blockPersonalEditing = true;
});
$scope.LoanData = {
FinanceAmount: $scope.ApplicationDetails.FinanceAmount,
RequestedAmount: $scope.ApplicationDetails.RequestedAmount,
FinanceCredit: _.findWhere($scope.CreditScores, { CreditScoreID: $scope.ApplicationDetails.CreditScoreID }),
FinanceTimeInBusiness: _.findWhere($scope.TimeInBusiness, { TimeInBusinessID: $scope.ApplicationDetails.FinanceTimeInBusiness }),
InterestRate: ($scope.ApplicationDetails.InterestRate * 100).toFixed(2),
CommissionPoints: parseFloat($scope.ApplicationDetails.CommissionPoints) ? $scope.ApplicationDetails.CommissionPoints : $scope.CompanyPreferences.DefaultCommissionCap,
FinanceTenure: _.findWhere($scope.appliedProgram.Terms, { Term: $scope.ApplicationDetails.FinanceTenure }),
AmountPayable: $scope.ApplicationDetails.AmountPayable,
DownPayment: $scope.ApplicationDetails.DownPayment,
FinancePurpose: [],
approvedAmount: null
};
if (!$scope.LoanData.FinanceTenure) {
$scope.LoanData.FinanceTenure = _.last($scope.appliedProgram.Terms);
if($scope.ApplicationDetails.StatusID != 37){
$scope.showFlashMessage('info', 'Finance Tenure ' + $scope.ApplicationDetails.FinanceTenure + ' is not available based on the application details. Rolling back to max available tenure.');
}
}
appInfo.getFinancePurposeList(function () {
for (var i in $rootScope.FinancePurposeData) {
for (var j in $scope.ApplicationDetails.FinancePurposeID) {
if ($rootScope.FinancePurposeData[i].FinancePurposeID == $scope.ApplicationDetails.FinancePurposeID[j])
$scope.LoanData.FinancePurpose.push($rootScope.FinancePurposeData[i]);
}
}
// $scope.LoanData.FinancePurpose=_.findWhere($scope.FinancePurposeData,{FinancePurposeID:$scope.ApplicationDetails.FinancePurposeID});
$scope.ApplicationDetails.CustomRate = null;
$scope.blockPaymentEditing = true;
$scope.getShareApplicationPrograms();
});
for (var j in $scope.PurposeOfPurchase) {
if ($scope.PurposeOfPurchase[j].key == $scope.ApplicationDetails.PurposeOfPurchase) {
$scope.ApplicationDetails.PurposeOfPurchase = $scope.PurposeOfPurchase[j];
}
}
if ($scope.ApplicationDetails.TimeInBusiness) {
$scope.ApplicationDetails.TimeInBusiness = $scope.ApplicationDetails.TimeInBusiness.split('-');
for (var j in $rootScope.MasterMonths) {
if ($rootScope.MasterMonths[j].key == $scope.ApplicationDetails.TimeInBusiness[1]) {
$scope.ApplicationDetails.BusinessMonth = $rootScope.MasterMonths[j];
break;
}
}
for (var j in $rootScope.Years) {
if ($rootScope.Years[j].Year == $scope.ApplicationDetails.TimeInBusiness[0]) {
$scope.ApplicationDetails.BusinessYear = $rootScope.Years[j];
break;
}
}
}
// $scope.Application.getNotes();
}
$scope.updateShareingStatus = function (ProgramID) {
if ($scope.btnText == 'Revoke') {
$scope.loading = true;
appInfo.cancelSharedApplication($scope.ApplicationDetails, function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.loading = false;
$scope.getShareApplicationPrograms();
$scope.partnerDetailView = false;
}
}, ProgramID);
$scope.loading = false;
} else {
$location.path('/share-application/' + $scope.ApplicationDetails.ApplicationNumber);
}
}
// Start Application Edit Handling
$scope.editPersonalDetails = function () {
$scope.blockPersonalEditing = false;
$scope.ApplicationDetails.PercentageOwnership = $scope.ApplicationDetails.PercentageOwnership;
}
$scope.editBusinessOwners = function (index) {
$scope.RemoveBusinessOwnerIDs = [];
//$scope.blockOwnerEditing=false;
$scope.ApplicationDetails.BusinessOwners[index]['blockOwnerEditing'] = false;
$scope.ApplicationDetails.PercentageOwnership = $scope.ApplicationDetails.PercentageOwnership;
}
$scope.cancelOwnerUpdate = function (e) {
$rootScope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
$scope.blockOwnerEditing = false;
$scope.GetApplicationDetails(function () {
$scope.blockOwnerEditing = true;
clearValidation('FrmAdditionalOwner');
});
});
}
$scope.editBusinessDetails = function () {
$scope.blockBusinessEditing = false;
$scope.industryRestricted = $rootScope.CompanyPreferences.RestrictIndustryDefault;
}
$scope.updatePersonalDetails = function () {
if (checkstatus('personalDetailsValidation', $scope)) {
$scope.loading = true;
var reqData = {
"EditApplication": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"ModuleName": "PersonalDetails",
"TargetID": $scope.ApplicationDetails.UserID,
"BusinessID": $scope.ApplicationDetails.BusinessID,
"PersonalDetails":
{
"FirstName": $scope.ApplicationDetails.FirstName,
"LastName": $scope.ApplicationDetails.LastName,
"Email": $scope.ApplicationDetails.Email,
"MobileNumber": $scope.ApplicationDetails.MobileNumber,
"Address1": $scope.ApplicationDetails.PersonalAddress1,
"Address2": $scope.ApplicationDetails.PersonalAddress2,
"CityID": $scope.ApplicationDetails.PersonalCityName,
"StateID": $scope.ApplicationDetails.PersonalStateID.StateID,
"Postal": $scope.ApplicationDetails.PersonalPostal,
"SocialSecurityNumber": $scope.ApplicationDetails.SocialSecurityNumber,
"PercentageOwnership": $scope.ApplicationDetails.PercentageOwnership,
}
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.blockPersonalEditing = true;
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.loading = false;
}, function () {
$scope.loading = false;
});
} else {
$scope.showFlashMessage('error', 'Please correct the marked data errors.')
}
}
$scope.cancelPersonalUpdate = function (e) {
$rootScope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
$scope.blockPaymentEditing = false;
$scope.GetApplicationDetails(function () {
$scope.blockPaymentEditing = $scope.blockPersonalEditing = true;
clearValidation('personalDetailsValidation')
});
});
}
$scope.cancelBusinessUpdate = function (e) {
$rootScope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
$scope.blockPaymentEditing = false;
$scope.GetApplicationDetails(function () {
$scope.blockPaymentEditing = $scope.industryRestricted = $scope.blockBusinessEditing = true;
clearValidation('frmBusinessDetails');
});
});
}
$scope.updateBusinesDetails = function () {
if ($scope.ApplicationDetails.MedicalLicenseIssueDate) {
var date = new Date($scope.ApplicationDetails.MedicalLicenseIssueDate);
$scope.ApplicationDetails.MedicalLicenseIssueDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear()
}
if (checkstatus('frmBusinessDetails', $scope)) {
$scope.loading = true;
var reqData = {
"EditApplication": {
"TargetID": $scope.ApplicationDetails.BusinessID,
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"ModuleName": "BusinessDetails",
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"BusinessDetails":
{
"BusinessName": $scope.ApplicationDetails.BusinessName,
"BusinessDBA": $scope.ApplicationDetails.BusinessDBA,
"TaxID": $scope.ApplicationDetails.TaxID,
"LegalStructureID": $scope.ApplicationDetails.LegalStructure ? $scope.ApplicationDetails.LegalStructure.LegalStructureID : null,
"BusinessYear": $scope.ApplicationDetails.BusinessYear.Year,
"BusinessMonth": $scope.ApplicationDetails.BusinessMonth.key,
"IndustryTypes": $scope.ApplicationDetails.IndustryTypes.IndustryTypeID,
"Address1": $scope.ApplicationDetails.Address1,
"Address2": $scope.ApplicationDetails.Address2,
"StateID": $scope.ApplicationDetails.BusinessStateID.StateID,
"CityID": $scope.ApplicationDetails.BusinessCityName,
"Postal": $scope.ApplicationDetails.Postal,
"PhoneNumber": $scope.ApplicationDetails.PhoneNumber,
"PrimaryContactName": $scope.ApplicationDetails.PrimaryContactName,
"PrimaryContactTitle": $scope.ApplicationDetails.PrimaryContactTitle,
"PrimaryContactNumber": $scope.ApplicationDetails.PrimaryContactNumber,
"MedicalSpecialityDescription": $scope.ApplicationDetails.MedicalSpecialityDescription,
"PatientsGroupID": $scope.ApplicationDetails.PatientsGroupID,
"EmployeeGroupID": $scope.ApplicationDetails.EmployeeGroupID,
"MedicalStaffGroupID": $scope.ApplicationDetails.MedicalStaffGroupID,
"SupportStaffGroupID": $scope.ApplicationDetails.SupportStaffGroupID,
"MedicalLicense": $scope.ApplicationDetails.MedicalLicense,
"MedicalLicenseIssueDate": $scope.ApplicationDetails.MedicalLicenseIssueDate,
"MedicalLicenseStateID": ($scope.ApplicationDetails.MedicalLicenseStateID) ? $scope.ApplicationDetails.MedicalLicenseStateID.StateID : null,
"MedicalGroupMember": $scope.ApplicationDetails.MedicalGroupMember,
"MedicalGroups": $scope.ApplicationDetails.MedicalGroups,
"MalPracticePerIncident": $scope.ApplicationDetails.MalPracticePerIncident,
"MalPracticeTotal": $scope.ApplicationDetails.MalPracticeTotal,
"InsuranceCarriersAccepted": $scope.ApplicationDetails.InsuranceCarriersAccepted,
"PurposeOfPurchase": $scope.ApplicationDetails.PurposeOfPurchase.key,
"EquipmentDescription": $scope.ApplicationDetails.EquipmentDescription ? $scope.ApplicationDetails.EquipmentDescription : null,
"CreatedDate": $scope.ApplicationDetails.CreatedDate
}
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.industryRestricted = $scope.blockBusinessEditing = true;
$scope.showFlashMessage('success', response.Message);
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.loading = false;
});
}
}
$scope.addOwners = function () {
$scope.ApplicationDetails.BusinessOwners.splice(0, 0, { blockOwnerEditing: false });
}
$scope.addBlocking = function (BusinessOwner) {
$scope.RemoveBusinessOwnerIDs = [];
if ('blockOwnerEditing' in BusinessOwner) {
BusinessOwner.blockOwnerEditing = false;
} else {
BusinessOwner.blockOwnerEditing = true;
}
}
$scope.removeOwner = function () {
$scope.selectedBusinessOwner = this;
$rootScope.ngConfirm('Are you sure you want to delete this owner ?', function () {
$scope.RemoveBusinessOwnerIDs.push($scope.selectedBusinessOwner.BusinessOwner.BusinessOwnerID);
$scope.ApplicationDetails.BusinessOwners.splice($scope.selectedBusinessOwner.$index, 1);
//remove owners
if ($scope.RemoveBusinessOwnerIDs.length != 0) {
var reqData = {
"RemoveOwner": {
"BusinessOwnerID": $scope.RemoveBusinessOwnerIDs,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
// $scope.showFlashMessage('success',response.Message);
// $scope.ApplicationDetails.BusinessOwners.splice(this.$index,1);
$scope.blockOwnerEditing = true;
//performUpdate();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
} else {
for (var i in $scope.ApplicationDetails.BusinessOwners) {
$scope.ApplicationDetails.BusinessOwners[i].StateID = $scope.ApplicationDetails.BusinessOwners[i].StateID.StateID;
$scope.ApplicationDetails.BusinessOwners[i].Postal = $scope.ApplicationDetails.BusinessOwners[i].PostalCode;
delete $scope.ApplicationDetails.BusinessOwners[i].PostalCode;
}
//performUpdate();
}
//remove owners
});
}
$scope.updateOwnersship = function () {
BusinessOwners = $scope.ApplicationDetails.BusinessOwners;
var i = '';
var goNext = true;
angular.forEach(BusinessOwners, function (BusinessOwner, key) {
if (BusinessOwner.PercentageOwnership == 0) {
goNext = false;
$scope.showFlashMessage('error', 'Total Ownership cant be greater than 100%.'); return false;
}
if (!BusinessOwner.StateID) {
goNext = false;
$scope.showFlashMessage('error', 'Please fill required fields'); return false;
}
});
if (checkstatus('FrmAdditionalOwner', $scope) && goNext) {
var performUpdate = function () {
var reqData = {
"EditApplication": {
"ModuleName": "AdditionalOwners",
"TargetID": $scope.ApplicationDetails.UserID,
"BusinessID": $scope.ApplicationDetails.BusinessID,
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"AdditionalOwners": $scope.ApplicationDetails.BusinessOwners,
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.BusinessOwnerData = response.Data.BusinessOwnerData;
$scope.showFlashMessage('success', response.Message);
$scope.blockOwnerEditing = true;
$scope.GetApplicationDetails();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
if ($scope.RemoveBusinessOwnerIDs.length != 0) {
var reqData = {
"RemoveOwner": {
"BusinessOwnerID": $scope.RemoveBusinessOwnerIDs,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
// $scope.showFlashMessage('success',response.Message);
// $scope.ApplicationDetails.BusinessOwners.splice(this.$index,1);
$scope.blockOwnerEditing = true;
performUpdate();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
} else {
for (var i in $scope.ApplicationDetails.BusinessOwners) {
$scope.ApplicationDetails.BusinessOwners[i].StateID = $scope.ApplicationDetails.BusinessOwners[i].StateID.StateID;
$scope.ApplicationDetails.BusinessOwners[i].CityID = $scope.ApplicationDetails.BusinessOwners[i].City;
$scope.ApplicationDetails.BusinessOwners[i].Postal = $scope.ApplicationDetails.BusinessOwners[i].PostalCode;
delete $scope.ApplicationDetails.BusinessOwners[i].PostalCode;
delete $scope.ApplicationDetails.BusinessOwners[i].blockOwnerEditing;
}
performUpdate();
}
}
}
$scope.editPaymentDetails = function () {
$scope.validateData = true;
$scope.blockPaymentEditing = false;
}
$scope.showAdditionalInfo = function () {
var reqData = {
"GetApplicationAdditionalDetails": {
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (!response.Data || response.Data.length == 0) {
return false;
}
$scope.additionalFields = response.Data;
$scope.blockAdditionalFieldEditing = true;
$timeout(function () {
$("#frmAdditionalFields select").trigger("chosen:updated");
});
});
}
$scope.updateEMI = function () {
if ($scope.detailsLoaded && $scope.FinancePurposeData && $scope.validateData) {
with ($scope.LoanData) {
var LoanData = appInfo.getCalcData({
"FinancePurposeID": (_.isObject(FinancePurpose)) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (_.isObject(FinanceCredit)) ? FinanceCredit.CreditScoreID : 1,
"FinanceAmount": (FinanceAmount) ? (FinanceAmount + '').replace(',', '') : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (_.isObject(FinanceTenure)) ? FinanceTenure.Term : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": (FinanceTimeInBusiness && (typeof FinanceTimeInBusiness == 'object')) ? FinanceTimeInBusiness.TimeInBusinessID : $scope.CompanyPreferences.DefaultTimeInBusinessID,
"CommissionPoints": CommissionPoints,
"UseCustomRate": ($scope.UseCustomRate && parseFloat(InterestRate)) ? parseFloat(InterestRate) : false
});
$scope.LoanData.AmountPayable = LoanData.AmountPayable;
$scope.LoanData.InterestRate = (LoanData.InterestRate * 100).toFixed(4);
$scope.LoanData.appliedRate = LoanData.appliedRate;
}
if ($scope.ProgramLoanType) {
$scope.LoanData.ProgramLoanType = $scope.ProgramLoanType;
}
else {
if ($rootScope.CompanyPreferences.LoanType2 == 'BusinessLoanHomePage') {
$scope.LoanData.ProgramLoanType = 'Business';
}
else if ($rootScope.CompanyPreferences.LoanType2 == 'PersonalLoanHomePage') {
$scope.LoanData.ProgramLoanType = 'Personal';
}
else if ($rootScope.CompanyPreferences.LoanType == 'Both' && $rootScope.CompanyPreferences.LoanType2 == 'BusinessLoanHomePage') {
$scope.LoanData.ProgramLoanType = 'Business';
}
else {
$scope.LoanData.ProgramLoanType = 'Personal';
}
}
$scope.LoanData.ProgramLoanType = 'Business';
return LoanData;
} else {
return true;
}
}
$scope.$watch('LoanData.FinanceAmount', _.debounce(function (newValue, oldValue) {
if (newValue && newValue != oldValue) {
$scope.UseCustomRate = true;
if (newValue.length < 4 || !$scope.updateEMI()) {
if (parseFloat(newValue) > $scope.appliedProgram.MaxAmount)
$scope.errorFinanceAmount = 'Maximum allowed amount is $ ' + $scope.appliedProgram.MaxAmount.formatMoney();
else
$scope.errorFinanceAmount = 'Minimum required amount is $ ' + $scope.appliedProgram.MinAmount.formatMoney();
$scope.ApplicationDetails.AmountPayable = null;
if (!_.isUndefined($scope.LoanData.updateTermsDropDownUI))
$scope.LoanData.updateTermsDropDownUI();
} else
$scope.errorFinanceAmount = '';
}
}, 800));
$scope.$watch('LoanData.FinanceCredit', function (newValue, oldValue) {
if (_.isObject(newValue) && _.isObject($scope.ApplicationDetails.FinanceTimeInBusiness) && !angular.equals(newValue, oldValue)) {
$scope.UseCustomRate = false;
appInfo.getFundingProgram(function () {
if (!$scope.updateEMI()) {
if ($scope.LoanData.FailOverUserCreditScore != newValue) {
$scope.LoanData.FinanceCredit = oldValue;
$scope.LoanData.FailOverUserCreditScore = oldValue;
}
}
}, true, {
TimeInBusinessID: $scope.ApplicationDetails.FinanceTimeInBusiness.TimeInBusinessID,
CreditScoreID: newValue.CreditScoreID,
ProgramID: ($scope.ApplicationDetails.ProgramID) ? $scope.ApplicationDetails.ProgramID : $scope.CompanyPreferences.DefaultProgramID,
UsingDefault: FALSE,
ProgramLoanType: $scope.ApplicationDetails.ProgramLoanType,
});
}
});
$scope.lastUpdatedAppforBR = 0;
$scope.lastUpdatedInterestRateBR = 0;
$scope.lastUpdatedAppforRF = 0;
$scope.lastUpdatedInterestRateRF = 0;
$scope.lastUpdatedAmountPayableBR = 0;
$scope.lastUpdatedAmountPayableRF = 0;
$scope.setRateOfIntrest = function () {
if ($scope.RateOption === 'BR') {
$scope.RateOption = 'RF';
$scope.lastUpdatedAppforBR = $scope.LoanData.approvedAmount;
$scope.lastUpdatedInterestRateBR = $scope.LoanData.InterestRate;
$scope.lastUpdatedAmountPayableBR = $scope.LoanData.AmountPayable;
// console.log($scope.lastUpdatedAppforRF);
$scope.LoanData.approvedAmount = $scope.lastUpdatedAppforRF === 0 ? $scope.LoanData.approvedAmount : $scope.lastUpdatedAppforRF;
$scope.LoanData.InterestRate = $scope.lastUpdatedInterestRateRF;
$scope.LoanData.AmountPayable = $scope.lastUpdatedAmountPayableRF;
} else {
$scope.RateOption = 'BR';
$scope.lastUpdatedAppforRF = $scope.LoanData.approvedAmount;
$scope.lastUpdatedInterestRateRF = $scope.LoanData.InterestRate;
$scope.lastUpdatedAmountPayableRF = $scope.LoanData.AmountPayable;
$scope.LoanData.approvedAmount = $scope.lastUpdatedAppforBR;
$scope.LoanData.InterestRate = $scope.lastUpdatedInterestRateBR;
$scope.LoanData.AmountPayable = $scope.lastUpdatedAmountPayableBR;
}
}
function updateRate(newValue, oldValue) {
if ($scope.RateOption === 'RF') {
$scope.RateOfFactorLr = $scope.LoanData.InterestRate;
$scope.ApprovedpaymentLr = $scope.LoanData.approvedAmount;
$scope.paymentRfW = appInfo.getRateFactor($scope.RateOfFactorLr, $scope.ApprovedpaymentLr);
$scope.LoanData.AmountPayable = $scope.paymentRfW;
} else {
if (newValue && newValue != oldValue) {
$scope.UseCustomRate = true;
if (!$scope.LoanData.CommissionPoints)
$scope.LoanData.CommissionPoints = 0;
if (!$scope.updateEMI()) {
//console.log(this);
}
}
}
}
$scope.$watch('LoanData.CommissionPoints', _.debounce(updateRate, 200));
$scope.$watch('LoanData.InterestRate', _.debounce(updateRate, 200));
$scope.$watch('LoanData.FinanceTenure', function (newValue, oldValue) {
if (newValue && !angular.equals(newValue, oldValue)) {
$scope.UseCustomRate = false;
if (!$scope.updateEMI()) {
if ($scope.LoanData.FailOverFinanceTenure != newValue) {
$scope.LoanData.FinanceTenure = oldValue;
$scope.LoanData.FailOverFinanceTenure = oldValue;
}
}
}
});
$scope.$watch('LoanData.FinanceTimeInBusiness', function (newValue, oldValue) {
if (_.isObject(newValue) && !angular.equals(newValue, oldValue)) {
$scope.UseCustomRate = false;
appInfo.getFundingProgram(function () {
if (!$scope.updateEMI()) {
if ($scope.LoanData.FailOverFinanceTimeInBusiness != newValue) {
$scope.LoanData.FinanceTimeInBusiness = oldValue;
$scope.LoanData.FailOverFinanceTimeInBusiness = oldValue;
}
}
}, true, {
TimeInBusinessID: newValue.TimeInBusinessID,
CreditScoreID: $scope.LoanData.FinanceCredit.CreditScoreID,
ProgramID: ($scope.ApplicationDetails.ProgramID) ? $scope.ApplicationDetails.ProgramID : $scope.CompanyPreferences.DefaultProgramID,
ProgramLoanType: $scope.ApplicationDetails.ProgramLoanType,
UsingDefault: FALSE
});
}
});
$scope.updatePaymentDetails = function () {
if (checkstatus('frmLoanData', $scope) && $scope.updateEMI()) {
$scope.loading = true;
var reqData = {
"EditApplication":
{
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"ModuleName": "LoanAmount",
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"TargetID": $scope.ApplicationDetails.UserID,
"LoanData": {
"FinancePurposeID": $scope.LoanData.FinancePurpose.FinancePurposeID,
"FinanceAmount": $scope.LoanData.FinanceAmount,
"FinanceTenure": $scope.LoanData.FinanceTenure.Term,
// "FinanceTimeInBusiness": $scope.LoanData.FinanceTimeInBusiness.TimeInBusinessID,
"FinanceTimeInBusiness": [],
"InterestRate": parseFloat($scope.LoanData.InterestRate) / 100,
"AmountPayable": $scope.LoanData.AmountPayable,
"CreditScoreID": $scope.LoanData.FinanceCredit.CreditScoreID,
"CommissionPoints": parseFloat($scope.LoanData.CommissionPoints),
"AssignedPartner": $scope.ApplicationDetails.AssignedPartner,
"DownPayment": $scope.LoanData.DownPayment
}
}
};
if (reqData.EditApplication.LoanData && $scope.LoanData.ProgramLoanType == 'Business') {
reqData.EditApplication.LoanData.FinancePurposeID = [];
for (var i in $scope.LoanData.FinancePurpose) {
if (typeof $scope.LoanData.FinancePurpose[i] == 'object')
reqData.EditApplication.LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i].FinancePurposeID);
else
reqData.EditApplication.LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i]);
}
}
if ($scope.ApplicationDetails.currentProgramID) {
if ($scope.ApplicationDetails.currentProgramID)
reqData.EditApplication.ProgramID = $scope.ApplicationDetails.currentProgramID.ProgramID;
}
else if ($scope.ApplicationStatusData)
reqData.EditApplication.ProgramID = $scope.ApplicationStatusData[0].ProgramID;
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.GetApplicationDetails(function () {
$scope.blockPaymentEditing = true;
});
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.loading = false;
});
} else {
$scope.showFlashMessage('error', 'Please correct the marked data errors.')
}
}
$scope.updateRequestedAmount = function () {
if (checkstatus('requestedAmountfrm', $scope)) {
$scope.loading = true;
var reqData = {
"EditApplication": {
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"ModuleName": "RequestAmount",
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"TargetID": $scope.ApplicationDetails.UserID,
"RequestedAmount": $scope.LoanData.RequestedAmount
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.GetApplicationDetails(function () {
$scope.blockPaymentEditing = true;
});
$scope.loading = false;
});
ngDialog.close();
} else {
$scope.showFlashMessage('error', 'Please correct the marked data errors.')
}
}
$scope.cancelPaymentUpdate = function (e) {
$rootScope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
$scope.validateData = false;
$scope.GetApplicationDetails(function () {
$scope.errorFinanceAmount = '';
$scope.blockPaymentEditing = true;
$scope.errorCommissionPoint = null;
clearValidation('frmLoanData');
});
});
}
$scope.showProgramDetails = function () {
Storage.setItem('ProgramDetails', { 'ProgramID': this.ApplicationDetails.ProgramID });
$location.path('/program/view/config');
}
if ($rootScope.CompanyPreferences) {
$scope.initLoading();
} else
$rootScope.$on('company-loaded', function (event, eSrc) {
$scope.initLoading();
});
$scope.navigateToProposals = function () {
$location.path('/proposal-status/' + this.ApplicationDetails.ProposalGUID);
}
$scope.showDescription = function (index) {
$('#showDiv' + index).toggle();
//$scope.showNoteDesc = !$scope.showNoteDesc
}
$scope.cancalApplicationStatus = function (StatusID) {
$scope.ApplicationDetails.ApplicationStatus = _.findWhere($scope.statusList, { StatusID: StatusID });
}
$scope.$watch("LoanData.approveFlag", function (newVal) {
if (!newVal)
return;
if (newVal == 'full') {
$scope.approveFull = true;
// $scope.LoanData.approvedAmount=$scope.ApplicationDetails.FinanceAmount;
$scope.LoanData.approvedAmount = $scope.LoanData.FinanceAmount;
$scope.LoanData.downPayment = 0;
$scope.disableButton = false;
$scope.ApplicationDetails.ApplicationStatus.StatusID = ($scope.companyPermissions.Application.PermittedActions['Review Required'] && $scope.CompanyPreferences.FundingManagerID) ? 56 : 37;
}
else {
$scope.approveFull = false;
$scope.ApplicationDetails.ApplicationStatus.StatusID = ($scope.companyPermissions.Application.PermittedActions['Review Required'] && $scope.CompanyPreferences.FundingManagerID) ? 56 : 37;
}
})
$scope.closePopup = function () {
ngDialog.close();
}
$scope.editFinanceAmountPopup = function () {
$scope.validateData = true;
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-EditFinanceAmount.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope,
});
}
$scope.checkAppCommission = function () {
if ($scope.LoanData.CommissionPoints > $scope.ApplicationDetails.CommissionPoints) {
$scope.errorCommissionPoint = "Commission Points Should be less than applied commission point.";
$scope.BlockSaveButton = true;
}
else {
$scope.BlockSaveButton = false;
$scope.errorCommissionPoint = null;
}
}
$scope.showSSNDetails = function () {
if (!$scope.checked) {
$scope.showMessage = FALSE;
$scope.forAppDetails = true;
$scope.PrimaryOwner = {
SocialSecurityNumber: null
}
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-AddSSN.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope,
showClose: FALSE
});
}
}
$scope.showMessage = FALSE;
$scope.addSSN = function () {
$scope.showMessage = TRUE;
if (checkstatus('addEditCommissionCapfrm', $scope)) {
$scope.loading = true;
var reqData = {
"EditApplication":
{
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"ModuleName": "SSN",
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"TargetID": $scope.ApplicationDetails.UserID,
"SocialSecurityNumber": $scope.PrimaryOwner.SocialSecurityNumber
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.GetApplicationDetails(function () {
$scope.blockPaymentEditing = true;
});
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.loading = false;
$scope.showMessage = TRUE;
});
} else {
$scope.showFlashMessage('error', 'Please correct the marked data errors.')
}
}
$scope.editCommissionPoint = function () {
if (checkstatus('editCommissionPointfrm', $scope)) {
$scope.loading = true;
var reqData = {
"EditCommissionPoint":
{
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProgramID": $scope.currentSelectedOffer.Metadata.ProgramID,
"CommissionPoint": $scope.currentSelectedOffer.Metadata.CommissionPoints
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.GetApplicationDetails(function () {
$scope.blockPaymentEditing = true;
});
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.loading = false;
$scope.showMessage = TRUE;
});
} else {
$scope.showFlashMessage('error', 'Please correct the marked data errors.')
}
}
$scope.shareAppWithDeal = function () {
appInfo.getServerData({
"ShareApplicationToDeal": {
"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $scope.SignIn.LoginSessionKey
}
}).then(function (response) {
var msgType = "error";
if (response.ResponseCode == 200) {
$scope.GetApplicationDetails();
msgType = "success";
}
$scope.showFlashMessage(msgType, response.Message);
});
}
}])
// Application Notes Controller
.controller('NotesController', ['$rootScope', '$scope', '$timeout', 'appInfo', '$state', 'ngDialog', 'Storage', '$location', function ($rootScope, $scope, $timeout, appInfo, $state, ngDialog, Storage, $location) {
$scope.ModuleEntityID = null;
$scope.ModuleName = $scope.noteTab;
var getFirstNote = function () {
switch ($scope.ModuleName) {
case 'Application':
$scope.ModuleEntityID = typeof $scope.ApplicationDetails == 'object'?$scope.ApplicationDetails.ApplicationNumber:null;
break;
case 'Deal':
$scope.ModuleEntityID = $scope.deal.DealDetail.DealID;
break;
case 'DealPool':
$scope.ModuleEntityID = $scope.dealPool.DealPoolID;
break;
}
if ($scope.ModuleEntityID)
$scope.getNotes();
else
$timeout(getFirstNote, 800);
}
$timeout(getFirstNote, 800);
$scope.OpenNotePopup = function (NotePopupFlag) {
$scope.isDealNote = ($scope.noteTab != 'Application');
$scope.Note = {};
$scope.IsDeleted = true;
$scope.Note = angular.copy(this.Note);
// console.log($scope.Note);return;
if (NotePopupFlag == 'addNote') {
$scope.Note = { Title: "", Attachments: [], NotePrivacy: { 'OnlyMe': true } };
}
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-editNote.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope,
preCloseCallback: function (value) {
if ($scope.uploading) {
$scope.showFlashMessage('error', 'Unable to close.Upload under progress.')
return FALSE;
}
return TRUE;
}
});
}
$scope.addNote = function () {
if (checkstatus('addDocfrm')) {
var reqData = {
"SaveNote": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ModuleEntityID": $scope.ModuleEntityID,
"Remarks": this.Note.Remarks,
"Title": this.Note.Title,
"NoteID": this.Note.NoteID,
"NotePrivacy": this.Note.NotePrivacy,
"ModuleName": $scope.ModuleName,
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$timeout(function () {
ngDialog.close();
}, 600);
$scope.getNotes();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.cancelNotePopup = function () {
ngDialog.close();
}
$scope.checkPrivacy = function (value) {
if (value == 'OnlyMe') {
$scope.Note.NotePrivacy = { 'OnlyMe': true };
}
else {
$scope.Note.NotePrivacy = { 'MeAndOthers': true }
}
}
$scope.renameAttachment = function () {
if (this.Attachment.edit) {
var Attachment = this.Attachment;
if (Attachment.OldDocName != Attachment.ImageName) {
var reqData = {
"RenameMedia": {
"Module": "NoteAttachments",
"NoteID": this.Note.NoteID,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"DocumentName": Attachment.ImageName,
"MediaID": Attachment.MediaID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
Attachment.edit = FALSE;
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
Attachment.ImageName += '.' + Attachment.ImageExt;
}
} else {
var a = this.Attachment.ImageName.split(".");
if (_.isUndefined(this.Attachment.ImageExt) && (!a.length === 1 || !(a[0] === "" && a.length === 2))) {
this.Attachment.ImageExt = a.pop();
this.Attachment.OldDocName = this.Attachment.ImageName;
this.Attachment.ImageName = this.Attachment.ImageName.replace('.' + this.Attachment.ImageExt, '');
}
else {
this.Attachment.OldDocName = this.Attachment.ImageName;
this.Attachment.ImageName = this.Attachment.ImageName.replace('.' + this.Attachment.ImageExt, '');
}
this.Attachment.edit = TRUE;
}
}
$scope.getNotes = function () {
var reqData = {
"ListNotes": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ModuleEntityID": $scope.ModuleEntityID,
"ModuleName": $scope.ModuleName,
"PageNo": $scope.notes.noteCurrentPage,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"Sort": null
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.Notes = response.Data.Notes;
pagingData = [];
$scope.notes.noteCurrentPage = pagingData.currentPage = parseInt(response.Data.Paginator.current_page);
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.notes.totalNotes = response.Data.Paginator.total_notes
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.deleteNote = function () {
$scope.Note = this.Note;
$scope.ngConfirm('Are you sure you want to delete this note ?', function () {
var reqData = {
"DeleteNote": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ModuleEntityID": $scope.ModuleEntityID,
"ModuleName": $scope.ModuleName,
"NoteID": $scope.Note.NoteID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.getNotes();
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
});
}
$scope.showRemarks = function () {
$scope.currentNoteData = this.Note;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-Show-Remarks.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
}
$scope.validateNoteAttachments = function (e) {
if ($scope.uploading) {
$scope.showFlashMessage('error', "Please wait,Another upload in progress.");
return false;
}
var totalSize = 0;
for (var i = 0; i < e.target.files.length; i++) {
totalSize += e.target.files[i].size;
}
if (totalSize > 20971520) {
$scope.showFlashMessage('error', "Maximum permitted upload size is 20 MB");
return false;
}
return true;
}
$scope.uploadNoteAttachments = function (e) {
if (e.target.files && e.target.files.length) {
for (var i = 0; i < e.target.files.length; i++) {
var reqData = {
"UploadFile": {
"ModuleName": 'NoteAttachments',
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"File": e.target.files[i],
//"ApplicationNumber": $scope.ApplicationDetails.ApplicationNumber,
"ModuleEntityID": $scope.ModuleEntityID,
"NoteModule": $scope.ModuleName,
"NoteID": this.Note.NoteID,
"NoteTitle": this.Note.Title,
}
};
$scope.Note.Attachments.push({ ImageName: e.target.files[i].name });
$scope.attachmentsUploadProgress = '0%';
appInfo.uploadFile(reqData).then(function (response) {
var msgType = 'error';
if (response.ResponseCode == 200) {
if (!$scope.Note.NoteID)
$scope.getNotes();
$scope.Note.NoteID = response.Data.NoteID;
$scope.Note.Attachments[0] = response.Data.Media;
msgType = 'success';
} else {
$scope.Note.Attachments = [];
$scope.showFlashMessage(msgType, response.Message);
}
// $scope.showFlashMessage(msgType,response.Message);
}, function () {
$scope.attachmentsUploadProgress = '100%';
$scope.showFlashMessage("error", "Upload Failed. Please try again later.");
$scope.Note.Attachments = [];
}, function (progress) {
$scope.attachmentsUploadProgress = progress;
});
}
}
}
$scope.listNoteoteDownload = function () {
$scope.TotalAttachment = this.Note.TotalAttachment;
var reqData = {
"ListNoteAttachments": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"NoteID": this.Note.NoteID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.Attachments = response.Data.Media;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-downloadNote.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.closePopup = function () {
ngDialog.close();
}
$scope.downloadAttachment = function () {
$scope.closePopup();
}
$scope.deleteAttachment = function () {
$scope.Note = this.Note;
var index = this.$index;
var reqData = {
"DeleteNoteAttachment": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"NoteID": $scope.Note.NoteID,
"MediaID": $scope.Note.Attachments[0].MediaID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.IsDeleted = false;
$scope.showFlashMessage('success', response.Message);
if ($scope.Note.Attachments.length > 0) {
$scope.Note.Attachments.splice(index, 1);
}
$scope.getNotes();
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
//$scope.getNotes();
}])
// Partial Application Details Controller
.controller('partialAppCtrl', ['$rootScope', '$scope', 'appInfo', '$location', '$stateParams', 'ngDialog', 'Storage', function ($rootScope, $scope, appInfo, $location, $stateParams, ngDialog, Storage) {
$scope.firstLoad = true;
if (!angular.equals({}, $stateParams) && $stateParams.partialAppUID) {
// User is coming from email link to view partial application
$scope.fetchPartialAppData = function () {
if ($scope.SignIn && $scope.SignIn.UserDetails.UserTypeID != 4) {
return $location.path('/view-partial/' + $stateParams.partialAppUID);
}
var reqData = {
"GetPartialAppData": {
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"PartialAppUID": $stateParams.partialAppUID
}
};
if ($rootScope.SignIn)
reqData.GetPartialAppData.LoginSessionKey = $rootScope.SignIn.LoginSessionKey;
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
Storage.setItem('PartialApplications', response.Data);
if (_.isNull(response.Data.ThirdParty)) {
$location.path('/custom-quote/').replace();
} else {
$location.path('/borrower-view-rate').replace();
}
} else {
if (response.ResponseCode == 526)
$scope.Page.Referer = $location.path();
//when application completed it will redirected to completed application
if (response.ResponseCode == 534) {
$location.path('/app-details/view/' + response.Data.ApplicationNumber);
} else {
$scope.showFlashMessage('error', response.Message);
$location.path('/');
}
}
});
}
if ($rootScope.CompanyPreferences)
$scope.fetchPartialAppData();
else
$rootScope.$on('company-loaded', $scope.fetchPartialAppData);
return;
}
$scope.SortByPartials = [
// {key:'Principal', sortByPartial:'Principal Amount'},
{ key: 'Created', sortByPartial: 'Created Date' },
{ key: 'FilledBy', sortByPartial: 'Filled By' },
{ key: 'FormsFilled', sortByPartial: 'Forms Filled' }
];
$scope.removePartialAppData = function (PartialAppUID) {
var reqData = {
"RemovePartialAppData": {
"PartialAppUID": PartialAppUID,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.PartialApplications = response.Data;
$scope.refreshPartialApplicationsList();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
ngDialog.close();
}
// get sales person name
$scope.getSalesPersonName = function (SalesPersonID) {
var sp = _.findWhere($rootScope.salesPersons, { ID: SalesPersonID });
return sp ? sp.Name : null;
}
$scope.confirmDelete = function (PartialAppUID) {
$scope.PartialAppUID = PartialAppUID;
$rootScope.ngConfirm('Are you sure you want to delete this application ?', function () {
$scope.removePartialAppData(PartialAppUID);
});
}
$scope.closePopup = function () {
ngDialog.close();
}
$scope.assignPartlAppPopup = function () {
$scope.selectedApplication = this.PartialApplications;
if (this.PartialApplications.AssigneeID) {
$scope.salesPersonName = _.findWhere($rootScope.salesPersons, { ID: this.PartialApplications.AssigneeID });
} else
$scope.salesPersonName = {};
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-assignPartlAppPopUp.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
}
$scope.assignPartialApplication = function () {
var reqData = {
"AssignApplications": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Assignments": [
{
"FinanceRequestID": $scope.selectedApplication.PartialAppID,
"AssigneeID": this.salesPersonName.ID,
"OldAssigneeID": $scope.selectedApplication.AssigneeID
}
],
"ApplicationsType": "Partial"
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.assignPartialAppData = response.Data;
$scope.showFlashMessage('success', response.Message);
$scope.refreshPartialApplicationsList();
ngDialog.close();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
// Notify section
$scope.notifyPendingApplicationPopUp = function () {
$scope.PartialApplications = this.PartialApplications;
$rootScope.ngConfirm('Would you like to notify this user?', function () {
$scope.notifyPendingApplication();
});
}
$scope.notifyPendingApplication = function () {
var reqData = {
"NotifyPendingApplication": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PartialAppUID": $scope.PartialApplications.PartialAppUID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.NotifyPendingApplication = response.Data;
$scope.showFlashMessage('success', response.Message);
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.resetFiltersForPartialApp = function () {
$scope.partialAppListFilter = { StartDate: null, EndDate: null, appStatus: { StatusName: null }, currentPage: 1, ProposalLeadID: null, PartialAppSearch: null };
$scope.partialAppListSorting = { appSort: null };
$scope.ProposalGUID = null;
$scope.totalPartialApplications = 0;
$scope.refreshPartialApplicationsList();
}
$scope.resetBorrowerFilters = function () {
$scope.ProposalGUID = $scope.partialAppListFilter.ProposalLeadID = $scope.partialAppListFilter.Email = null;
$scope.saveAppState(null);
$scope.refreshPartialApplicationsList();
if (_.isFunction($scope.$parent.resetBorrowerFilters))
$scope.$parent.resetBorrowerFilters();
}
$scope.refreshPartialApplicationsList = function () {
$scope.Page.trackLoading('partialApp-list');
var reqData = {
"GetPartialApplicationsList": {
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.partialAppListFilter.currentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"Filter": {
"CompanyApplicationsFilter_StartDate": $scope.partialAppListFilter.StartDate,
"CompanyApplicationsFilter_EndDate": $scope.partialAppListFilter.EndDate,
"CompanyApplicationsFilter_Search": $scope.partialAppListFilter.PartialAppSearch,
"ProposalLeadID": $scope.partialAppListFilter.ProposalLeadID
},
"SortBy": $scope.partialAppListSorting.appSort
}
};
if ($scope.partialAppListFilter.StartDate && $scope.partialAppListFilter.EndDate) {
reqData.GetPartialApplicationsList.Filter = {
CompanyApplicationsFilter_StartDate: $scope.partialAppListFilter.StartDate,
CompanyApplicationsFilter_EndDate: $scope.partialAppListFilter.EndDate
};
}
if ($scope.partialAppListFilter.PartialAppSearch) {
reqData.GetPartialApplicationsList.Filter.CompanyApplicationsFilter_PartialAppSearch = $scope.partialAppListFilter.PartialAppSearch;
}
if (!$scope.firstLoad)
$scope.saveAppState(null);
$scope.PartialApplicationsList = false;
reqData.GetPartialApplicationsList.SortBy = $scope.partialAppListSorting.appSort;
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('partialApp-list');
$scope.PartialApplicationsList = FALSE;
if (response.ResponseCode == 200) {
if (response.Data.PartialApplications) {
$scope.PartialApplicationsList = response.Data.PartialApplications;
var pagingData = [];
$scope.partialAppListFilter.currentPage = pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPartialApplications = response.Data.Paginator.total_applications;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
}, function () {
$scope.Page.untrackLoading('partialApp-list');
});
}
$scope.initFilters = function () {
appInfo.getSalesPersons(function () {
var PartialAppList = Storage.getItem('PartialAppList');
if (PartialAppList) {
$scope.partialAppListFilter = {
StartDate: PartialAppList.Filter.StartDate,
EndDate: PartialAppList.Filter.EndDate,
PartialAppSearch: PartialAppList.Filter.PartialAppSearch,
appStatus: null,
currentPage: PartialAppList.Filter.currentPage,
ProposalLeadID: PartialAppList.Filter.ProposalLeadID,
Email: PartialAppList.Filter.Email
};
$scope.partialAppListSorting = { appSort: {} };
if (PartialAppList.SortBy) {
$scope.partialAppListSorting.appSort = _.findWhere($scope.SortByPartials, { key: PartialAppList.SortBy.key });
// for(var i in $scope.SortByPartials){
// if(angular.equals($scope.SortByPartials[i],PartialAppList.SortBy)){
// $scope.partialAppListSorting.appSort=$scope.SortByPartials[i];
// break;
// }
// }
}
$scope.ProposalName = PartialAppList.ProposalName;
$scope.ProposalGUID = PartialAppList.ProposalGUID;
$scope.refreshPartialApplicationsList();
}
else
$scope.resetFiltersForPartialApp();
$scope.firstLoad = false;
});
};
$scope.$watch('partialAppListFilter.StartDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.partialAppListFilter.EndDate) {
var StartDate = new Date(newValue);
var EndDate = new Date($scope.partialAppListFilter.EndDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.partialAppListFilter.StartDate = null;
}
}
});
$scope.$watch('partialAppListFilter.EndDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.partialAppListFilter.StartDate) {
var EndDate = new Date(newValue);
var StartDate = new Date($scope.partialAppListFilter.StartDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.partialAppListFilter.EndDate = null;
}
}
});
$scope.navigateToDetails = function () {
if ($rootScope.SignIn.UserDetails.UserTypeID == '4') {
$location.path('/applications/viewpartial/' + this.PartialApplications.PartialAppUID);
} else {
$location.path('/view-partial/' + this.PartialApplications.PartialAppUID);
}
}
$scope.saveAppState = function () {
var PartialAppList = {
"Filter": $scope.partialAppListFilter,
"currentPage": $scope.currentPage,
"SortBy": $scope.partialAppListSorting.appSort
};
Storage.setItem('PartialAppList', PartialAppList);
}
appInfo.getStatusList(function () {
$scope.initFilters();
$scope.Page.Title = 'Application - ' + $rootScope.CompanyPreferences.CompanyName;
});
}])
// Partial Application Details Controller
.controller('proposalDashboardAppCtrl', ['$rootScope', '$scope', 'appInfo', '$location', '$stateParams', 'ngDialog', 'Storage', '$sce', '$q', function ($rootScope, $scope, appInfo, $location, $stateParams, ngDialog, Storage, $sce, $q) {
$scope.proposalListFilter = { currentPage: 1, Association: null };
$scope.ProposalLeads = null;
$scope.autocomplete_options = {
suggest: function (keyword) {
var deferred = $q.defer();
$scope.proposalListFilter.AssociationID = null;
var highlight = function (str, term) {
var highlight_regex = new RegExp('(' + term + ')', 'gi');
return str.replace(highlight_regex,
'$1');
};
appInfo.getAssociationList(function () {
var associations = [];
for (var i = 0; i < $scope.AssociationData.length; i++) {
associations[i] = {
value: $scope.AssociationData[i].AssociationName,
obj: $scope.AssociationData[i],
label: $sce.trustAsHtml(highlight($scope.AssociationData[i].AssociationName, keyword))
};
}
deferred.resolve(associations);
}, {
"Title": keyword
});
return deferred.promise;
},
on_select: function (selected) {
$scope.proposalListFilter.AssociationID = selected.obj.CompanyID;
}
};
$scope.navigateProposal = function () {
$location.path('/create-proposal/' + this.Proposal.ProposalGUID);
}
$scope.filterByAssociate = function (associate) {
$scope.proposalListFilter.Association = associate;
$scope.GetProposalsList();
};
$scope.editProposals = function () {
$scope.Proposal = this.Proposal;
var reqData = {
"GetProposalData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProposalID": $scope.Proposal.ProposalID,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.ProposalData = response.Data;
// Storage.setItem('Proposal',$scope.ProposalData);
// $state.go('create-proposal.proposal-create-tab');
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.resetFilters = function () {
$scope.proposalListFilter = { Name: null, currentPage: 1, AssociationID: null };
$scope.GetProposalsList();
}
$scope.GetProposalsList = function () {
$scope.Page.trackLoading('proposal-list');
var reqData = {
"GetProposalsList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.proposalListFilter.currentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF
}
}
if ($scope.proposalListFilter) {
reqData.GetProposalsList.Filter = {
"StartDate": $scope.proposalListFilter.StartDate,
"EndDate": $scope.proposalListFilter.EndDate,
"Name": $scope.proposalListFilter.Name,
"currentPage": $scope.proposalListFilter.currentPage,
"AssociationID": $scope.proposalListFilter.AssociationID,
};
}
$scope.Proposals = null;
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('proposal-list');
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.Proposals = response.Data.Proposals;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalProposals = response.Data.Paginator.total_proposals
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
};
$scope.$watch('proposalListFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue) {
$scope.proposalListFilter.currentPage = 1;
$scope.GetProposalsList();
}
}, 700));
$scope.$watch('proposalListFilter.StartDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.proposalListFilter.EndDate) {
var StartDate = new Date(newValue);
var EndDate = new Date($scope.proposalListFilter.EndDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.proposalListFilter.StartDate = null;
}
}
});
$scope.$watch('proposalListFilter.EndDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.proposalListFilter.StartDate) {
var EndDate = new Date(newValue);
var StartDate = new Date($scope.proposalListFilter.StartDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.proposalListFilter.EndDate = null;
}
}
});
$scope.navigateProposalLead = function () {
$location.path('/proposal-status/' + this.Proposal.ProposalGUID);
}
$scope.getProposalStatus = function () {
var reqData = {
"GetProposalStatus": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.ProposalDashBoardData = response.Data;
}
else {
$scope.showFlashMessage('error', response.Message);
}
}
});
$scope.GetProposalsList();
$scope.Page.Title = 'Proposals - ' + $rootScope.CompanyPreferences.CompanyName;
}
if ($rootScope.CompanyPreferences)
$scope.getProposalStatus();
else
$rootScope.$on('company-loaded', $scope.getProposalStatus);
}])
// Partial Application Details Controller
.controller('proposalLeadAppCtrl', ['$rootScope', '$scope', 'appInfo', '$location', '$stateParams', 'ngDialog', 'Storage', function ($rootScope, $scope, appInfo, $location, $stateParams, ngDialog, Storage) {
$scope.Page.Title = 'Proposals - ' + $rootScope.CompanyPreferences.CompanyName;
$scope.currentPage = 1;
$scope.getProposalLeadsList = function () {
var reqData = {
"GetProposalLeadsList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProposalGUID": $stateParams.ProposalGUID,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.ProposalGUID = $stateParams.ProposalGUID;
pagingData = [];
$scope.ProposalLeads = response.Data.proposalLeads;
$scope.ProposalDetails = response.Data.proposals;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalProposals = response.Data.Paginator.total_users
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
else {
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
if ($rootScope.CompanyPreferences)
$scope.getProposalLeadsList();
else
$rootScope.$on('company-loaded', $scope.getProposalLeadsList);
$scope.navigateToApplications = function () {
var appList = {
"ApplicationNumber": null,
"Filter": {
Name: null, StartDate: null, EndDate: null,
appStatus: { StatusName: null }, BorrowerID: null, ProposalLeadID: this.ProposalLead.ProposalLeadID, Email: this.ProposalLead.Email
},
"currentPage": 1,
"ProposalGUID": this.ProposalGUID,
"SortBy": null,
"ProposalName": $scope.ProposalDetails.Title
};
Storage.setItem('appList', appList);
$location.path('/applications');
}
$scope.navigateToPartialApplications = function () {
var partialAppList = {
"Filter": { StartDate: null, EndDate: null, ProposalLeadID: this.ProposalLead.ProposalLeadID, Email: this.ProposalLead.Email, currentPage: 1 },
"ProposalGUID": this.ProposalGUID,
"ProposalName": $scope.ProposalDetails.Title
};
Storage.setItem('PartialAppList', partialAppList);
$location.path('/partial-application');
}
}])
// Create Proposal Controller
.controller('createProposalAppCtrl', ['$rootScope', '$state', '$scope', 'appInfo', '$location', '$stateParams', 'ngDialog', 'Storage', 'ngNotify', '$sce', '$q', function ($rootScope, $state, $scope, appInfo, $location, $stateParams, ngDialog, Storage, ngNotify, $sce, $q) {
$scope.contactData = { PrimaryContactEmail: "" };
$scope.MatchLead = true;
$scope.ProposalTemplates = { currentPage: 1, Filter: null };
$scope.ProposalTemplates.Filter = { Page: 1 }
$scope.ProposalTemplates.NotificationTemplateID = null;
$scope.ProposalTemplates.TemplateName = null;
$scope.ProposalTemplates.MailSubject = null;
$scope.ProposalTemplates.MailContent = null;
$scope.showingtextTemplate = '';
$scope.TemplatesListData = {};
$scope.templateData = {};
$scope.editorCaretPosition = 0;
$scope.keyUpAtEditor = function (e) {
// $scope.editorCaretPosition=getCaretPosition(e.target);
$scope.templateData.editor.summernote('saveRange');
}
//insert keywords into editor
$scope.insertText = function () {
$scope.templateData.editor.summernote('restoreRange');
$scope.templateData.editor.summernote('insertText', $scope.ProposalTemplates.Token);
$scope.ProposalTemplates.Token = '';
}
//insert keywords into editor
$scope.$watch('Proposal.Filter.Lead', _.debounce(function (newValue, oldValue) {
if (newValue && newValue != oldValue) {
$scope.current_page = 1;
$scope.matchedRecords = [];
appInfo.getMatchingContacts(newValue, $scope.current_page, $scope.referesLeads);
}
}, 700));
$scope.autocomplete_options = {
suggest: function (emails) {
var deferred = $q.defer();
var matchingEmails = [];
var ix = emails.lastIndexOf(';'),
lhs = emails.substring(0, ix + 1),
keyword = $.trim(emails.substring(ix + 1));
appInfo.getServerData({
"GetCompanysUsersList": {
"PageNo": 1,
"CompanyID": $scope.CompanyPreferences.CompanyID,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Filter": {
"CompanyusersFilter_Email": keyword
}
}
}).then(function (response) {
var users = response.Data.CompanyUsers;
if (!users) {
deferred.resolve(matchingEmails);
return;
}
for (var i = 0; i < users.length; i++) {
matchingEmails[i] = {
value: lhs + users[i].Email,
obj: users[i],
label: $sce.trustAsHtml(highlight(users[i].Email, keyword))
};;
}
deferred.resolve(matchingEmails);
});
var highlight = function (str, term) {
var highlight_regex = new RegExp('(' + term + ')', 'gi');
return str.replace(highlight_regex,
'$1');
};
return deferred.promise;
},
on_select: function (selected) {
}
};
$scope.referesLeads = function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
if (!$scope.MatchLead) {
$scope.MatchLead = true;
}
$scope.matchedRecords = response.Data.Contacts;
$scope.PaginatorData = response.Data.Paginator;
$scope.totalContacts = response.Data.Paginator.total_users;
pagingData = [];
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalRecord = $scope.totalApplications = response.Data.Paginator.total_users;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
for (var i in $scope.Proposal.Leads) {
for (var j in $scope.matchedRecords) {
if ($scope.Proposal.Leads[i].ID == $scope.matchedRecords[j].ID && $scope.Proposal.Leads[i].Type == $scope.matchedRecords[j].Type) {
$scope.matchedRecords[j].chkContact = true;
break;
}
}
}
}
else {
$scope.matchedRecords = null;
}
} else {
$scope.matchedRecords = null;
//$scope.showFlashMessage('error',response.Message);
}
};
$scope.submitProposal = function () {
if (checkstatus('proposalContact')) {
if ($scope.CompanyPreferences.Category == "Company" || $scope.Proposal.ProgramFrom == 'self') {
$scope.setProposal(true);
} else {
$scope.checkProgramAssociation();
}
} else {
focusOnErrorItem();
}
}
$scope.AddContactPopUp = _.debounce(function (e) {
if (e.target.type == "button" || (e.charCode == 13 && $scope.Proposal.Filter.Lead && $scope.Proposal.Filter.Lead.length && isValidEmail('#searchLead'))) {
$scope.salesMode = true;
$scope.contactData = { FaxNo: null, SecondaryContactEmail: null, PrimaryContactNo: null, SecondaryContactNo: null, LastName: null, FirstName: null };
// console.log($scope.contactData);
$scope.contactData.PrimaryContactEmail = $scope.Proposal.Filter.Lead;
$scope.Proposal.Filter.Lead = '';
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-dlgAddContact.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope
});
}
$scope.MatchLead = true
}, 100);
$scope.setSelectedLead = function () {
var selectedLead = this.record;
// console.log(selectedLead);
if (selectedLead.chkContact) {
$scope.Proposal.Leads.push(selectedLead);
}
else {
// console.log($scope.Proposal.Leads);
for (var i in $scope.Proposal.Leads) {
// console.log($scope.Proposal.Leads[i].ID,'==',selectedLead.ID);
// if ($scope.Proposal.Leads[i].ID==selectedLead.ID && $scope.Proposal.Leads[i].MailType==selectedLead.MailType)
if ($scope.Proposal.Leads[i].ID == selectedLead.ID) {
$scope.Proposal.Leads.splice(i, 1);
// console.log($scope.Proposal.Leads);
if (typeof $scope.Proposal.Leads[i] != 'undefined') {
$scope.RemoveLeads.push($scope.Proposal.Leads[i]);
}
}
}
}
}
$scope.saveContact = function () {
var contactData = $scope.contactData;
contactData.ProposalGUID = $scope.Proposal.ProposalGUID;
if (checkstatus('frmAddContact', $scope) && contactData) {
appInfo.saveContact(contactData, function (response) {
if (response.ResponseCode == 200 && response.Data) {
ngDialog.close();
$scope.Proposal.Filter.Lead = $scope.contactData.PrimaryContactEmail;
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.$watch('Proposal.Filter.FinanceCredit', function (newValue, oldValue) {
if (newValue && newValue != oldValue) {
$scope.getProposalProgramsList();
}
});
$scope.$watch('Proposal.Filter.Association', function (newValue, oldValue) {
if (newValue || newValue != oldValue) {
$scope.getProposalProgramsList();
}
});
$scope.$watch('Proposal.Filter.FinanceTimeInBusiness', function (newValue, oldValue) {
if (newValue && newValue != oldValue) {
$scope.getProposalProgramsList();
}
});
$scope.$watch('Proposal.Filter.CodeTitle', function (newValue, oldValue) {
if (newValue != oldValue) {
$scope.getProposalProgramsList();
}
});
$scope.$watch('Proposal.QuotedAmount', _.debounce(function (newValue, oldValue) {
if (newValue) {
// newValue=newValue.replace(',','');
// oldValue=oldValue.replace(',','');
// oldValue=oldValue;
if (newValue && newValue != oldValue) {
$scope.Proposal.SelectedProgram = null;
$scope.getProposalProgramsList();
}
}
}, 600));
$scope.$watch('Proposal.Filter.IndustryTypes', function (newValue, oldValue) {
if (newValue && newValue != oldValue) {
$scope.getProposalProgramsList();
}
});
$scope.getProposalProgramsList = function () {
if (checkstatus('proposal-1', $scope)) {
var reqData = {
"GetProposalProgram": {
"PageNo": $scope.Proposal.Filter.ProgramsPage,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
}
};
if ($scope.Proposal.Filter) {
with ($scope.Proposal.Filter) {
reqData.GetProposalProgram.Filter = {
ProposalFilter_AssociationID: (Association) ? Association.CompanyID : null,
ProposalFilter_ProgramFrom: ($scope.Proposal.ProgramFrom) ? $scope.Proposal.ProgramFrom : null,
ProposalFilter_FinanceCredit: (FinanceCredit.CreditScoreID) ? FinanceCredit.CreditScoreID : null,
ProposalFilter_FinanceTimeInBusiness: (FinanceTimeInBusiness.TimeInBusinessID) ? FinanceTimeInBusiness.TimeInBusinessID : null,
ProposalFilter_Name: (CodeTitle) ? CodeTitle : null,
}
}
reqData.GetProposalProgram.Filter.ProposalFilter_FinanceAmount = ($scope.Proposal.QuotedAmount) ? parseInt($scope.Proposal.QuotedAmount) : 0;
reqData.GetProposalProgram.Filter.ProposalFilter_IndustryTypes = [];
for (var i in $scope.Proposal.Filter.IndustryTypes) {
reqData.GetProposalProgram.Filter.ProposalFilter_IndustryTypes.push($scope.Proposal.Filter.IndustryTypes[i].IndustryTypeID);
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.ProgramList = response.Data.Programs;
pagingData = [];
$scope.totalPrograms = response.Data.Paginator.total_programs;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalProposals = response.Data.Paginator.total_programs
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
for (var j in $scope.ProgramList) {
$scope.ProgramList[j].Industries = [];
for (var k in $rootScope.industryData) {
for (var l in $scope.ProgramList[j].IndustryTypes) {
if ($scope.ProgramList[j].IndustryTypes[l] == $rootScope.industryData[k].IndustryTypeID) {
$scope.ProgramList[j].Industries.push($rootScope.industryData[k].Name);
}
}
}
if ($scope.Proposal.SelectedProgram && $scope.Proposal.SelectedProgram.ProgramID === $scope.ProgramList[j].ProgramID) {
$scope.Proposal.SelectedProgram = $scope.ProgramList[j];
}
}
}
else {
$scope.ProgramList = null;
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
var setTimeInBusiness = function (response) {
$scope.SelectedProgramTimeInBusiness = response.Data.Timeinbusiness;
Storage.setItem('Proposal', $scope.Proposal);
$scope.disableSupport = { DisabledCreditScores: [], DisabledTimeInBusiness: [] };
$scope.Proposal.DisabledTimeInBusiness = [];
for (var i in $scope.TimeInBusiness) {
if (_.isUndefined($scope.TimeInBusiness[i].CreditScoreSelection)) {
$scope.TimeInBusiness[i].CreditScoreSelection = [];
}
for (k = 1; k <= 5; k++) {
$scope.TimeInBusiness[i].CreditScoreSelection[k] = ($scope.TimeInBusiness[i].DisabledCreditScores.indexOf(k) == -1);
}
}
}
$scope.setProposal = function (BeginDelievery) {
if (checkstatus('proposal-1', $scope) && $scope.Proposal.SelectedProgram) {
// Storage.setItem('Proposal',unescape(encodeURIComponent($scope.Proposal)));
Storage.setItem('Proposal', $scope.Proposal);
var reqData = {
"SetProposal": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProposalGUID": $scope.Proposal.ProposalGUID,
"Title": ($scope.Proposal.Title) ? $scope.Proposal.Title : null,
"Message": ($scope.Proposal.Message) ? $scope.Proposal.Message : null,
"MailSubject": $scope.Proposal.mailSubject,
"QuotedAmount": $scope.Proposal.QuotedAmount/*.replace(',','')*/,
"CommissionPoints": $scope.Proposal.Commission,
"ProgramID": $scope.Proposal.SelectedProgram.ProgramID,
"OfferedTerms": $scope.Proposal.SelectedProgram.Terms,
"BeginDelievery": BeginDelievery,
"CopySender": $scope.Proposal.copySender,
"BccEmails": $scope.Proposal.bccEmails,
"ccEmails": $scope.Proposal.ccEmails,
"AppWorkFlow": $scope.Proposal.AppWorkFlow,
"AppliedFilters": {
"CreditRating": $scope.Proposal.Filter.FinanceCredit.CreditScoreID,
"TimeInBusiness": $scope.Proposal.Filter.FinanceTimeInBusiness.TimeInBusinessID,
"BankID": ($scope.Proposal.Filter.Association) ? $scope.Proposal.Filter.Association.CompanyID : null,
"ProgramName": $scope.Proposal.Filter.CodeTitle,
"IndustryType": $scope.Proposal.Filter.IndustryTypes,
},
"SelectedTemplate": $scope.TemplatesListData.SelectedTemplate,
}
}
if ($scope.Proposal.DisabledTimeInBusiness) {
$scope.disableSupport = { DisabledCreditScores: [], DisabledTimeInBusiness: $scope.Proposal.DisabledTimeInBusiness };
for (var i in $scope.TimeInBusiness) {
$scope.disableSupport.DisabledCreditScores.push({ TimeInBusinessID: $scope.TimeInBusiness[i].TimeInBusinessID });
$scope.disableSupport.DisabledCreditScores[i].CreditScores = [];
for (var j in $scope.TimeInBusiness[i].CreditScoreSelection) {
if ($scope.TimeInBusiness[i].CreditScoreSelection[j] != true) {
$scope.disableSupport.DisabledCreditScores[i].CreditScores.push(parseInt(j));
}
}
}
reqData.SetProposal.AppliedFilters.disableSupport = $scope.disableSupport;
}
if ($rootScope.CompanyPreferences.Category == "Bank" && $scope.Proposal.ProgramFrom !== 'self') {
reqData.SetProposal.TargetVendorID = $scope.Proposal.Filter.Association.CompanyID;
if ($scope.CommissionData) {
reqData.SetProposal.CommissionPoints = $scope.CommissionData.PartnerSideCommissionCap;
}
}
if ($scope.Proposal.Attachments) {
reqData.SetProposal.Attachments = $scope.Proposal.Attachments;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (BeginDelievery) {
Storage.removeItem('Proposal');
Storage.removeItem('RemoveLeads');
$location.path('/proposal-dashboard');
} else {
$scope.Proposal.ProposalGUID = response.Data.ProposalGUID;
$scope.Proposal.EstimatedEMI = response.Data.EstimatedEMI;
$scope.Proposal.VendorProfit = response.Data.VendorProfit;
appInfo.getTimeInBusiness(setTimeInBusiness, { ProgramID: $scope.Proposal.SelectedProgram.ProgramID }, TRUE);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.updateDisabledTIB = function (event) {
var itemIndex = $scope.Proposal.DisabledTimeInBusiness.indexOf(this.TimeInBusinessGroup.TimeInBusinessID);
if (event.target.checked) {
if (itemIndex != -1)
$scope.Proposal.DisabledTimeInBusiness.splice(itemIndex, 1);
} else {
if ($scope.Proposal.DisabledTimeInBusiness.length == $scope.SelectedProgramTimeInBusiness.length - 1) {
$scope.showFlashMessage('error', 'At least one Time in business must be selected.');
event.preventDefault();
} else {
$scope.Proposal.DisabledTimeInBusiness.push(this.TimeInBusinessGroup.TimeInBusinessID);
}
}
}
$scope.setProposalLeads = function () {
if ($scope.Proposal.Leads.length > 0 && !$scope.UploadedData) {
var reqData = {
"SetProposalLeads": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProposalGUID": $scope.Proposal.ProposalGUID,
"AddLeads": $scope.Proposal.Leads,
"RemoveLeads": null
}
}
// var RemoveLeads=Storage.getItem('RemoveLeads');
if ($scope.RemoveLeads) {
reqData.SetProposalLeads.RemoveLeads = $scope.RemoveLeads;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
Storage.setItem('Proposal', $scope.Proposal);
// $scope.navigateWizard('Next')
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.navigateWizard = function (button) {
if (checkstatus('proposal-1', $scope)) {
switch ($location.$$url) {
case '/create-proposal/proposal-select-leads':
if (button == 'Next') {
if (!$scope.Proposal.Leads.length)
return $scope.showFlashMessage('error', 'Please select atleast one lead.');
$scope.setProposalLeads();
$location.path('/create-proposal/proposal-select-template');
} else
$location.path('/create-proposal/proposal-create-tab');
break;
case '/create-proposal/proposal-review-send':
// Only Previous Step
$location.path('/create-proposal/proposal-select-template');
break;
case '/create-proposal/proposal-select-template':
if (button == 'Next') {
if (!$scope.TemplatesListData.SelectedTemplate)
return $scope.showFlashMessage('error', 'Please select a Template.');
$scope.Proposal.mailSubject = $scope.TemplatesListData.SelectedTemplate.MailSubject;
if ($scope.TemplatesListData.SelectedTemplate.HasAdvancePaymentToken)
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-selectTerm.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope,
});
$location.path('/create-proposal/proposal-review-send');
} else {
$location.path('/create-proposal/proposal-select-leads');
}
break;
case '/create-proposal/proposal-create-tab':
if ($scope.Proposal.SelectedProgram) {
$scope.checkCommission(); $scope.setProposal(false);
$location.path('/create-proposal/proposal-select-leads');
} else {
$scope.showFlashMessage('error', 'Please select a program.');
}
break;
}
}
if ($location.$$url == '/create-proposal/proposal-review-send') {
if (button == 'Previous') {
$location.path('/create-proposal/proposal-select-template');
}
}
}
$scope.checkSelectedTerms = function () {
var sc = 0;
for (var i in $scope.Proposal.SelectedProgram.Terms) {
if ($scope.Proposal.SelectedProgram.Terms[i].Selected) {
sc++;
break;
}
}
if (!sc) {
$scope.showFlashMessage('error', "At least one term must be selected, to send the proposal with advance payment options.");
} else {
ngDialog.close();
}
}
$scope.checkProgramAssociation = function () {
if (!$scope.Proposal.SelectedProgram.PartnerSideCommissionCap) {
$scope.ngConfirm('Selected programs is not associated with selected Vendor are you sure you want to associate with it?', function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-AddCommissionCap.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
});
} else {
if ($scope.checkCommission()) {
$scope.setProposal(true);
$scope.navigateWizard('Next');
}
}
}
$scope.removeProposalLead = function () {
var LeadData = this.LeadData;
var reqData = {
"RemoveLead": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProposalGUID": $scope.Proposal.ProposalGUID,
"TargetID": LeadData.ID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
for (var i in $scope.Proposal.Leads) {
if ($scope.Proposal.Leads[i].ID == LeadData.ID) {
$scope.Proposal.Leads.splice(i, 1);
$scope.RemoveLeads.push(LeadData);
}
}
Storage.setItem('RemoveLeads', $scope.RemoveLeads);
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.getMatchingContacts = function () {
if ($scope.MatchLead) {
appInfo.getMatchingContacts($scope.contactData.PrimaryContactEmail, $scope.Proposal.Filter.MatchingLeadPage, $scope.referesLeads);
} else {
$scope.getSelectedRecords();
}
}
$scope.getSelectedRecords = function () {
if ($scope.Proposal.Leads.length) {
if ($scope.MatchLead) {
$scope.oldMatchingRecords = angular.copy($scope.matchedRecords);
$scope.MatchLead = false;
}
$scope.matchedRecords = [];
pagingData = [];
$scope.totalContacts = $scope.Proposal.Leads.length;
pagingData.totalPage = ($scope.totalContacts / 10) + (($scope.totalContacts % 10 > 0) + 1);
if (pagingData.totalPage === 0) {
pagingData.totalPage = 1;
}
pagingData.totalRecord = $scope.totalProposals = $scope.Proposal.Leads.length;
pagingData.numPerPage = 10;
pagingData.currentPage = ($scope.Proposal.Filter.SelectedLeadPage <= pagingData.totalPage) ? $scope.Proposal.Filter.SelectedLeadPage : 1;
for (var i = (pagingData.currentPage - 1) * pagingData.numPerPage; i < (pagingData.currentPage * pagingData.numPerPage) && i < pagingData.totalRecord; i++) {
$scope.matchedRecords.push($scope.Proposal.Leads[i]);
}
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
}
$scope.getMatchedRecords = function () {
if ($scope.oldMatchingRecords) {
if (!$scope.MatchLead)
$scope.MatchLead = true;
if ($scope.oldMatchingRecords && $scope.PaginatorData) {
$scope.matchedRecords = angular.copy($scope.oldMatchingRecords);
pagingData = [];
$scope.totalContacts = $scope.PaginatorData.total_users;
$scope.Proposal.Filter.MatchingLeadPage = pagingData.currentPage = $scope.PaginatorData.current_page;
pagingData.totalPage = $scope.PaginatorData.total_pages;
pagingData.totalRecord = $scope.totalProposals = $scope.PaginatorData.total_users;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
}
}
$scope.checkCommission = function () {
if ($scope.Proposal.SelectedProgram) {
if ($scope.Proposal.SelectedProgram.LockCommission) {
$scope.Proposal.Commission = $scope.Proposal.SelectedProgram.PartnerSideCommissionCap ? $scope.Proposal.SelectedProgram.PartnerSideCommissionCap : $scope.Proposal.SelectedProgram.VendorSideCommissionCap;
}
if ($scope.Proposal.SelectedProgram.VendorSideCommissionCap) {
if (parseInt($scope.Proposal.SelectedProgram.VendorSideCommissionCap) >= parseInt($scope.Proposal.Commission)) {
return true;
}
else {
// $scope.showFlashMessage("error","Commission must be less than or equal to Vendor Commission Cap.");
$scope.errorCommission = "Commission must be less than Vendor Commission Point.";
$scope.Proposal.Commission = $scope.Proposal.SelectedProgram.VendorSideCommissionCap;
return false;
}
}
else if ($scope.Proposal.SelectedProgram.PartnerSideCommissionCap) {
if (parseInt($scope.Proposal.SelectedProgram.PartnerSideCommissionCap) >= parseInt($scope.Proposal.Commission)) {
return true;
}
else {
// $scope.showFlashMessage("error","Commission must be less than or equal to Partner Commission Cap.");
$scope.errorCommission = "Commission must be less than Partner Commission Point.";
$scope.Proposal.Commission = $scope.Proposal.SelectedProgram.PartnerSideCommissionCap;
return false;
}
}
}
}
$scope.uploadLeads = function (e) {
if (e.target.files && e.target.files.length) {
var reqData = {
"UploadFile": {
"ModuleName": 'UploadLeads',
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"File": e.target.files[0],
"ProposalGUID": $scope.Proposal.ProposalGUID,
"VendorID": $scope.Proposal.Filter.Association.CompanyID
}
};
appInfo.uploadFile(reqData).then(function (response) {
var msgType = 'error';
if (response.ResponseCode == 200) {
$scope.UploadedData = response.Data.SalesLeads;
$scope.Proposal.Leads = $scope.UploadedData.SuccessfullyAddedEmail.Data;
$scope.switchLeadTab(3);
msgType = 'success';
}
$scope.showFlashMessage(msgType, response.Message);
}, function () {
$scope.uploadProgress = '100%';
$scope.showFlashMessage("error", "Upload Failed. Please try again later.");
}, function (progress) {
$scope.uploadProgress = progress;
});
}
}
$scope.switchLeadTab = function (Flag) {
if (Flag == 2) {
$scope.SwitchTab = 2;
if (!_.isUndefined($scope.UploadedData.DescardedMails)) {
$scope.SalesLeads = $scope.UploadedData.DescardedMails.Data;
if ($scope.UploadedData.DescardedMails.length > 0) {
pagingData = [];
pagingData.currentPage = $scope.UploadedData.DescardedMails.Paginator.current_page;
pagingData.totalPage = $scope.UploadedData.DescardedMails.Paginator.total_pages;
pagingData.totalRecord = $scope.totalLeads = $scope.UploadedData.DescardedMails.Paginator.total_leads;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
}
else {
$scope.UploadedData = {};
}
}
else {
$scope.SwitchTab = 3;
if (!_.isUndefined($scope.UploadedData.SuccessfullyAddedEmail)) {
$scope.SalesLeads = $scope.UploadedData.SuccessfullyAddedEmail.Data;
pagingData = [];
pagingData.currentPage = $scope.UploadedData.SuccessfullyAddedEmail.Paginator.current_page;
pagingData.totalPage = $scope.UploadedData.SuccessfullyAddedEmail.Paginator.total_pages;
pagingData.totalRecord = $scope.totalLeads = $scope.UploadedData.SuccessfullyAddedEmail.Paginator.total_leads;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
else {
$scope.UploadedData = {};
}
}
$scope.getLeads();
}
$scope.getLeads = function () {
var reqData = {
"GetImportedLeads": {
"ProposalGUID": $scope.Proposal.ProposalGUID,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": this.LeadPage
}
}
if ($scope.SwitchTab == 2) {
reqData.GetImportedLeads.TabName = "Discarded";
}
else {
reqData.GetImportedLeads.TabName = "AddedLeadPage";
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.SalesLeads = response.Data.Leads;
pagingData = [];
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalLeads = response.Data.Paginator.total_leads;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.GrantRevokeProgram = function (PartnerSideCommissionCap) {
$scope.CommissionData = this.CommissionData;
var Vendors = [];
Vendors.push({
"VendorID": $scope.Proposal.Filter.Association.CompanyID,
"PartnerSideCommissionCap": $scope.CommissionData.PartnerSideCommissionCap
});
if (checkstatus('addEditCommissionCapfrm', $scope)) {
appInfo.requestProgramAccess(function () {
$scope.setProposal(true);
}, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.Proposal.SelectedProgram.ProgramID,
"RequestChannel": "Via Proposal",
"Vendors": Vendors
});
ngDialog.close();
}
}
$scope.validateProposalAttachments = function (e) {
if ($scope.uploading) {
$scope.showFlashMessage('error', "Please wait,Another upload in progress.");
return false;
}
var totalSize = 0;
for (var i = 0; i < e.target.files.length; i++) {
totalSize += e.target.files[i].size;
}
if (totalSize > 20971520) {
$scope.showFlashMessage('error', "Maximum permitted upload size is 20 MB");
return false;
}
return true;
}
$scope.uploadProposalAttachments = function (e) {
if (e.target.files && e.target.files.length) {
for (var i = 0; i < e.target.files.length; i++) {
var reqData = {
"UploadFile": {
"ModuleName": 'PropsoalAttachments',
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"File": e.target.files[i],
"ProposalGUID": $scope.Proposal.ProposalGUID
}
};
// $scope.Proposal.Attachments.push({ImageName:e.target.files[i].name});
$scope.attachmentsUploadProgress = '0%';
appInfo.uploadFile(reqData).then(function (response) {
var msgType = 'error';
if (response.ResponseCode == 200) {
$scope.Proposal.Attachments.push(response.Data.Media);
msgType = 'success';
} else {
$scope.Proposal.Attachments = [];
}
// Storage.setItem('Proposal',$scope.Proposal);
$scope.showFlashMessage(msgType, response.Message);
}, function () {
$scope.attachmentsUploadProgress = '100%';
$scope.showFlashMessage("error", "Upload Failed. Please try again later.");
$scope.Proposal.Attachments = [];
}, function (progress) {
$scope.attachmentsUploadProgress = progress;
});
}
}
}
$scope.getPropsoalAttachment = function () {
var form = angular.element('#frmDownloadProposalData').attr('action', appInfo.appDocumentDownloadUrl);
form.find('[name="FileName"]').val(this.Proposal.Attachments[0].ImageName);
form.find('[name="DownloadURL"]').val(this.Proposal.Attachments[0].ImageUrl);
form.submit();
}
$scope.delete_proposal_attachment = function () {
$scope.currentindex = this.$index
var reqData = {
"DeleteProposalAttachment": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProposalGUID": $scope.Proposal.ProposalGUID,
"MediaID": this.Attachment.MediaID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.Proposal.Attachments.splice($scope.currentindex, 1);
$scope.showFlashMessage('success', response.Message);
}
else
$scope.showFlashMessage('error', response.Message);
});
}
$scope.showPraposalPopup = function () {
$scope.templateData = {};
$scope.ProposalTemplates.NotificationTemplateID = null;
$scope.ProposalTemplates.TemplateName = null;
$scope.ProposalTemplates.MailSubject = null;
$scope.ProposalTemplates.MailContent = null;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-praposalPopup.html',
className: 'ng-popup ngdialog-theme-default custom-width',
scope: $scope,
});
}
$scope.showPraposalDocumentPopup = function () {
$scope.createProposalTemplate(true);
setTimeout(function () {
$rootScope.SeeRecordData = { maxDisplayPages: '10' };
$scope.Page.documents = {
"ModuleEntityID": $scope.ProposalTemplates.NotificationTemplateID,
"ModuleName": "EmailTemplateDocuments",
"selectedFiles": [],
"DocumentsData": [],
"selectedFileIds": [],
"FolderName": [],
"checkedFile": false,
"filter": { "currentPage": 1 },
"shareWithList": null,
"blockEdit": null,
"blockSelect": null,
"blockDelete": null
};
$rootScope.Page.documents.FolderName = [];
if ($scope.ProposalTemplates.NotificationTemplateID) {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-praposalDocumentPopup.html',
className: 'ng-popup ngdialog-theme-default custom-width',
scope: $scope,
});
$rootScope.refreshFileList();
} else {
$scope.showFlashMessage('error', 'Please Fill All Required Fields.');
}
}, 2000);
}
$scope.createProposalTemplate = function (DontClose) {
if (checkstatus('ProposalTemplates', $scope)) {
if ($scope.ProposalTemplates.MailContent == null) {
$scope.showFlashMessage('error', 'Please Add Mail Content');
return false;
}
var reqData = {
"SaveProposalTemplate": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"CompanyID": $scope.SignIn.UserDetails.CompanyID,
"EventID": 21,
"TemplateName": $scope.ProposalTemplates.TemplateName,
"MailSubject": $scope.ProposalTemplates.MailSubject,
"MailContent": $scope.ProposalTemplates.MailContent
}
}
if ($scope.ProposalTemplates.NotificationTemplateID) {
reqData.SaveProposalTemplate.NotificationTemplateID = $scope.ProposalTemplates.NotificationTemplateID;
} else {
reqData.SaveProposalTemplate.NotificationTemplateID = null;
}
//console.log($scope.ProposalTemplates,reqData); return false;
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.ProposalTemplates.NotificationTemplateID = response.Data;
$scope.getTemplates();
if (!DontClose) {
ngDialog.close();
$scope.showFlashMessage('success', response.Message);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
} else {
//console.log('Not Proper Data');
}
}
$scope.getTemplates = function () {
var reqData = {
"GetTemplates": {
"PageNo": $scope.ProposalTemplates.Filter.Page,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
}
};
if ($scope.ProposalTemplates.Filter) {
with ($scope.ProposalTemplates.Filter) {
reqData.GetTemplates.Filter = {
CompanyID: $rootScope.SignIn.UserDetails.CompanyID,
EventID: 21,
KeyWord: null
}
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.TemplatesListData.TemplatesList = response.Data.Templates;
$scope.totalTemplates = response.Data.Paginator.total_templates;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalTemplates = response.Data.Paginator.total_templates
pagingData.numPerPage = 10;
$scope.showingtextTemplate = appInfo.getPaginationData(pagingData);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
function setProposalConfig() {
$scope.RemoveLeads = [];
if (!$scope.CompanyPreferences.DefaultProgramID) {
$scope.showFlashMessage('error', 'Please first select a program as Default.');
return $state.go('program-list');
}
if ($rootScope.CompanyPreferences.Category == 'Bank') {
$scope.SwitchTab = 2;
}
appInfo.getSignUpStaticData(function () {
appInfo.getUserCreditScores(function () {
if (!$scope.Proposal) {
$location.path('/create-proposal/proposal-create-tab');
$scope.contactData = { PrimaryContactEmail: "" };
$scope.Proposal = {
QuotedAmount: null, Leads: [], Attachments: [], Filter: {
FinanceTimeInBusiness: $rootScope.TimeInBusiness[0],
FinanceCredit: $rootScope.CreditScores[0],
MatchingLeadPage: 1, SelectedLeadPage: 1,
CodeTitle: '',
ProgramsPage: 1
}, Commission: $scope.CompanyPreferences.DefaultCommissionCap, SelectedProgram: null, DisabledTimeInBusiness: [], ProgramFrom: 'self'
};
for (var i in $scope.ApplicationFlowOptions) {
if ($scope.ApplicationFlowOptions[i].key == $scope.CompanyPreferences.DefaultAppWorkFlow) {
$scope.Proposal.AppWorkFlow = $scope.ApplicationFlowOptions[i];
}
}
} else {
$scope.RemoveLeads = Storage.getItem('RemoveLeads');
if (!_.isUndefined($scope.RemoveLeads)) {
for (var i in $scope.Proposal.Leads) {
for (var j in $scope.RemoveLeads) {
if ($scope.Proposal.Leads[i].ID == $scope.RemoveLeads[j].ID) {
$scope.Proposal.Leads.splice(i, 1);
}
}
}
} else
$scope.RemoveLeads = [];
$scope.Proposal.Filter.FinanceCredit = _.findWhere($rootScope.CreditScores, { CreditScoreID: $scope.Proposal.Filter.FinanceCredit.CreditScoreID });
$scope.Proposal.Filter.FinanceTimeInBusiness = _.findWhere($rootScope.TimeInBusiness, { TimeInBusinessID: $scope.Proposal.Filter.FinanceTimeInBusiness.TimeInBusinessID });
if (_.isObject($scope.Proposal.SelectedProgram)) {
appInfo.getTimeInBusiness(function () {
if (_.isUndefined($scope.Proposal.Filter.FinanceTimeInBusiness))
$scope.Proposal.Filter.FinanceTimeInBusiness = _.last($rootScope.TimeInBusiness);
else
$scope.Proposal.Filter.FinanceTimeInBusiness = _.findWhere($rootScope.TimeInBusiness, { TimeInBusinessID: $scope.Proposal.Filter.FinanceTimeInBusiness.TimeInBusinessID });
}, { ProgramID: $scope.CompanyPreferences.DefaultProgramID });
}
}
appInfo.getIndustryTypes(function () {
var industries = [];
angular.copy($scope.Proposal.Filter.IndustryTypes, industries);
$scope.Proposal.Filter.IndustryTypes = [];
if (industries) {
$scope.Proposal.Filter.IndustryTypes = industries;
setTimeout(function () {
_.each(industries, function (i) {
angular.element("#proposalIndustryDetails option").each(function () {
if ((i.IndustryTypeID - 1) == this.value)
$(this).attr('selected', 'selected');
});
});
angular.element("#proposalIndustryDetails").trigger('chosen:updated');
}, 100);
}
});
appInfo.getAssociationList(function () {
if ($scope.Proposal.Filter.Association)
$scope.Proposal.Filter.Association = _.findWhere($rootScope.AssociationData, { CompanyID: $scope.Proposal.Filter.Association.CompanyID });
else
$scope.Proposal.Filter.Association = null;
});
});
}, $scope.CompanyPreferences.DefaultProgramID);
$scope.getTemplates();
$scope.Page.Title = 'Proposals - ' + $scope.CompanyPreferences.CompanyName;
}
if ($rootScope.CompanyPreferences)
setProposalConfig();
else
$scope.$on('company-loaded', setProposalConfig);
$scope.DeleteTemplate = function (TemplateData) {
var reqData = {
"DeleteTempate": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"NotificationTemplateID": TemplateData.NotificationTemplateID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.getTemplates();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.EditTemplate = function (Template) {
$scope.templateData = {};
$scope.ProposalTemplates.NotificationTemplateID = Template.NotificationTemplateID;
$scope.ProposalTemplates.TemplateName = Template.TemplateName;
$scope.ProposalTemplates.MailSubject = Template.MailSubject;
$scope.ProposalTemplates.MailContent = Template.MailContent;
//$scope.showPraposalPopup();
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-praposalPopup.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope,
});
}
}])
// Company User Controller
.controller('companyUserCtrl', ['$rootScope', '$scope', 'appInfo', 'appCache', '$location', 'ngDialog', 'Storage', '$state', function ($rootScope, $scope, appInfo, appCache, $location, ngDialog, Storage, $state) {
$scope.editContact = '';
$scope.addUser = {};
$scope.AllowedUser = true;
$scope.ForcefullyDelete = false;
$scope.resetPage = function () {
if (($scope.SignIn.UserDetails.UserTypeID == 6)) {
$scope.addUser = {
User_Type: _.findWhere($scope.userTypes, { RoleID: 6 })
};
// $scope.disabelUserTypeSelection=TRUE;
} else
$scope.addUser = { User_Type: null };
$scope.refreshCompanysUsersList();
};
$scope.init = function () {
$scope.usersListFilter = { Name: null };
$scope.Page.Title = 'Company User - ' + $scope.CompanyPreferences.CompanyName;
if ($location.path() == "/invited-users") {
$scope.InvitedVendorCurrentPage = 1;
$scope.getInvitedUsers();
} else {
appInfo.getUserTypes($scope.resetPage);
}
}
$scope.getInvitedUsers = function () {
$scope.Page.trackLoading('invited-users');
var reqData = {
"GetInvitedUsers": {
"PageNo": $scope.InvitedVendorCurrentPage,
"CompanyID": $scope.CompanyPreferences.CompanyID,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
}
};
$scope.invitedUsersList = null;
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('invited-users');
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.invitedUsersList = response.Data.Userlogins;
$scope.totalInvitedUsers = response.Data.Paginator.total_users;
pagingData = [];
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalApplications = response.Data.Paginator.total_users;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
if ($location.path() == '/company-user-details') {
var CompanysUsers = Storage.getItem('CompanysUsers');
$scope.CompanyUsersForPhone = CompanysUsers;
appInfo.getUserTypes(function () {
if ($scope.CompanyUsersForPhone.RoleID) {
for (var i in $scope.userTypes) {
if ($scope.userTypes[i].RoleID == $scope.CompanyUsersForPhone.RoleID) {
$scope.CompanyUsersForPhone.userType = $scope.userTypes[i];
break;
}
}
}
});
}
else {
$scope.refreshCompanysUsersList = function () {
$scope.Page.trackLoading('user-list');
var reqData = {
"GetCompanysUsersList": {
"PageNo": $scope.currentPage,
"CompanyID": $scope.CompanyPreferences.CompanyID,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
// "Sort": {
// "CreatedDate": "DESC"
// }
}
};
if ($scope.usersListFilter.Name) {
reqData.GetCompanysUsersList.Filter = { CompanyusersFilter_Name: $scope.usersListFilter.Name };
}
$scope.companysUsersList = null;
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('user-list');
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.AllowedUser = response.AllowedUser;
$scope.InvitedUserCount = response.InvitedUserCount;
$scope.companysUsersList = response.Data.CompanyUsers;
$scope.totalCompanysUsers = response.Data.Paginator.total_users;
pagingData = [];
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalApplications = response.Data.Paginator.total_users;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
if ($rootScope.CompanyPreferences)
$scope.init();
else
$rootScope.$on('company-loaded', $scope.init);
}
$scope.enableEdit = function () {
$scope.enableUserEdit = true;
}
$scope.$on('$stateChangeSuccess', function () {
$("html, body").animate({ scrollTop: 0 }, 200);
});
$scope.saveUserPhoneViewState = function (MantainState) {
Storage.setItem('CompanysUsers', this.CompanysUsers);
if (MantainState == 'ForPhoneView') {
$location.path('/company-user-details');
}
}
$scope.addUsers = function (addUsersData) {
if (checkstatus('frmAddUser', $scope)) {
$scope.loading = true;
var reqData = {
"SignUpCompanyUser": {
"DeviceType": "Web",
"SocialType": "Web",
"DeviceID": "Web",
"SourceID": 1,
"CompanyUser": {
"1": {
"FirstName": addUsersData.FirstName,
"LastName": addUsersData.LastName,
"PercentageOwnership": 0,
"Email": addUsersData.Email,
"Extension": addUsersData.Extension,
"MobileNumber": addUsersData.MobileNumber,
"UserTypeID": addUsersData.User_Type.RoleID,
"SyndicateChecked": addUsersData.syndicateChecked ? addUsersData.syndicateChecked : FALSE
}
},
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
switch (addUsersData.User_Type.RoleID) {
case 2:
Message = 'Admin';
break;
case 3:
Message = "Salesperson";
break;
case 6:
Message = 'Auditor';
break
}
$scope.showFlashMessage('success', $rootScope.ucfirst(addUsersData.FirstName) + " " + $rootScope.ucfirst(addUsersData.LastName) + " is added to " + $rootScope.CompanyPreferences.CompanyName + " as a " + Message);
delete $rootScope.salesPersons;
appCache.remove('SalesPersons');
$scope.resetPage();
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.loading = false;
});
}
}
$scope.editUser = function (editContact) {
if (checkstatus('frmUserDetails', $scope)) {
if (editContact.RoleID == 5) {
editContact.userType = {};
editContact.userType.RoleID = editContact.RoleID;
}
var reqData = {
"EditCompanyUser": {
"1": {
"FirstName": editContact.FirstName,
"LastName": editContact.LastName,
"UserID": editContact.UserID,
"MobileNumber": editContact.MobileNumber,
"UserTypeID": editContact.userType.RoleID,
"oldUserTypeID": editContact.RoleID,
"Extension": editContact.Extension ? editContact.Extension : null,
"SyndicateChecked": editContact.SyndicateChecked ? editContact.SyndicateChecked : 0
},
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.enableUserEdit = false;
if ($location.path() != '/company-user-details')
$scope.refreshCompanysUsersList(); // Only for desktop and tablet view
Storage.removeItem('CompanysUsers');
appInfo.getSalesPersons(function () {
ngDialog.close();
$scope.showFlashMessage('success', response.Message);
}, reqData.EditCompanyUser["1"].UserTypeID == 3);
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.editAuditDialog = function (editContact) {
if (editContact.RoleID == 3 && editContact.userType.RoleID == 6) {
$scope.ngConfirm('Are you sure you want to change sales person to auditor role? This will unassign any applications associated with sales person.', function () {
$scope.editUser(editContact)
});
}
else {
$scope.editUser(editContact)
}
}
$scope.editUserDialog = function () {
$scope.CompanysUsers = this.CompanysUsers;
$scope.saveUserPhoneViewState('ForWebView');
var CompanysUsers = Storage.getItem('CompanysUsers');
$scope.editContact = CompanysUsers;
if ($scope.editContact.RoleID) {
for (var i in $rootScope.userTypes) {
if ($rootScope.userTypes[i].RoleID == $scope.editContact.RoleID) {
$scope.editContact.userType = $rootScope.userTypes[i];
break;
}
}
}
if ($scope.editContact.Extension)
$scope.editContact.Extension = $scope.editContact.Extension.replace('x', '');
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-editUser.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
$scope.showUserDeletePopup = function () {
$scope.companysUsersData = (this.CompanysUsers) ? angular.copy(this.CompanysUsers) : {};
$scope.ngConfirm('Are you sure you want to delete this ' + (($location.path() == "/invited-users") ? "invitation" : "user") + '?', function () {
$scope.removeUser();
});
}
$scope.removeUser = function () {
var reqData = {
"RemoveUser": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"TargetUserID": (($scope.CompanyUsersForPhone) ? $scope.CompanyUsersForPhone : $scope.companysUsersData).UserID,
"ForcefullyDelete": $scope.ForcefullyDelete,
"RemoveInvitation": ($location.path() == "/invited-users")
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if ($location.path() == '/company-user-details') {
$location.path('/company-user');
} else {
$scope.showFlashMessage('success', response.Message);
if ($location.path() == "/invited-users") {
$scope.getInvitedUsers();
} else {
appInfo.getSalesPersons(function () {
$scope.refreshCompanysUsersList();
}, true);
}
}
} else if (response.ResponseCode == 112) {
$rootScope.ngConfirm(response.Message, function () {
$scope.ForcefullyDelete = true;
$scope.removeUser();
});
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.$watch('usersListFilter.Name', _.debounce(function (newval, oldval) {
if (newval != oldval) {
$scope.currentPage = null;
$scope.refreshCompanysUsersList();
}
}, 500));
$scope.showPermmitedAction = function () {
var companysUserData = this.CompanysUsers;
Storage.setItem('companysUserData', companysUserData);
$state.go('permitted-actions');
}
}])
// reports Controller
.controller('reportCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', function ($rootScope, $scope, appInfo, $location, ngDialog) {
$scope.getCompanyPerformanceAnalytics = function () {
var reqData = {
"GetCompanyPerformanceAnalytics": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Year": $rootScope.currentYear
}
}
$scope.Page.trackLoading('company-performance-graph');
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.Title = 'Performance Report - ' + $rootScope.CompanyPreferences.CompanyName;
if (response.ResponseCode == 200) {
$scope.CompanyPerformanceData = response.Data;
var chartDataRaw = [{
"month": $rootScope.currentYear + "00",
"value": parseInt($scope.CompanyPerformanceData.Jan)
}, {
"month": $rootScope.currentYear + "01",
"value": parseInt($scope.CompanyPerformanceData.Feb)
}, {
"month": $rootScope.currentYear + "02",
"value": parseInt($scope.CompanyPerformanceData.Mar)
}, {
"month": $rootScope.currentYear + "03",
"value": parseInt($scope.CompanyPerformanceData.Apr)
}, {
"month": $rootScope.currentYear + "04",
"value": parseInt($scope.CompanyPerformanceData.May)
}, {
"month": $rootScope.currentYear + "05",
"value": parseInt($scope.CompanyPerformanceData.Jun)
}, {
"month": $rootScope.currentYear + "06",
"value": parseInt($scope.CompanyPerformanceData.Jul)
}, {
"month": $rootScope.currentYear + "07",
"value": parseInt($scope.CompanyPerformanceData.Aug)
}, {
"month": $rootScope.currentYear + "08",
"value": parseInt($scope.CompanyPerformanceData.Sep)
}, {
"month": $rootScope.currentYear + "09",
"value": parseInt($scope.CompanyPerformanceData.Oct)
}, {
"month": $rootScope.currentYear + "10",
"value": parseInt($scope.CompanyPerformanceData.Nov)
}, {
"month": $rootScope.currentYear + "11",
"value": parseInt($scope.CompanyPerformanceData.Dec)
}];
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('date', 'Month');
dataTable.addColumn('number', 'value');
var i = 1;
//chartDataRaw is array of objects, requested from server. looped through jquery each to fill dataTable
$.each(chartDataRaw, function () {
var year = this.month.substring(0, 4);
var month = this.month.substring(4);
var dataItem = [new Date(year, month), this.value];
dataTable.addRow(dataItem);
});
var options = {
title: 'Overall Performance of Year',
titleTextStyle: { color: '#666666', fontSize: '16', fontName: 'open_sansregular' },
vAxis: { format: '$#,###,###.##', gridlines: { count: (7) } },
hAxis: { format: '' },
fontSize: 12,
legend: { position: "none" },
colors: ['#40AC42'],
height: '300',
chartArea: { backgroundColor: { 'fill': '#FFF' }, left: 70, width: "95%" },
bar: { groupWidth: "40%" }
};
var formatter = new google.visualization.NumberFormat({ prefix: '$' });
formatter.format(dataTable, 1);
var monthYearFormatter = new google.visualization.DateFormat({
pattern: "MMM, yyyy"
});
monthYearFormatter.format(dataTable, 0); //change date format to render on chart
var chart = new google.visualization.ColumnChart(document.getElementById('overAllPerformanceChart'));
chart.draw(dataTable, options);
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('company-performance-graph');
});
}
$scope.getCompanyPerformanceAnalytics();
$scope.getSalesPerformanceAnalytics = function () {
var reqData = {
"GetSalesPerformanceAnalytics": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Year": $rootScope.currentYear
}
}
$scope.Page.trackLoading('sales-performance-graph');
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.SalesPerformanceData = response.Data;
if ($scope.SalesPerformanceData.length) {
var pivotData = [
['Month'],
['Jan' + $rootScope.currentYear],
['Feb' + $rootScope.currentYear], ['Mar' + $rootScope.currentYear],
['Apr' + $rootScope.currentYear,], ['May' + $rootScope.currentYear],
['Jun' + $rootScope.currentYear], ['Jul' + $rootScope.currentYear],
['Aug' + $rootScope.currentYear], ['Sep' + $rootScope.currentYear],
['Oct' + $rootScope.currentYear], ['Nov' + $rootScope.currentYear],
['Dec' + $rootScope.currentYear]];
for (var i in response.Data) {
pivotData[0][parseInt(i) + 1] = response.Data[i].FirstName + ' ' + response.Data[i].LastName;
pivotData[1][parseInt(i) + 1] = parseInt(response.Data[i].Jan);
pivotData[2][parseInt(i) + 1] = parseInt(response.Data[i].Feb);
pivotData[3][parseInt(i) + 1] = parseInt(response.Data[i].Mar);
pivotData[4][parseInt(i) + 1] = parseInt(response.Data[i].Apr);
pivotData[5][parseInt(i) + 1] = parseInt(response.Data[i].May);
pivotData[6][parseInt(i) + 1] = parseInt(response.Data[i].Jun);
pivotData[7][parseInt(i) + 1] = parseInt(response.Data[i].Jul);
pivotData[8][parseInt(i) + 1] = parseInt(response.Data[i].Aug);
pivotData[9][parseInt(i) + 1] = parseInt(response.Data[i].Sep);
pivotData[10][parseInt(i) + 1] = parseInt(response.Data[i].Oct);
pivotData[11][parseInt(i) + 1] = parseInt(response.Data[i].Nov);
pivotData[12][parseInt(i) + 1] = parseInt(response.Data[i].Dec);
}
var data = google.visualization.arrayToDataTable(pivotData);
var options = {
title: 'Performance of all sales persons',
titleTextStyle: { color: '#666666', fontSize: '16', fontName: 'open_sansregular' },
vAxis: { format: '$#,###,###.##', gridlines: { count: (7) } },
hAxis: { format: '#' },
fontSize: 12,
chartArea: { backgroundColor: { 'fill': '#FFF' }, left: 70, width: "95%" },
legend: { position: 'bottom', alignment: 'start' },
pointSize: 5,
colors: ['#9358AC', '#FFB848', '#40AC42', '#4697CE', '#847F9F', '#00B7C5'],
bar: { groupWidth: "40%" },
height: '300'
};
var formatter = new google.visualization.NumberFormat({ prefix: '$' });
for (var i in response.Data) {
formatter.format(data, parseInt(i) + 1);
}
var chart = new google.visualization.LineChart(document.getElementById('salesPersonPerformanceChart'));
chart.draw(data, options);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('sales-performance-graph');
});
}
$scope.getSalesPerformanceAnalytics();
}])
// Contact Us Controller
.controller('contactUsCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', function ($rootScope, $scope, appInfo, $location, ngDialog) {
$scope.alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
$scope.totalApplications = 0;
$scope.currentPage = 1;
$scope.sentMessage = '';
//reset contact
$scope.salesMode = false;
$scope.resetPage = function (letter) {
if (!_.isString(letter))
letter = null;
$scope.contactListFilter = { Name: null, searchBar: letter };
$scope.Page.Title = 'Contacts - ' + $rootScope.CompanyPreferences.CompanyName;
$scope.refreshGetContactList();
};
$scope.showSalesLeadPopup = function () {
$scope.contactData = (this.contacts) ? angular.copy(this.contacts) : {};
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-dlgAddContact.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope
});
}
$scope.salesLeadMode = function () {
$scope.salesMode = true;
}
$scope.changeSalesLeadMode = function () {
$scope.salesMode = false;
}
// Add Contact
$scope.saveContact = function () {
var contactData = $scope.contactData;
$scope.Page.trackLoading('save-contact');
if (checkstatus('frmAddContact', $scope) && contactData) {
var reqData = {
"addEditcontact": {
"SalesLeadID": (contactData.SalesLeadID) ? contactData.SalesLeadID : "",
"DeviceType": "Web",
"ContactDetails": {
"FirstName": contactData.FirstName,
"LastName": contactData.LastName,
"PrimaryContactNo": contactData.PrimaryContactNo,
"SecondaryContactNo": contactData.SecondaryContactNo,
"FaxNo": contactData.FaxNo,
"PrimaryContactEmail": contactData.PrimaryContactEmail,
"SecondaryContactEmail": contactData.SecondaryContactEmail
},
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.refreshGetContactList();
ngDialog.close();
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('save-contact');
});
}
}
// Edit contact function
$rootScope.editContactList = function (editContact) {
var reqData = {
"addEditcontact": {
"SalesLeadID": editContact.SalesLeadID,
"DeviceType": "Web",
"ContactDetails": {
"FirstName": editContact.FirstName,
"LastName": editContact.LastName,
"PrimaryContactNo": editContact.PrimaryContactNo,
"SecondaryContactNo": editContact.SecondaryContactNo,
"FaxNo": editContact.FaxNo,
"PrimaryContactEmail": editContact.PrimaryContactEmail,
"SecondaryContactEmail": editContact.SecondaryContactEmail
},
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.contactList = response.Data.Contacts;
$scope.refreshGetContactList();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
// Delete Contact
$scope.showDeleteContactPopup = function () {
$scope.contactData = (this.contacts.SalesLeadID) ? angular.copy(this.contacts.SalesLeadID) : {};
$rootScope.ngConfirm('Are you sure you want to delete this Contact ?', function () {
$scope.deleteContact();
});
}
$rootScope.deleteContact = function () {
var reqData = {
"Removecontact": {
"SalesLeadID": $scope.contactData,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.refreshGetContactList();
ngDialog.close();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.refreshGetContactList = function () {
$scope.Page.trackLoading('contact-list');
var reqData = {
"GetContactList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.currentPage,
"Filter": {
"ContactFilter_Alphabet": $scope.contactListFilter.searchBar,
"ContactFilter_Name": $scope.contactListFilter.Name
}
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.contactList = response.Data.Contacts;
pagingData = [];
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalApplications = response.Data.Paginator.total_contacts;
pagingData.numPerPage = 12;
$scope.showingtext = appInfo.getPaginationData(pagingData);
} else {
$scope.contactList = false;
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('contact-list');
});
}
if ($rootScope.CompanyPreferences)
$scope.resetPage();
else
$rootScope.$on('company-loaded', $scope.resetPage);
$scope.$watch('contactListFilter.Name', function (newValue, oldValue) {
if (newValue != oldValue) {
$scope.contactListFilter.searchBar = null;
$scope.refreshGetContactList();
}
});
}])
// Borrower Controller
.controller('borrowerCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', 'Storage', function ($rootScope, $scope, appInfo, $location, ngDialog, Storage) {
$scope.firstLoad = true;
$scope.refreshBorrowerList = function () {
$scope.Page.trackLoading('borrower-list');
var reqData = {
"GetBorrowersList": {
"PageNo": $scope.borrowerListFilter.currentPage,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"Filter": {
"BorrowersFilter_Name": '',
"BorrowersFilter_Email": '',
"BorrowersFilter_StartDate": '',
"BorrowersFilter_EndDate": '',
},
"Sort": {
"FirstName": ''
}
}
};
if ($scope.borrowerListFilter) {
reqData.GetBorrowersList.Filter = {
BorrowersFilter_StartDate: $scope.borrowerListFilter.StartDate,
BorrowersFilter_EndDate: $scope.borrowerListFilter.EndDate,
BorrowersFilter_Email: $scope.borrowerListFilter.Email,
BorrowersFilter_Name: $scope.borrowerListFilter.Name
};
}
if (!$scope.firstLoad)
$scope.saveBorrowerState(null);
$scope.borrowersList = null;
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.Page.untrackLoading('borrower-list');
if (response.Data) {
$scope.borrowersList = response.Data.Borrowers;
$scope.totalborrowers = response.Data.Paginator.total_users;
pagingData = [];
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalApplications = response.Data.Paginator.total_users;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.resetBorrowerList = function () {
$scope.borrowerListFilter = { Name: null, StartDate: null, EndDate: null, currentPage: 1 };
$scope.refreshBorrowerList();
}
$scope.navigateToApplications = function (BorrowerID, Email) {
var appList = {
"ApplicationNumber": null,
"Filter": {
Name: null, StartDate: null, EndDate: null,
appStatus: { StatusName: null }, BorrowerID: BorrowerID, Email: Email
},
"currentPage": 1,
"SortBy": null
};
Storage.setItem('appList', appList);
$location.path('/applications');
}
$scope.saveBorrowerState = function () {
var borrowerList = {
"Filter": $scope.borrowerListFilter,
"currentPage": $scope.borrowerListFilter.currentPage
};
Storage.setItem('borrowerList', borrowerList);
}
var init = function () {
var borrowerList = Storage.getItem('borrowerList');
if (borrowerList) {
$scope.borrowerListFilter = borrowerList.Filter;
$scope.refreshBorrowerList();
} else
$scope.resetBorrowerList();
$scope.firstLoad = false;
$scope.Page.Title = 'Borrower - ' + $rootScope.CompanyPreferences.CompanyName;
}
if ($scope.CompanyPreferences)
init();
else
$scope.$on('company-loaded', init);
$scope.$watch('borrowerListFilter.Name', function (newValue, oldValue) {
if (newValue != oldValue)
$scope.refreshBorrowerList();
});
$scope.$watch('borrowerListFilter.StartDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.borrowerListFilter.EndDate) {
var StartDate = new Date(newValue);
var EndDate = new Date($scope.borrowerListFilter.EndDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.borrowerListFilter.StartDate = null;
}
}
});
$scope.$watch('borrowerListFilter.EndDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.borrowerListFilter.StartDate) {
var EndDate = new Date(newValue);
var StartDate = new Date($scope.borrowerListFilter.StartDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.borrowerListFilter.EndDate = null;
}
}
});
}])
// New Application Controller
.controller('NewApplicationController', ['$rootScope', '$scope', 'appInfo', '$state', 'ngDialog', 'Storage', '$timeout', function ($rootScope, $scope, appInfo, $state, ngDialog, Storage, $timeout) {
$scope.dataEnable = $scope.SalesPersondisable = $scope.hideSalesPerson = false;
$rootScope.statename = $state.current.name;
setTimeout(function () {
$(".chosen-multiple-single").chosen({ max_selected_options: 1 });
}, 2000);
if ($scope.SignIn && $scope.SignIn.UserDetails.UserTypeID == '3') {
$scope.hideSalesPerson = true;
};
$scope.goBack = function () {
if ($scope.viewPartial) {
$scope.ngConfirm('Are you sure you want to cancel? All your changes will lost.', function () {
Storage.removeItem('PartialApplications');
if ($scope.SignIn)
$state.go('partial-application');
else
$state.go('home');
});
} else
$state.go('applications');
};
$scope.dataRequired = $scope.viewPartial = ['review-application', 'view-partial'].indexOf($state.current.name) != -1;
$scope.addOwners = function () {
$scope.BusinessPartners.push({});
}
$scope.removeOwner = function () {
if (this.BusinessOwner.PercentageOwnership > 0)
$scope.Business.totalOwnership -= parseInt(this.BusinessOwner.PercentageOwnership);
$scope.BusinessPartners.splice(this.$index, 1);
}
$scope.updateEMI = _.debounce(function () {
if ($scope.LoanData && $scope.LoanData.FinanceAmount && $scope.appliedProgram) {
var LoanData = appInfo.getCalcData({
"FinancePurposeID": [],
"FinanceCredit": _.isObject($scope.LoanData.FinanceCredit) ? $scope.LoanData.FinanceCredit.CreditScoreID : 1,
"FinanceAmount": ($scope.LoanData.FinanceAmount) ? ($scope.LoanData.FinanceAmount + '').replace(',', '') : $scope.CompanyPreferences.DefaultAmount,
"FinanceTenure": _.isObject($scope.LoanData.FinanceTenure) ? $scope.LoanData.FinanceTenure.Term : $scope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": _.isObject($scope.LoanData.FinanceTimeInBusiness) ? parseInt($scope.LoanData.FinanceTimeInBusiness.TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID,
"ShowConfigurationError": !_.isUndefined($scope.LoanData.preventRevert) ? $scope.LoanData.preventRevert : true,
"CommissionPoints": !_.isUndefined($scope.LoanData.CommissionPoints) ? $scope.LoanData.CommissionPoints : false
});
if (LoanData && $scope.LoanData.ProgramLoanType == 'Personal') {
LoanData.FinancePurposeID = [];
for (var i in $scope.LoanData.FinancePurpose) {
if (typeof $scope.LoanData.FinancePurpose[i] == 'object')
LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i].FinancePurposeID);
else
LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i]);
}
}
$scope.LoanData.AmountPayable = LoanData.AmountPayable;
$scope.LoanData.CommissionPoints = LoanData.CommissionPoints;
if (!$scope.$$phase)
$scope.$apply();
return LoanData;
}
}, 100);
$scope.$watch('LoanData.FinanceAmount', _.debounce(function (newValue, oldValue) {
if ($scope.appliedProgram && newValue && newValue != oldValue && !$scope.ignoreEMIUpdate) {
if (newValue.length < 5 || (!$scope.updateEMI() && $scope.appliedProgram.MinAmount > newValue)) {
$scope.errorFinanceAmount = 'Minimum required amount is $ ' + $scope.appliedProgram.MinAmount.formatMoney();
$scope.LoanData.AmountPayable = null;
if (newValue < $scope.appliedProgram.MinAmount) {
$scope.LoanData.FinanceAmount = $scope.appliedProgram.MinAmount;
} else if (newValue > $scope.appliedProgram.MaxAmount) {
$scope.LoanData.FinanceAmount = $scope.appliedProgram.MaxAmount;
}
}
else {
$scope.errorFinanceAmount = '';
// if(!$scope.updateEMI())
// $scope.LoanData.FinanceAmount=oldValue;
}
}
}, 500));
$scope.$watch('LoanData.FinanceCredit', _.debounce(function (newValue, oldValue) {
if (angular.isObject(newValue) && !angular.equals(newValue, oldValue) && !$scope.ignoreEMIUpdate) {
if (!$scope.updateEMI() && !$scope.LoanData.preventRevert) {
// $scope.LoanData.FinanceCredit=oldValue;
}
}
if (_.isFunction($scope.prepareSliderConfiguration))
$scope.prepareSliderConfiguration();
}, 200));
$scope.$watch('LoanData.FinanceTenure', function (newValue, oldValue) {
if (angular.isObject(newValue) && !angular.equals(newValue, oldValue) && !$scope.ignoreEMIUpdate) {
if (!$scope.updateEMI())
$scope.LoanData.FinanceTenure = oldValue;
var Term = newValue;
$($scope.appliedProgram.Terms).each(function (k, v) {
if (v.Term == Term.Term) {
$scope.LoanData.FinanceTenure = v;
$('#loanTerm').val(k).trigger("chosen:updated");
}
});
}
});
$scope.$watch('LoanData.FinanceTimeInBusiness', _.debounce(function (newValue, oldValue) {
if (angular.isObject(newValue) && !angular.equals(newValue, oldValue) && !$scope.ignoreEMIUpdate) {
if (!$scope.updateEMI() && !$scope.LoanData.preventRevert) {
$scope.LoanData.FinanceTimeInBusiness = oldValue;
}
}
if (_.isFunction($scope.prepareSliderConfiguration))
$scope.prepareSliderConfiguration();
}, 200));
function validateBusinessTime(newValue, oldValue) {
if (newValue && newValue != oldValue) {
if ($scope.Business.Year && $scope.Business.Year.Year == $rootScope.currentYear && $scope.Business.Month && $scope.Business.Month.key > parseInt(new Date().getMonth() + 1)) {
$scope.showFlashMessage('error', "Can't use Future date for Time in business");
$('#BusinessMonth').parent('.field-wrap').addClass('hasError').find('label').text('Choose lesser');
$scope.Business.Month = null;
}
}
}
$scope.$watch('Business.Month', validateBusinessTime);
$scope.$watch('Business.Year', validateBusinessTime);
$scope.resetPage = function () {
$scope.errorFinanceAmount = '';
$scope.BusinessPartners = [];
$scope.Contact = {
FirstName: null, LastName: null, Email: null, MobileNumber: null, Address1: null, Address2: null,
City: null, StateID: null, PostalCode: null, SocialSecurityNumber: null, PercentageOwnership: null
}
$scope.SalesPersonLoaded = $scope.StatesLoaded = false;
$scope.Business = {
Month: null, Year: null, Address1: null, Address2: null, DBA: null, TaxID: null, LegalStructure: null,
City: null, PostalCode: null, StateID: null, PhoneNumber: null, ContactName: null, ContactNumber: null, Name: null, IndustryTypes: null,
totalOwnership: 0
};
$scope.PrimaryOwner = {
FirstName: null, LastName: null, Email: null, MobileNumber: null, Address1: null, Address2: null,
City: null, StateID: null, PostalCode: null, SocialSecurityNumber: null, PercentageOwnership: null
}
$scope.loadLoanData = function () {
$scope.LoanData = {
FinanceAmount: $scope.CompanyPreferences.DefaultAmount,
AmountPayable: null,
FinanceTenure: _.findWhere($scope.appliedProgram.Terms, { Term: $scope.CompanyPreferences.DefaultLoanTerm }),
FinanceCredit: _.first($scope.CreditScores),
FinanceTimeInBusiness: _.findWhere($scope.TimeInBusiness, { TimeInBusinessID: $scope.CompanyPreferences.DefaultTimeInBusinessID }),
FinancePurpose: null,
ProgramLoanType: $scope.ProgramLoanType,
AddOns: {}
};
if (_.isFunction($scope.postLoanDataLoad))
$scope.postLoanDataLoad($scope);
// $scope.disableCreditScores=appInfo.disableCreditScore($scope.appliedProgram);
}
if ($scope.appliedProgram && ($scope.TimeInBusiness || $scope.appliedProgram.ProgramLoanType)) {
$scope.loadLoanData();
} else
$rootScope.$on('company-loaded', $scope.loadLoanData);
$scope.Login = {};
$scope.PartialApplications = {
PartialAppUID: null, LoanData: null, Form1Data: null, Form2Data: null, Form3Data: null, fixedAmount: $state.current.name == 'monthly-quote'
};
setTimeout($scope.updateEMI, 400);
$scope.Equipment = {
Description: null,
PurposeOfPurchase: $rootScope.PurposeOfPurchase[1],
};
$scope.Medical = {
License: null,
LicenseIssueDate: null,
LicenseIssueState: null,
SpecialityDescription: null,
};
if ($rootScope.SignIn) {
appInfo.getSalesPersons(function () {
if (!$scope.SalesPerson)
$scope.SalesPerson = null;
$scope.SalesPersonLoaded = true;
if ($rootScope.SignIn.UserDetails.UserTypeID == '3') {
for (var j in $rootScope.salesPersons) {
if ($rootScope.salesPersons[j].ID == $rootScope.SignIn.UserDetails.UserID) {
$scope.SalesPerson = $rootScope.salesPersons[j];
}
}
$scope.SalesPersondisable = true;
};
});
}
appInfo.getStates(function () {
if (!$scope.Business.StateID)
$scope.Business.StateID = {};
if (!$scope.Medical.LicenseIssueState)
$scope.Medical.LicenseIssueState = {};
if (!$scope.PrimaryOwner.StateID)
$scope.PrimaryOwner.StateID = {};
if (!$scope.Login.StateID)
$scope.Login.StateID = {};
});
appInfo.getLegalStructureName(function () {
if (!$scope.Business.LegalStructure)
$scope.Business.LegalStructure = {};
$scope.LegalStructureLoaded = true;
});
$scope.App = {};
appInfo.getBusinessPurposeList(function () {
$scope.App.BusinessApplicationPurposeID = null;
});
appInfo.getGetAnnualRevenueList(function () {
$scope.App.AnnualRevenueID = null;
});
appInfo.getIndustryTypes(function () {
$scope.dataEnable = !$scope.dataEnable;
if (!$scope.Business.IndustryTypes || !angular.isObject($scope.Business.IndustryTypes)) {
if ($rootScope.CompanyPreferences.DefaultIndustrySelected != 0) {
for (var j in $rootScope.industryData) {
if ($rootScope.industryData[j].IndustryTypeID == $rootScope.CompanyPreferences.DefaultIndustrySelected) {
$scope.Business.IndustryTypes = $rootScope.industryData[j];
if ($rootScope.CompanyPreferences.RestrictIndustryDefault != 0)
setTimeout(function () {
$('#BusinessIndustryType').prop('disabled', true).trigger('chosen:updated');
}, 200);
break;
}
}
} else
$scope.Business.IndustryTypes = {};
}
$scope.dataEnable = !$scope.dataEnable;
});
};
$scope.mapPartialAppData = function (callback) {
switch ($state.current.name) {
case 'home':
case 'signout':
case 'signin':
case 'recovery':
Storage.removeItem('PartialApplications');
return;
break;
default:
var p = Storage.getItem('PartialApplications');
if (!p) {
return;
}
if (p.Form1Data == null && p.Form3Data != null && p.Form3Data.SignUpBusiness3 != null && p.Form3Data.SignUpBusiness3.Users_Email) {
p.Form1Data = {};
p.Form1Data['SignUpBusiness1'] = {};
p.Form1Data['SignUpBusiness1']['Login_LoginKeyword'] = p.Form3Data.SignUpBusiness3.Users_Email;
}
$scope.PartialApplications = p;
if (_.isNull($scope.PartialApplications.ThirdParty)) {
$scope.isThirdParty = false;
} else {
$scope.isThirdParty = true;
}
switch ($state.current.name) {
case 'monthly-quote':
$scope.PartialApplications.fixedAmount = true;
break;
}
}
$scope.dataRequired = TRUE;
$scope.PartialApplications.acceptedTerms = false;
$scope.$watch('SalesPersonLoaded', function () {
$scope.SalesPerson = _.findWhere($scope.salesPersons, { ID: $scope.PartialApplications.AssigneeID });
});
$scope.App = {};
if ($scope.PartialApplications.BusinessApplicationPurposeID) {
appInfo.getBusinessPurposeList(function () {
$scope.App.BusinessApplicationPurposeID = _.findWhere($rootScope.BusinessPurposeData, { BusinessApplicationPurposeID: $scope.PartialApplications.BusinessApplicationPurposeID });
});
}
if ($scope.PartialApplications.AnnualRevenueID) {
appInfo.getGetAnnualRevenueList(function () {
$scope.App.AnnualRevenueID = _.findWhere($rootScope.GetAnnualRevenueData, { AnnualRevenueID: $scope.PartialApplications.AnnualRevenueID });
});
}
if ($scope.PartialApplications.Form1Data) {
with ($scope.PartialApplications.Form1Data.SignUpBusiness1) {
$scope.Login = {
LoginKeyword: (typeof Login_LoginKeyword != 'undefined') ? Login_LoginKeyword : null,
Password: (typeof Login_Password != 'undefined') ? Login_Password : null,
StateID: (typeof Users_StateID != 'undefined') ? Users_StateID : null,
}
}
appInfo.getStates(function () {
$scope.Login.StateID = _.findWhere($scope.stateData, { StateID: $scope.Login.StateID });
});
}
if ($scope.PartialApplications.Form2Data) {
with ($scope.PartialApplications.Form2Data.SignUpBusiness2) {
$scope.Business = {
Name: (typeof Business_BusinessName != 'undefined') ? Business_BusinessName : null,
DBA: (typeof Business_DBA != 'undefined') ? Business_DBA : null,
TaxID: (typeof Business_TaxID != 'undefined') ? Business_TaxID : null,
ContactName: (typeof Business_ContactName != 'undefined') ? Business_ContactName : null,
ContactNumber: (typeof Business_ContactNumber != 'undefined') ? Business_ContactNumber : null,
PhoneNumber: (typeof Business_PhoneNumber != 'undefined') ? Business_PhoneNumber : null,
LegalStructure: (typeof Business_LegalStructureName != 'undefined') ? Business_LegalStructureName : null,
Year: (typeof Business_Year != 'undefined') ? Business_Year : null,
Month: (typeof Business_Month != 'undefined') ? Business_Month : null,
IndustryTypes: [],
Address1: (typeof Business_Address1 == 'string') ? Business_Address1 : null,
Address2: (typeof Business_Address2 == 'string') ? Business_Address2 : null,
City: (typeof Business_CityID != 'undefined') ? Business_CityID : null,
PostalCode: (typeof Business_Postal != 'undefined') ? Business_Postal : null,
StateID: (typeof Business_StateID != 'undefined') ? Business_StateID : null,
totalOwnership: 0
};
appInfo.getStates(function () {
$scope.Business.StateID = _.findWhere($rootScope.stateData, { StateID: $scope.Business.StateID });
});
if ($scope.Business.IndustryTypes) {
$scope.Medical = {
License: (typeof Business_MedicalLicense != 'undefined') ? Business_MedicalLicense : null,
LicenseIssueDate: (typeof Business_MedicalLicenseIssueDate != 'undefined') ? Business_MedicalLicenseIssueDate : null,
LicenseIssueState: !_.isUndefined($scope.PartialApplications.Form2Data.SignUpBusiness2.Business_MedicalLicenseStateID) ? $scope.PartialApplications.Form2Data.SignUpBusiness2.Business_MedicalLicenseStateID : null,
SpecialityDescription: (typeof Business_MedicalSpecialityDescription != 'undefined') ? Business_MedicalSpecialityDescription : null,
};
// if($scope.Medical.LicenseIssueDate){
// var D=new Date($scope.Medical.LicenseIssueDate);
// $scope.Medical.LicenseIssueDate = D.getMonth()+'/'+D.getDay()+'/'+D.getFullYear()
// }
}
$scope.Equipment = {
Description: (typeof Business_EquipmentDescription != 'undefined') ? Business_EquipmentDescription : null,
PurposeOfPurchase: (typeof Business_PurposeOfPurchase != 'undefined') ? Business_PurposeOfPurchase : null,
};
}
appInfo.getStates(function () {
for (var j in $rootScope.stateData) {
if ($rootScope.stateData[j].StateID == $scope.Business.StateID) {
$scope.Business.StateID = $rootScope.stateData[j];
}
if ($scope.Medical && $rootScope.stateData[j].StateID == $scope.Medical.LicenseIssueState) {
$scope.Medical.LicenseIssueState = $rootScope.stateData[j];
}
}
});
for (var j in $scope.MasterMonths) {
if ($scope.MasterMonths[j].key == $scope.Business.Month) {
$scope.Business.Month = $scope.MasterMonths[j];
}
}
for (var j in $rootScope.Years) {
if ($rootScope.Years[j].Year == $scope.Business.Year) {
$scope.Business.Year = $rootScope.Years[j];
}
}
for (var j in $rootScope.PurposeOfPurchase) {
if ($rootScope.PurposeOfPurchase[j].key == $scope.Equipment.PurposeOfPurchase) {
$scope.Equipment.PurposeOfPurchase = $rootScope.PurposeOfPurchase[j];
}
}
$scope.$watch('LegalStructureLoaded', function () {
for (var j in $rootScope.legalStructureData) {
if ($rootScope.legalStructureData[j].LegalStructureID == $scope.Business.LegalStructure) {
$scope.Business.LegalStructure = $rootScope.legalStructureData[j];
}
}
});
appInfo.getIndustryTypes(function () {
if ($scope.CompanyPreferences.RestrictIndustryDefault) {
$scope.Business.IndustryTypes.push(_.findWhere($rootScope.industryData, { IndustryTypeID: $scope.CompanyPreferences.DefaultIndustrySelected }));
} else if (_.isNumber($scope.PartialApplications.Form2Data.SignUpBusiness2.Business_IndustryTypes)) {
$scope.Business.IndustryTypes.push(_.findWhere($rootScope.industryData, { IndustryTypeID: $scope.PartialApplications.Form2Data.SignUpBusiness2.Business_IndustryTypes }));
} else if (_.isObject($scope.PartialApplications.Form2Data.SignUpBusiness2.Business_IndustryTypes)) {
for (var i in $rootScope.industryData) {
for (var j in $scope.PartialApplications.Form2Data.SignUpBusiness2.Business_IndustryTypes) {
if ($rootScope.industryData[i].IndustryTypeID == $scope.PartialApplications.Form2Data.SignUpBusiness2.Business_IndustryTypes[j]) {
$scope.Business.IndustryTypes.push($rootScope.industryData[i]);
}
}
}
} else
$scope.Business.IndustryTypes = false;
});
} else if (!$scope.Business) {
$scope.Business = { IndustryTypes: {} };
}
setTimeout(function () {
$(".chosen-multiple-single").chosen({ max_selected_options: 1 });
}, 2000);
setTimeout(function () {
var indType = $('#BusinessIndustryType option[selected="selected"]').val();
if (typeof (indType) === "undefined") {
var labelName = _.isEmpty($scope.Business.IndustryTypes) ? null : $scope.Business.IndustryTypes[0].Name;
$('#BusinessIndustryType option[label="' + labelName + '"]').attr("selected", "selected");
var inderstryType = $('#BusinessIndustryType option[selected="selected"]').val();
$('#BusinessIndustryType').val(inderstryType).trigger('chosen:updated');
} else {
$('#BusinessIndustryType').val(indType).trigger('chosen:updated');
}
}, 4000);
if ($scope.PartialApplications.Form3Data) {
with ($scope.PartialApplications.Form3Data.SignUpBusiness3) {
if (!$scope.Login.LoginKeyword) {
$scope.Login.LoginKeyword = (typeof Users_Email != 'undefined') ? Users_Email : null;
}
$scope.PrimaryOwner = {
FirstName: (typeof Users_FirstName != 'undefined') ? Users_FirstName : null,
LastName: (typeof Users_LastName != 'undefined') ? Users_LastName : null,
MobileNumber: (typeof Users_MobileNumber != 'undefined') ? Users_MobileNumber : null,
LastName: (typeof Users_LastName != 'undefined') ? Users_LastName : null,
Email: (typeof Users_Email != 'undefined') ? Users_Email : null,
SocialSecurityNumber: (typeof Users_SocialSecurityNumber != 'undefined') ? Users_SocialSecurityNumber : null,
Address1: (typeof Users_Address1 != 'undefined') ? Users_Address1 : null,
Address2: (typeof Users_Address2 != 'undefined') ? Users_Address2 : null,
City: (typeof Users_CityID != 'undefined') ? Users_CityID : null,
StateID: (typeof Users_StateID != 'undefined') ? Users_StateID : null,
PostalCode: (typeof Users_Postal != 'undefined') ? Users_Postal : null,
PercentageOwnership: (typeof Users_PercentageOwnership != 'undefined') ? Users_PercentageOwnership : null
};
$scope.Business.totalOwnership = $scope.PrimaryOwner.PercentageOwnership;
if (typeof AdditionalOwners != 'undefined') {
$scope.BusinessPartners = AdditionalOwners;
};
}
if (typeof AdditionalOwners != 'undefined')
$scope.BusinessPartners = AdditionalOwners;
appInfo.getStates(function () {
$scope.PrimaryOwner.StateID = _.findWhere($rootScope.stateData, { StateID: $scope.PrimaryOwner.StateID });
});
}
if ($scope.PartialApplications.LoanData) {
$scope.ignoreEMIUpdate = true;
$scope.LoanData = {
FinanceAmount: $scope.PartialApplications.LoanData.ApplicationHome.FinanceAmount,
CommissionPoints: $scope.PartialApplications.LoanData.ApplicationHome.CommissionPoints,
AmountPayable: $scope.PartialApplications.LoanData.ApplicationHome.AmountPayable,
FinanceTenure: parseInt($scope.PartialApplications.LoanData.ApplicationHome.FinanceTenure),
FinanceCredit: $scope.PartialApplications.LoanData.ApplicationHome.FinanceCredit,
FinanceTimeInBusiness: $scope.PartialApplications.LoanData.ApplicationHome.FinanceTimeInBusiness,
FinancePurpose: $scope.PartialApplications.LoanData.ApplicationHome.FinancePurposeID,
ProgramLoanType: $scope.PartialApplications.LoanData.ApplicationHome.ProgramLoanType,
};
if ($scope.PartialApplications.LoanData.ApplicationHome.hideEMI)
$rootScope.hideEMI = TRUE;
var fundingConfig = {
ProgramID: $scope.CompanyPreferences.DefaultProgramID,
UsingDefault: true
};
if (!$scope.isThirdParty) {
if ($scope.PartialApplications.ProgramID) {
fundingConfig.ProgramID = $scope.PartialApplications.ProgramID;
fundingConfig.UsingDefault = FALSE;//changed to True to resolve TimeInBusinessID error
}
if ($scope.PartialApplications.ProposalID)
fundingConfig.ProposalID = $scope.PartialApplications.ProposalID;
if (!angular.equals(fundingConfig, $scope.loadingFundingData)) {
var mapLoanData = function () {
if ($scope.appliedProgram) {
$scope.LoanData.FinanceTimeInBusiness = _.findWhere($scope.TimeInBusiness, { TimeInBusinessID: $scope.appliedProgram.TimeInBusinessID });
if ($scope.LoanData.FinanceAmount < $scope.appliedProgram.MinAmount) {
$scope.LoanData.FinanceAmount = $scope.appliedProgram.MinAmount;
}
if ($scope.LoanData.FinanceAmount > $scope.appliedProgram.MaxAmount)
$scope.LoanData.FinanceAmount = $scope.appliedProgram.MaxAmount;
if (!_.isObject($scope.LoanData.FinanceTenure))
$scope.LoanData.FinanceTenure = _.findWhere($scope.appliedProgram.Terms, { Term: $scope.LoanData.FinanceTenure });
if (!_.isUndefined(callback))
callback();
} else {
appInfo.getFundingProgram(mapLoanData);
}
if (_.isFunction($rootScope.postLoanDataLoad))
$rootScope.postLoanDataLoad($scope);
}
appInfo.getFundingProgram(function () {
appInfo.getTimeInBusiness(mapLoanData, {
ProgramID: fundingConfig.ProgramID,
ProposalID: $scope.PartialApplications.ProposalID
});
}, true, fundingConfig);
} else {
appInfo.getFundingProgram(function () {
$scope.LoanData.FinanceTimeInBusiness = _.findWhere($scope.TimeInBusiness, { TimeInBusinessID: $scope.LoanData.FinanceTimeInBusiness });
if (!$scope.LoanData.FinanceTimeInBusiness && fundingConfig.ProgramID) {
appInfo.getTimeInBusiness(function () {
$scope.LoanData.FinanceTimeInBusiness = _.findWhere($scope.TimeInBusiness, { TimeInBusinessID: $scope.PartialApplications.LoanData.ApplicationHome.FinanceTimeInBusiness });
}, { ProgramID: fundingConfig.ProgramID });
}
$scope.LoanData.FinanceTenure = _.findWhere($scope.appliedProgram.Terms, { Term: $scope.LoanData.FinanceTenure });
if (!$scope.LoanData.FinanceTenure)
$scope.LoanData.FinanceTenure = _.last($rootScope.appliedProgram.Terms);
if (_.isFunction($rootScope.postLoanDataLoad))
$rootScope.postLoanDataLoad($scope);
});
}
}
$scope.LoanData.FinanceCredit = _.findWhere($rootScope.CreditScores, { CreditScoreID: $scope.LoanData.FinanceCredit });
$scope.$watch('FinancePurposeLoaded', function () {
for (var j in $rootScope.FinancePurposeData) {
if ($rootScope.FinancePurposeData[j].FinancePurposeID == $scope.LoanData.FinancePurpose) {
$scope.LoanData.FinancePurpose = $rootScope.FinancePurposeData[j];
}
}
});
// added for custome-quote page
setTimeout(function () {
$('#loanTerm option[label="' + $scope.LoanData.FinanceTenure + '"]').attr("selected", "selected");
var FinanceTenure = $('#loanTerm option[selected="selected"]').val();
$('#loanTerm').val(FinanceTenure).trigger('chosen:updated');
$('#PrimaryOwnerFinanceTimeInBusiness option[label="' + $scope.LoanData.FinanceTimeInBusiness.Title + '"]').attr("selected", "selected");
var FinanceTimeInBusiness = $('#PrimaryOwnerFinanceTimeInBusiness option[selected="selected"]').val();
$('#PrimaryOwnerFinanceTimeInBusiness').val(FinanceTimeInBusiness).trigger('chosen:updated');
}, 2000);
$timeout(function () {
//$scope.updateEMI();
$scope.ignoreEMIUpdate = false;
}, 500);
}
if (["custom-quote", "monthly-quote"].indexOf($state.current.name) > -1 && $state.params.proposalID) {
$scope.setRequestedFlow();
}
}
$scope.setRequestedFlow = function () {
if ($scope.SignIn && $scope.SignIn.UserDetails.UserTypeID != 4) {
$scope.showFlashMessage("error", "These links are reserved for the borrowers. Please use create new application and you can select desired workflow there.");
return $state.go('create-new-application');
}
switch ($state.params.proposalID) {
case 'selfcredit':
$scope.PartialApplications.DefaultAppWorkFlow = 'Selfcredit';
break;
case 'experianwithchooselender':
$scope.PartialApplications.DefaultAppWorkFlow = 'Experianwithchooselender';
break;
case 'experian':
$scope.PartialApplications.DefaultAppWorkFlow = 'Experian';
break;
case 'selfcreditwithchooselender':
$scope.PartialApplications.DefaultAppWorkFlow = 'SelfCreditWithChooseLender';
break;
case 'apply-now':
// Nothing to do
break;
default:
return false;
}
}
$scope.getPartialAppData = function (callback) {
var reqData = {
"GetPartialApplicationData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"PartialAppUID": $state.params.PartialAppUID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
Storage.setItem('PartialApplications', response.Data.PartialApplicationData);
// console.log(response.Data.PartialApplicationData);
$scope.mapPartialAppData();
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
};
var initPage = function () {
appInfo.getSignUpStaticData(function () {
$scope.stateName = $state.current.name;
if (!$scope.LoanData) {
$scope.resetPage();
}
if ($scope.viewPartial) {
switch ($scope.stateName) {
case 'view-partial':
$scope.getPartialAppData();
break;
case 'review-application':
$scope.mapPartialAppData();
if (_.isUndefined($scope.PartialApplications)) {
$state.go('create-account.ca-your-business');
}
else if (!_.isObject($scope.PartialApplications.Form3Data)) {
$state.go('create-account.ca-your-details');
}
break;
}
}
if ($scope.stateName == 'create-new-application') {
$scope.DefaultAppWorkFlow = _.findWhere($scope.ApplicationFlowOptions, { 'key': $scope.CompanyPreferences.DefaultAppWorkFlow });
}
if ($scope.stateName == 'signout')
$rootScope.Page.untrackLoading('sales-persons');
}, $scope.CompanyPreferences.DefaultProgramID);
}
if ($scope.CompanyPreferences)
initPage();
else
$rootScope.$on('company-loaded', initPage);
$scope.enableFields = function () {
$scope.dataEnable = true;
}
$scope.saveNewApplicationData = function () {
function saveApplication() {
var LoanData = Form3Data = Form2Data = {};
var Key = '';
if (['new-application', 'create-new-application'].indexOf($state.current.name) != -1) {
Key = "NewApplication";
} else {
Key = "SavePartialAppData";
if (!checkstatus('savePartialAppForm', $scope)) {
return focusOnErrorItem();
}
}
with ($scope.Business) {
var Form2Data = {
"SignUpBusiness2": {
Business_LegalStructureName: (LegalStructure && (typeof LegalStructure == 'object')) ? LegalStructure.LegalStructureID : null,
Business_Month: (Month && (typeof Month == 'object')) ? Month.key : null,
Business_Year: (Year && (typeof Year == 'object')) ? Year.Year : null,
Business_Address1: Address1,
Business_Address2: Address2,
Business_CityID: City,
Business_Postal: PostalCode,
Business_StateID: (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
Business_PhoneNumber: PhoneNumber,
Business_ContactName: ContactName,
Business_ContactNumber: ContactNumber,
Business_BusinessName: Name,
Business_DBA: DBA,
Business_TaxID: TaxID,
Business_IndustryTypes: (IndustryTypes && typeof IndustryTypes == 'object') ? IndustryTypes.IndustryTypeID : null,
Business_EquipmentDescription: $scope.Equipment.Description,
Business_PurposeOfPurchase: ($scope.Equipment.PurposeOfPurchase && typeof $scope.Equipment.PurposeOfPurchase == 'object') ? $scope.Equipment.PurposeOfPurchase.key : null,
}
};
if (IndustryTypes && [7, 23, 28].indexOf(IndustryTypes.IndustryTypeID) != -1) {
Form2Data.SignUpBusiness2.Business_MedicalLicense = $scope.Medical.License;
Form2Data.SignUpBusiness2.Business_MedicalLicenseIssueDate = $scope.Medical.LicenseIssueDate;
Form2Data.SignUpBusiness2.Business_MedicalLicenseStateID = ($scope.Medical.LicenseIssueState && typeof $scope.Medical.LicenseIssueState == 'object') ? $scope.Medical.LicenseIssueState.StateID : null;
Form2Data.SignUpBusiness2.Business_MedicalSpecialityDescription = $scope.Medical.SpecialityDescription;
}
}
with ($scope.PrimaryOwner) {
var Form3Data = {
"SignUpBusiness3": {
"Users_FirstName": FirstName,
"Users_LastName": LastName,
"Users_Email": Email,
"Users_MobileNumber": MobileNumber,
"Users_Address1": Address1,
"Users_Address2": Address2,
"Users_CityID": City,
"Users_StateID": (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
"Users_Postal": PostalCode,
"Users_SocialSecurityNumber": SocialSecurityNumber,
"Users_PercentageOwnership": PercentageOwnership,
}
};
var AdditionalOwners = {};
if ($scope.BusinessPartners.length) {
Form3Data.SignUpBusiness3.AdditionalOwners = $scope.BusinessPartners;
}
else {
Form3Data.SignUpBusiness3.AdditionalOwners = [];
}
if (SocialSecurityNumber && SocialSecurityNumber.length)
Form3Data.SignUpBusiness3.Users_SocialSecurityNumberView = '***-**-' + SocialSecurityNumber.substr(SocialSecurityNumber.length - 4, 4);
}
with ($scope.LoanData) {
var minAmount = $rootScope.CompanyPreferences.MinAmount;
var maxAmount = $rootScope.CompanyPreferences.MaxAmount;
if (isNaN(FinanceAmount)) {
$scope.LoanData.FinanceAmount = $rootScope.CompanyPreferences.DefaultAmount;
} else if (FinanceAmount > maxAmount || FinanceAmount < minAmount) {
$scope.showFlashMessage('error', $rootScope.CompanyPreferences.CompanyName + " provides loan in from $ " +
minAmount.formatMoney() + ' upto $ ' + maxAmount.formatMoney());
$scope.LoanData.FinanceAmount = oldValue;
} else {
LoanData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : "1",
"FinanceAmount": (FinanceAmount) ? FinanceAmount : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (typeof FinanceTenure == 'object')) ? FinanceTenure.Term : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": (FinanceTimeInBusiness && (typeof FinanceTimeInBusiness == 'object')) ? FinanceTimeInBusiness.TimeInBusinessID : $rootScope.CompanyPreferences.DefaultTimeInBusinessID,
});
LoanData.ProgramLoanType = (typeof ProgramLoanType == "undefined") ? $scope.CompanyPreferences.LoanType : ProgramLoanType;
}
}
var reqData = {};
reqData[Key] = {
"LoginSessionKey": ($rootScope.SignIn) ? $rootScope.SignIn.LoginSessionKey : null,
"Form": "All",
"Form2Data": Form2Data,
"Form3Data": Form3Data,
"LoanData": { "ApplicationHome": LoanData },
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
};
if (reqData.NewApplication) {
reqData.NewApplication["DefaultAppWorkFlow"] = $scope.DefaultAppWorkFlow;
reqData.NewApplication["AssigneeID"] = ($rootScope.SignIn.UserDetails.UserTypeID != '3' && $scope.SalesPerson) ? $scope.SalesPerson.ID : null;
reqData.NewApplication["EmailInfo"] = [{
"FirstName": $scope.PrimaryOwner.FirstName,
"LastName": $scope.PrimaryOwner.LastName,
"Email": $scope.PrimaryOwner.Email
}];
reqData.NewApplication["Form1Data"] = {
"SignUpBusiness1": {
"Login_LoginKeyword": $scope.PrimaryOwner.Email
}
};
reqData.NewApplication.MailSubject = $scope.mailSubject;
reqData.NewApplication.MailDescription = $scope.mailDescription;
}
if (reqData.SavePartialAppData) {
reqData.SavePartialAppData["PartialAppUID"] = $scope.PartialApplications.PartialAppUID;
var Form1Data = {
'SignUpBusiness1': {
'Login_LoginKeyword': $scope.Login.LoginKeyword,
"Login_Password": $scope.Login.Password,
"Users_StateID": $scope.Login.StateID ? $scope.Login.StateID.StateID : null
}
};
reqData.SavePartialAppData["Form1Data"] = Form1Data;
reqData.SavePartialAppData["CompanyID"] = $rootScope.CompanyPreferences.CompanyID;
};
if (reqData.NewApplication) {
if ($state.current.name == 'new-application') {
if (!reqData.NewApplication.Form1Data.SignUpBusiness1.Login_LoginKeyword) {
$scope.showFlashMessage('error', 'Borrower Email is required');
angular.element('#BOemailCtrlID').focus();
return false;
}
}
else if ($state.current.name == 'create-new-application') {
if (!$scope.PrimaryOwner.FirstName) {
$scope.showFlashMessage('error', 'Borrower First Name is required');
angular.element('#OwnerFirstName').focus();
return false;
}
else if (!$scope.PrimaryOwner.LastName) {
$scope.showFlashMessage('error', 'Borrower Last Name is required');
angular.element('#OwnerLastName').focus();
return false;
}
}
}
if (_.isFunction($scope.prePartialAppSubmit))
$scope.prePartialAppSubmit(reqData, $scope);
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
if ($state.current.name == 'new-application') {
$scope.resetPage();
} else {
$scope.PartialApplications.LoanData = reqData[Key].LoanData;
$scope.PartialApplications.Form1Data = reqData[Key].Form1Data;
$scope.PartialApplications.Form2Data = reqData[Key].Form2Data;
$scope.PartialApplications.Form3Data = reqData[Key].Form3Data;
$scope.PartialApplications.PartialAppUID = response.Data;
if ($state.current.name == 'create-new-application') {
$scope.dataRequired = true;
}
Storage.setItem('PartialApplications', $scope.PartialApplications);
$scope.dataEnable = false;
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.loading = false;
});
}
if ($state.current.name == 'new-application') {
if (checkstatus('savePartialAppForm')) {
saveApplication();
}
else
return false;
}
else
saveApplication();
}
$scope.submitApplicationData = function () {
if ($scope.PartialApplications.acceptedTerms) {
var LoanData = Form3Data = Form2Data = {};
if ($scope.PartialApplications.LoanData.ApplicationHome.ProgramLoanType == 'Business') {
with ($scope.Business) {
Form2Data = {
"BusinessData": {
LegalStructureID: (LegalStructure && (typeof LegalStructure == 'object')) ? LegalStructure.LegalStructureID : null,
EstablishedMonth: (Month && (typeof Month == 'object')) ? Month.key : null,
EstablishedYear: (Year && (typeof Year == 'object')) ? Year.Year : null,
Address1: Address1,
Address2: Address2,
CityID: City,
Postal: PostalCode,
StateID: (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
PhoneNumber: PhoneNumber,
PrimaryContactName: ContactName,
PrimaryContactNumber: ContactNumber,
BusinessName: Name,
BusinessDBA: DBA,
TaxID: TaxID,
// IndustryTypes:(IndustryTypes && typeof IndustryTypes == 'object')?IndustryTypes.IndustryTypeID:$rootScope.CompanyPreferences.DefaultIndustrySelected,
IndustryTypes: [],
EquipmentDescription: $scope.Equipment.Description,
PurposeOfPurchase: ($scope.Equipment.PurposeOfPurchase && typeof $scope.Equipment.PurposeOfPurchase == 'object') ? $scope.Equipment.PurposeOfPurchase.key : null,
}
};
var medicalDetailsRequired = false;
if (_.isArray($scope.Business.IndustryTypes) && $scope.Business.IndustryTypes.length) {
for (var i in $scope.Business.IndustryTypes) {
Form2Data.BusinessData.IndustryTypes.push($scope.Business.IndustryTypes[i].IndustryTypeID);
if (!medicalDetailsRequired && [7, 23, 28].indexOf($scope.Business.IndustryTypes[i].IndustryTypeID) != -1) {
medicalDetailsRequired = true;
}
}
} else if ($scope.CompanyPreferences.DefaultIndustrySelected) {
Form2Data.BusinessData.IndustryTypes.push($scope.CompanyPreferences.DefaultIndustrySelected);
medicalDetailsRequired = [7, 23, 28].indexOf($scope.CompanyPreferences.DefaultIndustrySelected) != -1;
} else {
Form2Data.BusinessData.IndustryTypes.push($scope.Business.IndustryTypes.IndustryTypeID);
if (!medicalDetailsRequired && [7, 23, 28].indexOf($scope.Business.IndustryTypes.IndustryTypeID) != -1) {
medicalDetailsRequired = true;
}
}
if (medicalDetailsRequired && _.isObject($scope.Medical)) {
Form2Data.BusinessData.MedicalLicense = $scope.Medical.License;
Form2Data.BusinessData.MedicalLicenseIssueDate = $scope.Medical.LicenseIssueDate;
Form2Data.BusinessData.MedicalLicenseStateID = ($scope.Medical.LicenseIssueState && typeof $scope.Medical.LicenseIssueState == 'object') ? $scope.Medical.LicenseIssueState.StateID : null;
Form2Data.BusinessData.MedicalSpecialityDescription = $scope.Medical.SpecialityDescription;
}
}
}
with ($scope.PrimaryOwner) {
Form3Data = {
"UserData":
{
"FirstName": FirstName,
"LastName": LastName,
"Email": Email,
"MobileNumber": MobileNumber,
"Address1": Address1,
"Address2": Address2,
"CityID": City,
"StateID": (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
"ShortCode": (StateID && (typeof StateID == 'object')) ? StateID.ShortCode : null,
"Postal": PostalCode,
"SocialSecurityNumber": SocialSecurityNumber,
"PercentageOwnership": PercentageOwnership
}
};
var AdditionalOwners = {};
if ($scope.PartialApplications.LoanData.ApplicationHome.ProgramLoanType == 'Business') {
if ($scope.BusinessPartners && $scope.BusinessPartners.length) {
Form3Data.UserData.AdditionalOwners = $scope.BusinessPartners;
}
}
if (SocialSecurityNumber && SocialSecurityNumber.length)
Form3Data.Users_SocialSecurityNumberView = '***-**-' + SocialSecurityNumber.substr(SocialSecurityNumber.length - 4, 4);
}
with ($scope.LoanData) {
var finAmount = $scope.LoanData.FinanceAmount;
var minAmount = $rootScope.CompanyPreferences.MinAmount;
var maxAmount = $rootScope.CompanyPreferences.MaxAmount;
if (isNaN(finAmount)) {
finAmount = $rootScope.CompanyPreferences.DefaultAmount;
} else {
LoanData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : "1",
"FinanceAmount": (FinanceAmount) ? finAmount : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (typeof FinanceTenure == 'object')) ? FinanceTenure.Term : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": (FinanceTimeInBusiness && (typeof FinanceTimeInBusiness == 'object')) ? parseInt(FinanceTimeInBusiness.TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID
});
LoanData.ProgramLoanType = _.isUndefined(ProgramLoanType) ? $scope.CompanyPreferences.LoanType : ProgramLoanType;
if ($scope.appliedProgram.ProgramLoanType == 'Personal') {
LoanData.FinancePurposeID = [];
for (var i in $scope.LoanData.FinancePurpose) {
if (typeof $scope.LoanData.FinancePurpose[i] == 'object')
LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i].FinancePurposeID);
else
LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i]);
}
}
}
}
if ($scope.LoanData.ProgramLoanType == 'Both') {
$scope.LoanData.ProgramLoanType = $scope.CompanyPreferences.LoanType2;
}
$scope.dataEnable = TRUE;
if (LoanData && checkstatus('savePartialAppForm', $scope)) {
if ($state.current.name == 'create-new-application') {
var ApiName = 'SignUpForAdmin';
}
else {
var ApiName = 'SignUp';
}
$scope.dataEnable = FALSE;
var reqData = {};
reqData[ApiName] = {
"Login_LoginKeyword": $scope.Login.LoginKeyword,
"Login_Password": $scope.Login.Password,
"Users_StateID": ($scope.Login.StateID) ? $scope.Login.StateID.StateID : null,
"AdditionalOwners": null,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"DeviceType": 'Web',
"SocialType": 'Web',
"DeviceID": 'Web',
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"Latitude": null,
"Longitude": null,
"PartialAppUID": $scope.PartialApplications.PartialAppUID,
"NewApplicationType": null,
"DefaultAppWorkFlow": $scope.PartialApplications.DefaultAppWorkFlow,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"NoEmailRequired": $scope.PartialApplications.NoEmailRequired
};
for (var key in LoanData)
reqData[ApiName][key] = LoanData[key];
for (var key in Form3Data)
reqData[ApiName][key] = Form3Data[key];
for (var key in Form2Data)
reqData[ApiName][key] = Form2Data[key];
if ($rootScope.SignIn) {
reqData[ApiName].NewApplicationType = 'Prefill';
reqData[ApiName].LoginSessionKey = $rootScope.SignIn.LoginSessionKey;
}
if ($scope.SalesPerson) {
reqData[ApiName].AssigneeID = $scope.SalesPerson.ID;
}
if (!$rootScope.SignIn)
reqData[ApiName].AutoLogin = TRUE;
$scope.Page.trackLoading('go-to-application');
appInfo.getServerData(reqData).then(function (response) {
if ([200, 201].indexOf(response.ResponseCode) != -1) {
$scope.showFlashMessage('success', response.Message);
/*Call thank you page - start*/
if (!$rootScope.SignIn) {
appInfo.processApplicationLogin(response);
}
var CompletedApplication = { ApplicationNumber: response.Data.ApplicationNumber, Email: $scope.Login.LoginKeyword, 'PrimaryPhoneNumber': $rootScope.CompanyPreferences.PrimaryPhoneNumber };
Storage.setItem('CompletedApplication', CompletedApplication);
/*Call thank you page - end*/
/*Clear cache of application data - stars*/
var ApplicationData = {
ApplicationNumber: response.Data.ApplicationNumber,
'FetchPreOfferFields': response.Data.isAdditionalInfoRequiredBeforeOffer,
'ApplicationWorkFlow': $scope.PartialApplications.ApplicationWorkFlow ? $scope.PartialApplications.ApplicationWorkFlow : $scope.PartialApplications.DefaultAppWorkFlow,
"LoanData": {
"CreditScore": LoanData,
"FinanceTenure": LoanData.FinanceTenure
}
};
Storage.setItem('ApplicationData', ApplicationData);
/*Clear cache of application data - end*/
//redirect to third party site from where partial app created
if (response.Data.ThirdParty) {
$rootScope.callback = response.Data.ThirdParty;
window.location.href = response.Data.ThirdParty;
}
if (response.Data.isAdditionalInfoRequiredBeforeOffer) {
$state.go('additional-information');
} else if (($scope.PartialApplications.ApplicationWorkFlow ? $scope.PartialApplications.ApplicationWorkFlow : $scope.PartialApplications.DefaultAppWorkFlow) == "SelfCreditWithChooseLender") {
$state.go('financing-offers');
} else {
$state.go('application-submited');
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('go-to-application');
});
} else {
focusOnErrorItem();
}
} else {
$scope.showFlashMessage('error', 'Please accept the term to continue application process.');
}
}
}])
// Email Application Controller
.controller('emailAppCtrl', ['$rootScope', '$scope', 'appInfo', '$timeout', 'ngDialog', '$location', function ($rootScope, $scope, appInfo, $timeout, ngDialog, $location) {
$scope.partialAppURL = null;
$scope.SelectedProgram = null;
$scope.CalcData = {};
$scope.getProgramsList = function () {
$scope.DefaultAppWorkFlow = _.findWhere($scope.ApplicationFlowOptions, { 'key': $scope.CompanyPreferences.DefaultAppWorkFlow });
var reqData = {
"GetProgramsList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"AssociatedProgramFlag": true,
"Filter": {
"StatusID": 25,
"IndustryTypeID": null
}
}
};
$rootScope.Page.trackLoading('programs-list');
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.ProgramList = response.Data.Programs;
for (var i in $scope.ProgramList) {
$scope.ProgramList[i].showData = $scope.ProgramList[i].Title + ', ' + $scope.ProgramList[i].CompanyName;
}
$scope.SelectedProgram = _.findWhere($scope.ProgramList, { ProgramID: $scope.CompanyPreferences.DefaultProgramID });
if (_.isUndefined($scope.SelectedProgram) && $rootScope.CompanyPreferences.Category == "Bank") {
$location.path('/programs/list');
$scope.showFlashMessage('error', "You must set a Default Program.");
}
if (_.isUndefined($scope.SelectedProgram)) {
$scope.SelectedProgram = $scope.ProgramList[0];
}
$timeout(function () {
// $scope.CalcData.FinanceTenure=_.findWhere($scope.appliedProgram.Terms,{Term:$scope.CompanyPreferences.DefaultLoanTerm});
$('#effectiveProgram').trigger('chosen:updated');
}, 500);
} else {
$scope.showFlashMessage('error', response.Message);
}
$rootScope.Page.untrackLoading('programs-list');
});
}
$scope.updateEMI = _.debounce(function () {
if ($scope.SelectedProgram && $scope.CalcData.FinanceAmount) {
with ($scope.CalcData) {
var LoanData = appInfo.getCalcData({
"FinancePurposeID": 1,
"FinanceCredit": CreditScoreID ? CreditScoreID : 1,
"FinanceAmount": (FinanceAmount) ? (FinanceAmount + '').replace(',', '') : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (typeof FinanceTenure == 'object')) ? FinanceTenure.Term : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": TimeInBusinessID ? parseInt(TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID,
"ShowConfigurationError": true,
"CommissionPoints": Commission
});
$scope.CalcData.AmountPayable = LoanData.AmountPayable;
if (!$scope.$$phase)
$scope.$apply();
$scope.getVendorProfit();
}
return LoanData;
}
}, 100);
$scope.mapProgramData = function (ProgramID) {
$scope.CalcData.FinanceAmount = $rootScope.CompanyPreferences.DefaultAmount;
// $scope.CalcData.FinanceTenure=$scope.CompanyPreferences.DefaultLoanTerm;
$scope.CalcData.FinanceTenure = _.findWhere($scope.appliedProgram.Terms, { Term: $scope.CompanyPreferences.DefaultLoanTerm });
$scope.CalcData.FinanceTenure = ($scope.CalcData.FinanceTenure) ? $scope.CalcData.FinanceTenure : 13;
$scope.CalcData.Commission = $scope.SelectedProgram.VendorSideCommissionCap ? $scope.SelectedProgram.VendorSideCommissionCap : $scope.SelectedProgram.PartnerSideCommissionCap;
$scope.CalcData.CreditScoreID = $rootScope.appliedProgram.CreditScoreID;
$scope.CalcData.TimeInBusinessID = $rootScope.appliedProgram.TimeInBusinessID;
prepareSliderConfiguration();
$scope.updateEMI();
}
$scope.setStep = function () {
var amount = (typeof $scope.price == 'string') ? $scope.LoanData.FinanceAmount.replace(',', '') : $scope.price;
var step = 1;
if (amount % 10 > 0) {
step = 1;
} else if ((amount % 100) / 10 > 0) {
step = 10;
} else if ((amount % 1000) / 100 > 0) {
step = 100;
} else {
step = 1000;
}
return step;
}
var prepareSliderConfiguration = function () {
$scope.minAmount = $scope.SelectedProgram.MinAmountRange;
$scope.maxAmount = $scope.SelectedProgram.MaxAmountRange;
$scope.minTerm = $scope.SelectedProgram.MinTenure;
$scope.maxTerm = $scope.SelectedProgram.MaxTenure;
$scope.amountSliderConfig = {
min: $scope.minAmount,
max: $scope.maxAmount,
filter: 'currency:undefined:2',
step: $scope.setStep(),
}
$scope.termConfig = {
min: $scope.minTerm,
max: $scope.maxTerm,
mask: "00M",
matchObjectKeyValue: 'Term',
objectDataPoolSource: $rootScope.appliedProgram.Terms,
step: 12
}
}
if ($rootScope.CompanyPreferences)
$scope.getProgramsList();
else
$rootScope.$on('company-loaded', $scope.getProgramsList);
$scope.updateMatchingEmails = _.debounce(function (typed) {
$scope.matchingEmails = [];
$scope.matchedRecords = null;
if (typed) {
var reqData = {
"suggestEmail": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Email": typed
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
for (var i in response.Data.Contacts) {
$scope.matchedRecords = response.Data.Contacts;
$scope.matchingEmails[i] = response.Data.Contacts[i].email;
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}, 200);
$scope.setRelatedName = function (e) {
$scope.selectedSuggestion = $scope.matchedRecords[this.getIndex()];
};
$scope.sendMail = function () {
var mailData = this;
if (checkstatus('frmEmailApplication', $scope)) {
var finAmount = $scope.CalcData.FinanceAmount;
var minAmount = $rootScope.CompanyPreferences.MinAmount;
var maxAmount = $rootScope.CompanyPreferences.MaxAmount;
if (isNaN(finAmount)) {
finAmount = $rootScope.CompanyPreferences.DefaultAmount;
}
var LoanData = appInfo.getCalcData({
"FinancePurposeID": 1,
"FinanceCredit": $rootScope.CompanyPreferences.DefaultCreditScoreID,
"FinanceAmount": finAmount,
"FinanceTenure": $scope.CalcData.FinanceTenure ? $scope.CalcData.FinanceTenure.Term : null,
"FinanceTimeInBusiness": $rootScope.CompanyPreferences.DefaultTimeInBusinessID
});
if (LoanData) {
if ($scope.SelectedProgram) {
LoanData.ProgramID = $scope.SelectedProgram.ProgramID;
}
var reqData = {
"EmailApplication": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Email": mailData.taggedEmail,
"FirstName": $scope.selectedSuggestion.FirstName,
"LastName": $scope.selectedSuggestion.LastName,
"SenderMessage": mailData.senderMessage,
"MailSubject": mailData.mailSubject,
"LoanData": LoanData,
"ApplicationWorkFlow": $scope.DefaultAppWorkFlow ? $scope.DefaultAppWorkFlow['key'] : $rootScope.CompanyPreferences.DefaultAppWorkFlow
}
};
if ($scope.selectedSuggestion && $scope.selectedSuggestion.email == mailData.taggedEmail && $scope.selectedSuggestion.Type == 'Borrower') {
reqData.EmailApplication.BorrowerID = $scope.selectedSuggestion.ID;
}
if (_.isFunction($scope.preEmailApplicationSend) && !$scope.preEmailApplicationSend(reqData, $scope))
return false;
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
if (_.isFunction($scope.postEmailApplicationSend))
$scope.postEmailApplicationSend(reqData, $scope);
$scope.partialAppURL = $rootScope.siteURL + 'applications/ViewPartial/' + response.Data.PartialAppUID;
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-Unique-link.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope
});
$scope.taggedEmail = $scope.selectedSuggestion.FirstName = $scope.selectedSuggestion.LastName = $scope.senderMessage = $scope.financeAmount = $scope.mailSubject = '';
} else {
$scope.showFlashMessage('error', response.Message);
}
// angular.element('#financeAmount').val('');
});
}
}
}
$scope.$watch('SelectedProgram', function (newVal, oldVal) {
if (newVal != oldVal) {
appInfo.getFundingProgram($scope.mapProgramData, true, {
TimeInBusinessID: $rootScope.CompanyPreferences.DefaultTimeInBusinessID,
CreditScoreID: $rootScope.CompanyPreferences.DefaultCreditScoreID,
ProgramID: newVal.ProgramID,
ProgramLoanType: ($scope.CompanyPreferences.LoanType == 'Both') ? 'Business' : $scope.CompanyPreferences.LoanType,
UsingDefault: FALSE
});
}
});
$scope.$watch('CalcData.FinanceAmount', _.debounce(function (newValue, oldValue) {
if (newValue && newValue != oldValue && !$scope.ignoreEMIUpdate) {
if (newValue.length < 5 || !$scope.updateEMI()) {
$scope.errorFinanceAmount = 'Minimum required amount is $ ' + $rootScope.appliedProgram.MinAmount.formatMoney();
$scope.CalcData.AmountPayable = null;
}
else {
$scope.errorFinanceAmount = '';
// if(!$scope.updateEMI())
// $scope.LoanData.FinanceAmount=oldValue;
}
}
}, 500));
$scope.$watch('CalcData.FinanceTenure', function (newValue, oldValue) {
if (angular.isObject(newValue) && !angular.equals(newValue, oldValue)) {
if (!$scope.updateEMI()) {
$scope.SelectedProgram.FinanceTenure = oldValue;
}
}
});
$scope.getVendorProfit = function () {
var AmountPayable = $scope.CalcData.AmountPayable;
with ($scope.CalcData) {
var WithoutCommissionLoanData = appInfo.getCalcData({
"FinancePurposeID": 1,
"FinanceCredit": CreditScoreID ? CreditScoreID : 1,
"FinanceAmount": (FinanceAmount) ? (FinanceAmount + '').replace(',', '') : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (typeof FinanceTenure == 'object')) ? FinanceTenure.Term : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": TimeInBusinessID ? parseInt(TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID,
"ShowConfigurationError": true,
"withoutCommission": true
});
if (!$scope.$$phase)
$scope.$apply();
}
var FinanceTenure = (typeof $scope.CalcData.FinanceTenure == 'object') ? $scope.CalcData.FinanceTenure.Term : $scope.CalcData.FinanceTenure
$scope.CalcData.VendorProfit = (parseInt(AmountPayable) * FinanceTenure) - (parseInt(WithoutCommissionLoanData.AmountPayable) * FinanceTenure);
}
}])
// SignUp Application Controller
.controller('SignUpApplicationController', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', '$state', 'Storage', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, $state, Storage) {
$scope.applyCheckBoxBg = function () {
var Currentselected = $scope.Business.IndustryTypes.Name;
}
$scope.isActive = function (route) {
return route === $location.path();
}
$scope.$parent.editLoanData = function () {
Storage.setItem('WizardReferrer', $location.path());
$location.path('/custom-quote/');
}
$scope.goBack = function () {
$location.path('/partial-application');
};
$scope.setStep = function () {
var amount = (typeof $scope.price == 'string') ? $scope.LoanData.FinanceAmount.replace(',', '') : $scope.price;
var step = 1;
if (amount % 10 > 0) {
step = 1;
} else if ((amount % 100) / 10 > 0) {
step = 10;
} else if ((amount % 1000) / 100 > 0) {
step = 100;
} else {
step = 1000;
}
return step;
}
$scope.$parent.prepareSliderConfiguration = function () {
if (!$scope.LoanData || !$scope.appliedProgram)
return false;
$scope.minAmount = $scope.appliedProgram.MinAmount;
$scope.maxAmount = $scope.appliedProgram.MaxAmount;
if ($scope.LoanData.FinanceAmount > $scope.maxAmount) {
$scope.LoanData.FinanceAmount = $scope.maxAmount;
}
$scope.minTerm = $scope.appliedProgram.Terms[0].Term;
$scope.maxTerm = $scope.appliedProgram.Terms[$scope.appliedProgram.Terms.length - 1].Term;
$scope.amountSliderConfig = {
min: $scope.minAmount,
max: $scope.maxAmount,
filter: 'currency:undefined:2',
step: $scope.setStep(),
}
$scope.termConfig = {
min: $scope.minTerm,
max: $scope.maxTerm,
mask: "00M",
matchObjectKeyValue: 'Term',
objectDataPoolSource: $rootScope.appliedProgram.Terms,
step: 12
}
$scope.setRequestedLoanFromURL($scope);
}
$scope.prepareSliderConfig = function () {
if ($scope.appliedProgram) {
$scope.prepareSliderConfiguration();
} else if (!$scope.CompanyPreferences) {
$rootScope.$on('company-loaded', $scope.prepareSliderConfiguration);
} else {
appInfo.getFundingProgram($scope.prepareSliderConfiguration);
}
}
$scope.setForm3Default = function () {
if ($scope.PartialApplications.Form2Data) {
if (!$scope.PartialApplications.Form3Data)
$scope.PartialApplications.Form3Data = { SignUpBusiness3: {} }
if (!$scope.PrimaryOwner)
$scope.PrimaryOwner = {};
if (!$scope.PrimaryOwner.Email)
$scope.PrimaryOwner.Email = $scope.PartialApplications.Form3Data.SignUpBusiness3.Email = $scope.Login.LoginKeyword;
if (!$scope.PrimaryOwner.FirstName && $scope.Business.ContactName) {
var n = $scope.Business.ContactName.split(' ');
$scope.PrimaryOwner.FirstName = $scope.PartialApplications.Form3Data.SignUpBusiness3.FirstName = n[0];
if (n[1])
$scope.PrimaryOwner.LastName = $scope.PartialApplications.Form3Data.SignUpBusiness3.LastName = n[1];
}
}
if (_.isFunction($scope.afterSettingForm3Default)) {
$scope.afterSettingForm3Default($scope);
}
}
$scope.loadAppData = function () {
if ($state.params.linkSource) {
var tokens = $state.params.linkSource.split('/');
if (tokens.length < 3) {
$location.path('/custom-quote/');
return;
}
tokens[1] = parseInt(tokens[1]);
tokens[2] = parseInt(tokens[2]);
setTimeout(function () {
$scope.LoanData.FinanceAmount = tokens[1];
$scope.LoanData.FinanceCredit = $rootScope.CreditScores[0];
$scope.LoanData.FinanceTimeInBusiness = $rootScope.TimeInBusiness[1];
$scope.LoanData.FinanceTenure = _.findWhere($rootScope.appliedProgram.Terms, { Term: parseInt(tokens[2]) });
$scope.updateEMI();
$scope.PartialApplications = {
LoanData: { ApplicationHome: { FinanceAmount: tokens[1], FinanceTenure: tokens[2], FinanceTimeInBusiness: 2, FinanceCredit: 1, FinancePurpose: 1 } },
Form1Data: null, Form2Data: null, Form3Data: null
};
Storage.setItem('PartialApplications', $scope.PartialApplications);
$location.$$url = '/create-account';
}, 500);
}
$scope.mapPartialAppData($scope.prepareSliderConfig);
if (_.isUndefined($scope.LoanData))
$scope.resetPage();
switch ($state.current.name) {
case 'monthly-quote':
case 'custom-quote':
if ($state.params.proposalID) {
if ($rootScope.SignIn)
$scope.newApplication($state.params.proposalID);
else if ($scope.setRequestedFlow() === false) {
var reqdata = {
"GetProposedQuote": {
"ProposalID": $state.params.proposalID,
"Referrer": document.referrer,
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"LoginSessionKey": ($rootScope.SignIn) ? $rootScope.SignIn.LoginSessionKey : null
}
};
appInfo.getServerData(reqdata).then(function (response) {
if (response.ResponseCode == 200) {
Storage.setItem("PartialApplications", response.Data);
$rootScope.CustomConfig = true;
$scope.mapPartialAppData($scope.prepareSliderConfig);
} else {
$scope.showFlashMessage("error", response.Message);
$scope.LoanData.FinanceTimeInBusiness = _.findWhere($rootScope.TimeInBusiness, { TimeInBusinessID: $scope.CompanyPreferences.DefaultTimeInBusinessID });
}
});
}
} else if (!$scope.PartialApplications) {
appInfo.getSignUpStaticData(function () {
$scope.LoanData.FinanceTenure = _.findWhere($scope.appliedProgram.Terms, { Terms: $scope.CompanyPreferences.DefaultLoanTerm });
$scope.LoanData.FinanceCredit = _.findWhere($scope.CreditScores, { CreditScoreID: $scope.CompanyPreferences.DefaultCreditScoreID });
$scope.LoanData.FinanceTimeInBusiness = _.findWhere($rootScope.TimeInBusiness, { TimeInBusinessID: $scope.CompanyPreferences.DefaultTimeInBusinessID });
if (!$scope.$$pharse && !_.isUndefined($scope.$$pharse))
$scope.$apply();
}, $scope.CompanyPreferences.DefaultProgramID);
}
break;
case 'create-account.ca-create-account':
if (!$scope.PartialApplications || !$scope.PartialApplications.LoanData)
$location.path('/custom-quote/');
break;
case 'create-account.ca-your-business':
if (!$scope.PartialApplications || !$scope.PartialApplications.Form1Data) {
$location.path('/create-account');
}
$timeout(function () {
$scope.$apply();
}, 1000);
break;
case 'create-account.ca-your-details':
if (!$scope.PartialApplications || !$scope.PartialApplications.Form1Data)
$location.path('/create-account/your-business');
$scope.setForm3Default();
break;
case 'create-proposal.proposal-review-send-tab':
break;
case 'home':
if ($rootScope.hideEMI) {
delete $rootScope.hideEMI;
}
Storage.removeItem('PartialApplications');
$scope.resetPage();
break;
default:
if ($rootScope.CustomConfig)
appInfo.getFundingProgram(function () {
if ($scope.PartialApplications && $state.current.name == 'borrower-view-rate' && $scope.PartialApplications.LoanData.ApplicationHome.FinanceAmount)
return;
$scope.resetPage();
}, true, {
ProgramID: $scope.CompanyPreferences.DefaultProgramID,
UsingDefault: true
});
}
if ($scope.appliedProgram) {
$scope.prepareSliderConfig();
}
$scope.term = $rootScope.CompanyPreferences.DefaultLoanTerm;
$timeout(function () { // Slow network patch
if (!$scope.updateEMI() && (_.isUndefined($scope.LoanData) || _.isUndefined($scope.LoanData.FinanceAmount))) {
$scope.resetPage();
$scope.prepareSliderConfig();
}
}, 1500);
}
angular.element('#financeAmount').keyup(function (e) {
$scope.amountSliderConfig.step = $scope.setStep();
});
var initprocessing = function () {
var PartialApplications = Storage.getItem('PartialApplications');
var settings = null;
if (PartialApplications && _.isNull(PartialApplications.ThirdParty)) {
settings = {
// TimeInBusinessID:PartialApplications.LoanData.ApplicationHome.FinanceTimeInBusiness.TimeInBusinessID,
TimeInBusinessID: (PartialApplications.LoanData.ApplicationHome.FinanceTimeInBusiness && (typeof PartialApplications.LoanData.ApplicationHome.FinanceTimeInBusiness == 'object')) ? parseInt(PartialApplications.LoanData.ApplicationHome.FinanceTimeInBusiness.TimeInBusinessID) : PartialApplications.LoanData.ApplicationHome.FinanceTimeInBusiness,
CreditScoreID: PartialApplications.LoanData.ApplicationHome.FinanceCredit,
ProgramID: $rootScope.CompanyPreferences.DefaultProgramID,
ProgramLoanType: ($scope.CompanyPreferences.LoanType == 'Both') ? $rootScope.CompanyPreferences.ProgramLoanType : $scope.CompanyPreferences.LoanType,
UsingDefault: FALSE
}
} else {
settings = {
ProgramID: $scope.CompanyPreferences.DefaultProgramID,
UsingDefault: true
}
}
appInfo.getFundingProgram(function () {
switch ($location.path()) {
case '/application-submited':
Storage.removeItem('PartialApplications');
$scope.CompletedApplication = Storage.getItem('CompletedApplication');
Storage.removeItem('CompletedApplication');
if (!$scope.CompletedApplication)
$location.path('/custom-quote/');
var redirectTimer = setTimeout(function () {
if ($rootScope.SignIn)
$location.path($scope.CompletedApplication.RequiredDocuments ? '/app-details/documents/' + $scope.CompletedApplication.ApplicationNumber : '/applications');
else
$location.path('/SignIn');
$scope.$apply();
}, 8000);
$rootScope.$on('$stateChangeStart', function () {
clearTimeout(redirectTimer);
});
return;
case '/':
case '/signout':
Storage.removeItem('PartialApplications');
if ($rootScope.CompanyPreferences.Category == "Company") {
appInfo.getFundingProgram(function () {
$scope.resetPage();
$scope.prepareSliderConfig();
}, TRUE, {
ProgramID: $scope.CompanyPreferences.DefaultProgramID,
UsingDefault: true
});
}
}
appInfo.getSignUpStaticData($scope.loadAppData, $rootScope.CompanyPreferences.DefaultProgramID);
}, true, settings);
}
if ($rootScope.CompanyPreferences)
appInfo.getSalesPersons(function () {
$scope.SSNNotRequiredFlag = TRUE;
initprocessing();
});
else {
$rootScope.$on('company-loaded', initprocessing);
}
$scope.$parent.stateName = $state.current.name;
$scope.saveSignAppData = function (targetURL) {
if (['create-account.ca-your-details'].indexOf($state.current.name) != -1) {
for (var i in $scope.BusinessPartners) {
for (var j in $rootScope.stateData) {
if ($scope.BusinessPartners[i].StateID.StateID == $scope.stateData[j].StateID)
$scope.BusinessPartners[i].StateID = $rootScope.stateData[j];
}
}
}
console.log("$state.current.name",$state.current.name)
switch ($state.current.name) {
case 'create-account.ca-create-account':
var FormNo = 'Form1';
if (!checkstatus('frmCreateAccount', $scope))
return false;
break;
case 'create-account.ca-your-business':
var FormNo = 'Form2';
if (!checkstatus('frmSignUpBusiness', $scope)) {
focusOnErrorItem();
return false;
}
if ($scope.PartialApplications.Form3Data) {
$scope.Business.totalOwnership = $scope.PartialApplications.Form3Data.SignUpBusiness3.Users_PercentageOwnership;
}
break;
case 'home':
case 'calculator':
case 'signout':
case 'signin':
case 'recovery':
if ($scope.CompanyPreferences.DefaultAppWorkFlow && ['selfcredit', 'selfcreditwithchooselender'].indexOf($scope.CompanyPreferences.DefaultAppWorkFlow.toLowerCase()) < 0) {
if (!targetURL) {
$location.path('/borrower-view-rate');
return false;
break;
}
}
case 'custom-quote':
case "custom-quote-with-loandata":
case 'monthly-quote':
var FormNo = 'LoanData';
if (!$scope.updateEMI())
return false;
break;
default:
var FormNo = 'Form3';
if (!checkstatus('frmSignUpOwner', $scope))
return false;
break;
}
var PartialAppUID = Form1Data = Form2Data = Form3Data = LoanData = null;
if ($scope.PartialApplications && $scope.PartialApplications.PartialAppUID) {
PartialAppUID = $scope.PartialApplications.PartialAppUID;
};
switch (FormNo) {
case 'Form1':
with ($scope.Login) {
Form1Data = {
"SignUpBusiness1": {
"Login_LoginKeyword": LoginKeyword,
"Login_Password": Password,
"Users_StateID": StateID.StateID
}
};
}
case 'LoanData':
with ($scope.LoanData) {
if (_.isFunction(FinanceAmount.replace))
var finAmount = parseInt(FinanceAmount.replace(',', ''));
else
var finAmount = parseInt(FinanceAmount);
if (isNaN(finAmount)) {
finAmount = $rootScope.CompanyPreferences.DefaultAmount;
} else if (!(LoanData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : $rootScope.CompanyPreferences.DefaultCreditScoreID,
"FinanceAmount": (FinanceAmount) ? finAmount : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && _.isObject(FinanceTenure)) ? FinanceTenure.Term : (_.isNumber(FinanceTenure) ? FinanceTenure : $rootScope.CompanyPreferences.DefaultLoanTerm),
"FinanceTimeInBusiness": (FinanceTimeInBusiness && (typeof FinanceTimeInBusiness == 'object')) ? parseInt(FinanceTimeInBusiness.TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID,
"CommissionPoints": CommissionPoints
}))) {
// Handle Error
}
LoanData.ProgramLoanType = (typeof ProgramLoanType == "undefined") ? 'Business' : ProgramLoanType;
LoanData.FinancePurposeID = [];
for (var i in $scope.LoanData.FinancePurpose) {
if (typeof $scope.LoanData.FinancePurpose[i] == 'object')
LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i].FinancePurposeID);
else
LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i]);
}
}
if ($rootScope.hideEMI) {
LoanData.hideEMI = $rootScope.hideEMI;
}
break;
case 'Form2':
with ($scope.Business) {
Form2Data = {
"SignUpBusiness2": {
Business_LegalStructureName: (LegalStructure && (typeof LegalStructure == 'object')) ? LegalStructure.LegalStructureID : null,
Business_Month: (Month && (typeof Month == 'object')) ? Month.key : null,
Business_Year: (Year && (typeof Year == 'object')) ? Year.Year : null,
Business_Address1: Address1,
Business_Address2: Address2,
Business_CityID: City,
Business_Postal: PostalCode,
Business_StateID: 12,//(StateID && (typeof StateID == 'object'))?StateID.StateID:null,
Business_PhoneNumber: PhoneNumber,
Business_ContactName: ContactName,
Business_ContactNumber: ContactNumber,
Business_BusinessName: Name,
Business_DBA: DBA,
Business_TaxID: TaxID,
// Business_IndustryTypes:(IndustryTypes && typeof IndustryTypes == 'object')?IndustryTypes.IndustryTypeID:null,
Business_IndustryTypes: [],
Business_EquipmentDescription: $scope.Equipment.Description,
Business_PurposeOfPurchase: ($scope.Equipment.PurposeOfPurchase && typeof $scope.Equipment.PurposeOfPurchase == 'object') ? $scope.Equipment.PurposeOfPurchase.key : null,
}
};
var medicalDetailsRequired = false;
if (_.isArray($scope.Business.IndustryTypes)) {
for (var j in $scope.Business.IndustryTypes) {
Form2Data.SignUpBusiness2.Business_IndustryTypes.push($scope.Business.IndustryTypes[j].IndustryTypeID);
if (!medicalDetailsRequired && [7, 23, 28].indexOf($scope.Business.IndustryTypes[j].IndustryTypeID) != -1) {
medicalDetailsRequired = true;
}
}
} else {
// Handle Industry Type is not an array
Form2Data.SignUpBusiness2.Business_IndustryTypes.push($scope.Business.IndustryTypes.IndustryTypeID);
if (!medicalDetailsRequired && [7, 23, 28].indexOf($scope.Business.IndustryTypes.IndustryTypeID) != -1) {
medicalDetailsRequired = true;
}
}
if (medicalDetailsRequired) {
Form2Data.SignUpBusiness2.Business_MedicalLicense = $scope.Medical.License;
Form2Data.SignUpBusiness2.Business_MedicalLicenseIssueDate = $scope.Medical.LicenseIssueDate;
Form2Data.SignUpBusiness2.Business_MedicalLicenseStateID = ($scope.Medical.LicenseIssueState && typeof $scope.Medical.LicenseIssueState == 'object') ? $scope.Medical.LicenseIssueState.StateID : null;
Form2Data.SignUpBusiness2.Business_MedicalSpecialityDescription = $scope.Medical.SpecialityDescription;
}
}
break;
case 'Form3':
with ($scope.PrimaryOwner) {
Form3Data = {
"SignUpBusiness3": {
"Users_FirstName": FirstName,
"Users_LastName": LastName,
"Users_Email": Email,
"Users_MobileNumber": MobileNumber,
"Users_Address1": Address1,
"Users_Address2": Address2,
"Users_CityID": City,
"Users_StateID": (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
"Users_Postal": PostalCode,
"Users_SocialSecurityNumber": SocialSecurityNumber,
"Users_PercentageOwnership": PercentageOwnership,
"AdditionalOwners": null
}
};
// console.log($scope.BusinessPartners);
if (!_.isUndefined($scope.BusinessPartners)) {
Form3Data.SignUpBusiness3.AdditionalOwners = $scope.BusinessPartners;
}
if (SocialSecurityNumber && SocialSecurityNumber.length)
Form3Data.Users_SocialSecurityNumberView = '***-**-' + SocialSecurityNumber.substr(SocialSecurityNumber.length - 4, 4);
}
break;
}
if (checkstatus('frmCustomQuote', $scope)) {
$rootScope.Page.trackLoading('save-partial-app');
var reqData = {
"SavePartialAppData": {
"LoginSessionKey": ($rootScope.SignIn) ? $rootScope.SignIn.LoginSessionKey : null,
"Form": FormNo,
"Form1Data": Form1Data,
"Form2Data": Form2Data,
"Form3Data": Form3Data,
"LoanData": { 'ApplicationHome': LoanData },
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
'AppWorkFlow': $scope.PartialApplications.DefaultAppWorkFlow,
"PartialAppUID": PartialAppUID,
"ProposalID": $scope.PartialApplications.ProposalID
}
};
if (FormNo == 'Form1') {
reqData1 = {
"CheckLoginKeywordExist": {
"LoginKeyword": $scope.Login.LoginKeyword,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
};
appInfo.getServerData(reqData1).then(function (response) {
$rootScope.Page.untrackLoading('save-partial-app');
if (response.ResponseCode != 200) {
$rootScope.ngConfirm(response.Message + ' Would you like to login and apply?', function () {
$rootScope.clickToOpen();
});
} else if (response.ResponseCode != 200) {
$scope.showFlashMessage('error', response.Message);
} else
$scope.saveWizardData(targetURL, reqData);
});
} else
$scope.saveWizardData(targetURL, reqData);
$rootScope.Page.untrackLoading('save-partial-app');
};
}
$scope.saveWizardData = function (targetURL, reqData) {
$scope.Page.trackLoading('save-wizard');
if (_.isFunction($scope.prePartialAppSubmit))
$scope.prePartialAppSubmit(reqData, $scope);
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
switch (reqData.SavePartialAppData.Form) {
case 'Form1':
$scope.PartialApplications.Form1Data = Form1Data;
break;
case 'Form2':
$scope.PartialApplications.Form2Data = Form2Data;
$scope.setForm3Default();
break;
case 'Form3':
$scope.PartialApplications.Form3Data = Form3Data;
break;
case 'LoanData':
$scope.PartialApplications.LoanData = reqData.SavePartialAppData.LoanData;
$scope.setForm3Default();
break;
case 'borrower':
$scope.PartialApplications = reqData.SavePartialAppData;
break;
}
$scope.PartialApplications.PartialAppUID = response.Data.PartialAppUID;
Storage.setItem('PartialApplications', $scope.PartialApplications);
if (targetURL) {
$location.path(targetURL);
}
else {
switch (reqData.SavePartialAppData.Form) {
case 'LoanData':
if ($scope.PartialApplications) {
var ApplicationWorkFlow = ($scope.PartialApplications.DefaultAppWorkFlow ? $scope.PartialApplications.DefaultAppWorkFlow : $rootScope.CompanyPreferences.DefaultAppWorkFlow).toLowerCase();
switch (ApplicationWorkFlow) {
case 'selfcredit':
case "selfcreditwithchooselender":
if ($scope.PartialApplications.LoanData.ApplicationHome.ProgramLoanType == 'Business')
$state.go('create-account.ca-your-business');
else
$state.go('create-account.ca-your-details');
break;
case 'experianwithchooselender':
case 'experian':
case 'experianwithproductmonthlyquote':
$state.go('borrower-view-rate');
break;
}
}
else {
if (Storage.getItem('WizardReferrer')) {
$location.path(Storage.getItem('WizardReferrer'));
Storage.removeItem('WizardReferrer');
} else if ($rootScope.SignIn)
$location.path('/create-account/your-business');
else {
$location.path('/create-account');
}
}
break;
case 'Form1':
if ($scope.PartialApplications.LoanData.ApplicationHome.ProgramLoanType == 'Business')
$location.path('/create-account/your-business');
else
$location.path('/create-account/your-details');
break;
case 'Form2':
$location.path('/create-account/your-details');
break;
case 'Form3':
$location.path('/review-application');
break;
case 'borrower':
$location.path('/borrower-view-rate');
break;
}
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('save-wizard');
});
}
$scope.saveCustomPartialAppData = function () {
var LoanData = {};
with ($scope.LoanData) {
var finAmount = parseInt(FinanceAmount.replace(',', ''));
if (isNaN(finAmount)) {
finAmount = $rootScope.CompanyPreferences.DefaultAmount;
} else
LoanData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : 1,
"FinanceAmount": (FinanceAmount) ? finAmount : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (typeof FinanceTenure == 'object')) ? FinanceTenure.Term : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": (FinanceTimeInBusiness && (typeof FinanceTimeInBusiness == 'object')) ? parseInt(FinanceTimeInBusiness.TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID
});
}
var reqData = {
"SavePartialAppData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Form": "LoanData",
"Form1Data": null,
"Form2Data": null,
"Form3Data": null,
"LoanData": { 'ApplicationHome': LoanData },
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
'AppWorkFlow': $scope.PartialApplications.DefaultAppWorkFlow,
"PartialAppUID": null
}
};
if ($scope.PartialApplications.PartialAppUID) {
reqData.SavePartialAppData.PartialAppUID = $scope.PartialApplications.PartialAppUID;
};
if (_.isFunction($scope.prePartialAppSubmit))
$scope.prePartialAppSubmit(reqData, $scope);
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.PartialApplications.PartialAppUID = response.Data.PartialAppUID;
Storage.setItem('PartialApplications', $scope.PartialApplications);
$scope.loading = false;
$location.path('/custom-quote/');
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.showSSNDetails = function () {
if ($scope.checked) {
$scope.SSNNotRequiredFlag = FALSE;
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-corp-only-terms-popup.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope,
showClose: FALSE
});
}
else {
$scope.SSNNotRequiredFlag = TRUE;
}
}
$scope.cancelSSNPopup = function () {
$scope.checked = FALSE;
}
$scope.CancelPopup = function () {
$scope.checked = FALSE;
$scope.SSNNotRequiredFlag = TRUE;
ngDialog.close();
}
}])
// Program Controller
.controller('ProgramCtrl', ['$scope', '$rootScope', '$location', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$state', '$filter', '$q', 'appCache', function ($scope, $rootScope, $location, appInfo, ngDialog, $timeout, Storage, $state, $filter, $q, appCache, $route) {
$rootScope.SeeRecordData = { maxDisplayPages: '10' };
$scope.disableInputField = true;
$scope.disableManageTeamInput = true;
$scope.DataMandatory = TRUE;
$scope.LoanTime = {};
$scope.Annual = {};
$scope.LoanTime.loanduration = 1;
//$scope.Annual.annualRevenue = 1;
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
if (toState.name != 'program.config') {
$scope.saveLoanSettings();
}
});
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams, options) {
//console.log(event, toState, fromState);
});
$rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, options) {
//console.log(event, toState, fromState);
});
//$scope.ManageTeam={'currentPage':1,'totalRecords':10};
$scope.vendorSelectionProperties = {
'keyProperty': 'CompanyID',
'iterationList': null,
'iterationProperty': 'Association',
'sourceListModelName': 'AssociationData',
'sourceList': null
};
$scope.lastState = (!$scope.CompanyPreferences.isAffilate && $scope.CompanyPreferences.Category === 'Bank') ? 'program.required-document' : 'program.config';
$scope.deleteTerm = function (Term) {
var termIndex = this.$index;
function removeTerm() {
for (var j in $scope.programData) {
$scope.programData[j].Terms.splice(termIndex, 1);
}
$scope.ProgramTerms.splice(termIndex, 1);
}
if ($scope.CompanyPreferences.Category == 'Bank' || Term != $scope.Program.Term.Term)
var confirmMessage = 'Are you sure you want to remove ' + Term + ' term from calculator?';
else
var confirmMessage = "Selected Term is Default LoanTerm Are you sure you want to delete ?";
$scope.ngConfirm(confirmMessage, function () {
// if(termIndex)
removeTerm();
});
}
$scope.modifyInput = {
edit: function () { return $scope.disableInputField = false; },
save: function () { return $scope.disableInputField = true; },
cancel: function () { return $scope.disableInputField = true; }
}
$scope.tableRows = {};
$scope.updateChosen = function () {
setTimeout(function () {
$(".chosen-multiple-single").trigger('chosen:updated');
}, 200);
}
$scope.getFundingPaging = function () {
appInfo.getFundingProgram(function (response) {
setProgramData(response);
//--------
/*pagingData=[];
$scope.ManageTeam.currentPage=pagingData.currentPage=parseInt(response.Data.ProgramAccessData.Paginator.current_page);
pagingData.totalPage=response.Data.ProgramAccessData.Paginator.total_pages;
pagingData.totalRecord = $scope.ManageTeam.totalRecords=response.Data.ProgramAccessData.Paginator.total_programaccess
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);*/
//--------
}, true, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.Program.ProgramID,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"PageNo": $scope.ManageTeam.currentPage,
'ProgramLoanType': $scope.Program.ProgramLoanType,
'LoanTimeFormate': $scope.LoanTime.loanduration
//'AnnualRevenueScore': $scope.Annual.annualRevenue
});
//$scope.disableVendorInputField=true;
}
var resetPage = function (response) {
if (response) {
// console.log('resetPage function',response);
$scope.programData = response.Data.Mappings;
$scope.ProgramTerms = response.Data.ProgramTerms;
//--------
if (response.Data.ProgramAccessData && response.Data.ProgramAccessData.Paginator.total_programaccess) {
$scope.ManageTeam = response.Data.ProgramAccessData.Programaccess;
var pagingData = {};
$scope.ManageTeam.currentPage = pagingData.currentPage = parseInt(response.Data.ProgramAccessData.Paginator.current_page);
pagingData.totalPage = response.Data.ProgramAccessData.Paginator.total_pages;
pagingData.totalRecord = $scope.ManageTeam.totalRecords = response.Data.ProgramAccessData.Paginator.total_programaccess
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
//--------
$scope.disableSalesPerson = [];
$scope.TeamData = response.Data.TeamData;
for (var i in $scope.TeamData) {
for (var j in $scope.TeamData[i].VendorSalesIDs) {
$scope.disableSalesPerson.push($scope.TeamData[i].VendorSalesIDs[j]);
}
}
}
$scope.Program = { TimeInBusinessValue: '', ProgramCode: '', TermLengthValue: '', DeferralPayment: 0, vendorsSalesTeam: {}, PrivateMode: 0, ProgramLoanType: 'Business', disableRequiredDocumentTypesInput: true };
$scope.hideSidebar = ($scope.CompanyPreferences.Category == 'Company');
$scope.InactiveCreditScores = [];
if (!response && $scope.CompanyPreferences.Category == "Bank") {
$scope.ManageTeam = [];
$scope.TeamData = [];
// $scope.TeamData.push({PartnerSalesPerson : null, Association : null, VendorSalesPerson : null});
$scope.ManageTeam.push({ VendorSalesPerson: null, SalesPerson: null, PartnerSideCommissionCap: null, CreatedDate: $filter('date')(new Date(), 'dd-MMM-yyyy'), Association: null, SalespersonID: null });
}
if ($state.params.action !== 'add') {
appInfo.getSignUpStaticData(function () {
$scope.Program.TimeInBusinessValue = _.first($scope.TimeInBusiness);
}, $scope.ProgramID);
}
if ($scope.CompanyPreferences.Category == 'Bank') {
appInfo.getProgramStatusList(function () {
$scope.Program.ProgramStatus = $scope.ProgramStatusList[1];
});
if ($state.params.action !== 'add') {
$scope.Program.DeferralPayment = response.Data.Program.DeferralPayment;
$scope.Program.PrivateMode = response.Data.Program.PrivateMode;
} else {
appInfo.getIndustryTypes(function () {
$scope.Program.IndustryType = [];
});
appInfo.getProgramTypeList(function () {
$scope.Program.ProgramTypeID = null;
$scope.setUI();
});
appInfo.getFinancePurposeList(function () {
$scope.Program.FinancePurpose = [];
});
appInfo.getBusinessPurposeList(function () {
$scope.Program.BusinessPurpose = [];
});
setTimeout(function () {
$(".chosen-multiple-single").chosen({ max_selected_options: 1 });
}, 2000);
}
} else {
$scope.Program.Amount = $scope.CompanyPreferences.DefaultAmount;
$scope.Program.Term = _.findWhere($scope.ProgramTerms, { Term: $scope.CompanyPreferences.DefaultLoanTerm });
}
var rate = null;
var timeInBusinessID = null;
var inActiveCount = null;
for (var i in $scope.programData) {
for (var k in $scope.ProgramTerms) {
if ($state.params.action == 'add') {
$scope.programData[i].MinAmount = $scope.programData[i].MaxAmount = null;
if (!$scope.programData[i].Terms[k]) {
$scope.programData[i].Terms[k] = { Term: $scope.ProgramTerms[k].Term };
}
$scope.programData[i].Terms[k].Rate = null;
} else {
if (!$scope.programData[i].Terms[k]) {
$scope.programData[i].Terms[k] = { Term: $scope.ProgramTerms[k].Term, Rate: 'N/A' };
} else if ($scope.programData[i].Terms[k].Term != $scope.ProgramTerms[k].Term) {
$scope.programData[i].Terms.splice(k, 0, { Term: $scope.ProgramTerms[k].Term, Rate: 'N/A' });
}
}
}
if (timeInBusinessID != $scope.programData[i].TimeInBusinessID) {
timeInBusinessID = $scope.programData[i].TimeInBusinessID;
inActiveCount = _.findWhere($scope.InactiveCreditScores, { TimeInBusinessID: timeInBusinessID });
if (_.isUndefined(inActiveCount)) {
var itemIndex = $scope.InactiveCreditScores.push({ TimeInBusinessID: timeInBusinessID, count: 0 }) - 1;
inActiveCount = $scope.InactiveCreditScores[itemIndex];
}
}
if (!$scope.programData[i].Status) {
inActiveCount.count++;
}
}
}
var setProgramData = function (response) {
// console.log('setProgramData function',response);
$scope.ProgramID = response.Data.Program.ProgramID;
resetPage(response);
$scope.Page.documents = {
"ModuleEntityID": $scope.ProgramID,
"ModuleName": "ProgramDocument",
"selectedFiles": [],
"DocumentsData": [],
"selectedFileIds": [],
"FolderName": [],
"checkedFile": false,
"zipName": response.Data.Program.Title,
"filter": { "currentPage": 1 },
"selectedFileConditions": { "requiredIndustries": [] },
"selectedFilesActions": [{ "label": 'Set Conditions', "perform": $scope.requiredDocumentPopup }]
}
$scope.Program = response.Data.Program;
$scope.Program.disableRequiredDocumentTypesInput = true;
$scope.Program.IndustryType = $scope.Program.FinancePurpose = $scope.Program.BusinessPurpose = [];
$scope.Program.Action = $state.params.action;
$scope.removeRequiredDocumentTypes = [];
appInfo.getIndustryTypes(function () {
for (var k in $scope.Program.IndustryTypes) {
for (var j in $scope.industryData) {
if ($scope.industryData[j].IndustryTypeID == $scope.Program.IndustryTypes[k]) {
$scope.Program.IndustryType.push($scope.industryData[j]);
break;
}
}
}
delete $scope.Program.IndustryTypes;
if ($scope.disableInputField) {
setTimeout(function () {
angular.element('[hide-cross]').find('.search-choice-close').hide();
angular.element('[hide-cross]').find('.search-choice').css('padding-right', '5px');
}, 200);
}
$scope.Page.documents.selectedFileConditions.requiredIndustries = null;
});
appInfo.getFinancePurposeList(function () {
for (var k in $scope.Program.FinancePurposeID) {
for (var j in $scope.FinancePurposeData) {
if ($scope.FinancePurposeData[j].FinancePurposeID == $scope.Program.FinancePurposeID[k]) {
$scope.Program.FinancePurpose.push($scope.FinancePurposeData[j]);
break;
}
}
}
setTimeout(function () {
$(".chosen-multiple-single").chosen({ max_selected_options: 1 });
}, 2000);
if ($scope.Program.ProgramLoanType == 'Personal') {
delete $scope.Program.FinancePurposeID;
}
if ($scope.disableInputField) {
setTimeout(function () {
angular.element('[hide-cross]').find('.search-choice-close').hide();
angular.element('[hide-cross]').find('.search-choice').css('padding-right', '5px');
}, 200);
}
$scope.Page.documents.selectedFileConditions.requiredIndustries = null;
});
appInfo.getBusinessPurposeList(function () {
$scope.Program.BusinessPurpose = [];
for (var k in $scope.Program.FinancePurposeID) {
for (var j in $scope.BusinessPurposeData) {
if ($scope.BusinessPurposeData[j].BusinessApplicationPurposeID == $scope.Program.FinancePurposeID[k]) {
$scope.Program.BusinessPurpose.push($scope.BusinessPurposeData[j]);
break;
}
}
}
setTimeout(function () {
$(".chosen-multiple-single").chosen({ max_selected_options: 1 });
}, 2000);
if ($scope.Program.ProgramLoanType == 'Business') {
delete $scope.Program.FinancePurposeID;
}
if ($scope.disableInputField) {
setTimeout(function () {
angular.element('[hide-cross]').find('.search-choice-close').hide();
angular.element('[hide-cross]').find('.search-choice').css('padding-right', '5px');
}, 200);
}
$scope.Page.documents.selectedFileConditions.requiredIndustries = null;
});
appInfo.getProgramTypeList(function () {
$scope.Program.ProgramTypeID = _.findWhere($scope.ProgramTypeList, { ProgramTypeID: $scope.Program.ProgramTypeID });
});
vendorAllocation();
$scope.refreshFileList();
$scope.refreshRequiredDocumentTypeList();
if (_.isUndefined($scope.Program.TimeInBusinessValue) && $scope.TimeInBusiness) {
$scope.updateTimeInBusiness(0);
}
}
var initConfig = function () {
switch ($scope.CompanyPreferences.Category) {
case 'Company':
delete $scope.ProgramID;
appInfo.getFundingProgram(resetPage, true, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey
});
var offCallMeFn = $rootScope.$on('$stateChangeSuccess', function (event, toState) {
if (['program.details', 'program.config', 'signout'].indexOf(toState.name) == -1) {
appInfo.getFundingProgram(offCallMeFn, true, {
ProgramID: $scope.CompanyPreferences.DefaultProgramID,
UsingDefault: true
});
}
});
break;
case 'Bank':
$scope.disableVendorInputField = true;
var ProgramDetails = null;
if ($state.params.action == 'add') {
$scope.disableInputField = false;
$scope.disableVendorInputField = false;
resetPage();
$scope.Program.Action = $state.params.action;
}
else if (ProgramDetails = Storage.getItem('ProgramDetails')) {
$scope.ProgramID = ProgramDetails.ProgramID;
var newLoadingFundingData = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": ProgramDetails.ProgramID
}
if (!angular.equals($scope.loadingFundingData, newLoadingFundingData)) {
appInfo.getFundingProgram(setProgramData, true, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": ProgramDetails.ProgramID,
'ProgramLoanType': ProgramDetails.ProgramLoanType,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
'LoanTimeFormate': $scope.LoanTime.loanduration
//'AnnualRevenueScore': $scope.Annual.annualRevenue
});
}
}
else {
$location.path('/program');
}
break;
}
$scope.Page.Title = "Funding Program Settings - " + $scope.CompanyPreferences.CompanyName;
};
if ($scope.CompanyPreferences)
initConfig();
else
$scope.$on('company-loaded', initConfig);
$scope.setDocumentCriteria = function () {
appInfo.getServerData({
"setDocumentCriteria": {
"checkDocumentType": $scope.checkDocumentType ? $scope.checkDocumentType : false,
"selectedDocumentIDs": $scope.checkDocumentType ? $scope.selectedDocumentTypes : $scope.Page.documents.selectedFileIds,
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.ProgramID,
"Criteria": $scope.Page.documents.selectedFileConditions
}
}).then(function (response) {
if (response.ResponseCode == 200) {
if (!$scope.checkDocumentType) {
$scope.refreshFileList(_.last($scope.Page.documents.FolderName));
} else {
$scope.refreshRequiredDocumentTypeList();
$scope.Program.disableRequiredDocumentTypesInput = true;
}
$scope.showFlashMessage('success', response.Message);
ngDialog.close();
} else
$scope.showFlashMessage('error', response.Message);
}, function () {
$scope.showFlashMessage('error', 'Failed to save data.');
});
}
$scope.updateTimeInBusiness = function (index) {
$scope.Program.TimeInBusinessValue = $scope.TimeInBusiness[index];
}
$scope.addTermLengthCol = function () {
$scope.Program.TermLengthValue = parseInt($scope.Program.TermLengthValue);
$scope.MinActualTerm = parseInt($scope.programData[0].Terms[0].Term);
if ($scope.Program.ProgramTypeID.ProgramTypeID === 4) {
if ($scope.Program.TermLengthValue >= $scope.MinActualTerm) {
$scope.TermValue = $scope.Program.TermLengthValue;
if (!isNaN($scope.Program.TermLengthValue)) {
for (var i = 0; i < $scope.ProgramTerms.length; i++) {
if ($scope.ProgramTerms[i].Term == $scope.TermLengthValue) {
$scope.showFlashMessage('error', 'Already exists');
return;
} else if ($scope.ProgramTerms[i].Term > $scope.Program.TermLengthValue) {
break;
}
}
for (var j in $scope.programData) {
//Code for copy rate in previous terms.
var TempRate = ($scope.programData[j].Terms.length) ? $scope.programData[j].Terms[((i != 0) ? i - 1 : 0)].Rate : '';
$scope.programData[j].Terms.splice(i, 0, { Term: $scope.Program.TermLengthValue, Rate: TempRate });
}
$scope.ProgramTerms.splice(i, 0, { Term: $scope.Program.TermLengthValue, Rate: TempRate });
$scope.Program.TermLengthValue = null;
}
} else {
$scope.showFlashMessage('error', 'Term Length cannot be less then ' + $scope.MinActualTerm);
}
} else {
if ($scope.Program.TermLengthValue >= 12) {
$scope.TermValue = $scope.Program.TermLengthValue;
if (!isNaN($scope.Program.TermLengthValue)) {
for (var i = 0; i < $scope.ProgramTerms.length; i++) {
if ($scope.ProgramTerms[i].Term == $scope.TermLengthValue) {
$scope.showFlashMessage('error', 'Already exists');
return;
} else if ($scope.ProgramTerms[i].Term > $scope.Program.TermLengthValue) {
break;
}
}
for (var j in $scope.programData) {
//Code for copy rate in previous terms.
var TempRate = ($scope.programData[j].Terms.length) ? $scope.programData[j].Terms[((i != 0) ? i - 1 : 0)].Rate : '';
$scope.programData[j].Terms.splice(i, 0, { Term: $scope.Program.TermLengthValue, Rate: TempRate });
}
$scope.ProgramTerms.splice(i, 0, { Term: $scope.Program.TermLengthValue, Rate: TempRate });
$scope.Program.TermLengthValue = null;
}
} else {
$scope.showFlashMessage('error', 'Term Length cannot be less then 12');
}
}
}
$scope.cancelProgramChanges = function () {
$scope.disableInputField = false;
$scope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
$scope.disableInputField = true;
// delete $rootScope.loadingFundingData;
initConfig();
});
}
$scope.checkProgramType = function () {
if ($scope.Program.ProgramLoanType == 'Business') {
$scope.DataMandatory = TRUE;
$scope.Program.ProgramTypeID = null;
$scope.Program.IndustryType = [];
}
else
$scope.DataMandatory = FALSE;
setTimeout(function () {
$(".chosen-multiple-single").chosen({ max_selected_options: 1 });
}, 200);
}
$scope.addAllIndustryType = function () {
if ($scope.checkSelected == false) {
$scope.checkSelected = true;
$scope.Program.IndustryType = [];
} else {
$scope.checkSelected = false;
$scope.Program.IndustryType = $rootScope.industryData;
}
}
$scope.addAllLoanPurpose = function () {
if ($scope.checkSelected == false) {
$scope.checkSelected = true;
$scope.Program.FinancePurpose = [];
} else {
$scope.checkSelected = false;
$scope.Program.FinancePurpose = $scope.FinancePurposeData;
}
}
$scope.addAllLoanBusinessPurpose = function () {
if ($scope.checkSelected == false) {
$scope.checkSelected = true;
$scope.Program.BusinessPurpose = [];
} else {
$scope.checkSelected = false;
$scope.Program.BusinessPurpose = $scope.BusinessPurposeData;
}
}
$scope.saveProgramData = function (callback) {
if ($scope.CompanyPreferences.Category == 'Bank') {
$formName = 'frmAddPrograms';
}
else {
$formName = 'frmViewProgram';
}
if (checkstatus($formName, $scope)) {
var reqData = {
"SaveFundingProgramData": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Mappings": [],
"forceSave": false
}
};
var minAmount = null;
var maxAmount = null;
for (var i in $scope.programData) {
minAmount = ($scope.programData[i].MinAmount) ? parseInt(($scope.programData[i].MinAmount + '').replace(',', '')) : 0;
maxAmount = ($scope.programData[i].MaxAmount) ? parseInt(($scope.programData[i].MaxAmount + '').replace(',', '')) : 0;
if (!minAmount || !maxAmount) {
$scope.disableInputField = false;
angular.element('#MinAmount' + i).focus();
var errMessage = 'Amount Range cannot be blank.';
$scope.Program.TimeInBusinessValue = _.findWhere($scope.TimeInBusiness, { TimeInBusinessID: $scope.programData[i].TimeInBusinessID });
$scope.showFlashMessage('error', errMessage);
return $scope.disableInputField = false;
} else if (maxAmount < minAmount) {
$scope.showFlashMessage('error', "Max Amount must be greater then or equal to Min Amount");
return $scope.disableInputField = false;
}
//console.log($scope.programData);
reqData.SaveFundingProgramData.Mappings.push({
"MinAmount": minAmount,
"MaxAmount": maxAmount,
"TimeInBusinessID": $scope.programData[i].TimeInBusinessID,
"CreditScoreID": $scope.programData[i].CreditScoreID,
"Terms": $scope.programData[i].Terms,
"Status": $scope.programData[i].Status,
"AnnualRevenueID": $scope.programData[i].AnnualRevenueID
});
}
if ($scope.CompanyPreferences.Category == "Company") {
reqData.SaveFundingProgramData.Defaults = {
DefaultAmount: ($scope.Program.Amount + '').replace(',', ''),
DefaultLoanTerm: $scope.Program.Term.Term
};
} else {
with ($scope.Program) {
reqData.SaveFundingProgramData.Program = {
"ProgramID": $scope.ProgramID,
'ProgramCode': ProgramCode,
'Title': Title,
'Description': Description,
'DeferralPayment': DeferralPayment,
'ProgramLoanType': ProgramLoanType,
'ProgramTypeID': ProgramTypeID ? ProgramTypeID.ProgramTypeID : null,
'PrivateMode': PrivateMode,
'IndustryTypes': [],
'FinancePurposeID': []
};
for (var i in IndustryType)
reqData.SaveFundingProgramData.Program.IndustryTypes.push(IndustryType[i].IndustryTypeID);
if (reqData.SaveFundingProgramData.Program.ProgramLoanType == 'Personal') {
for (var i in FinancePurpose)
reqData.SaveFundingProgramData.Program.FinancePurposeID.push(FinancePurpose[i].FinancePurposeID);
}
if (reqData.SaveFundingProgramData.Program.ProgramLoanType == 'Business') {
for (var i in BusinessPurpose)
reqData.SaveFundingProgramData.Program.FinancePurposeID.push(BusinessPurpose[i].BusinessApplicationPurposeID);
}
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if ($scope.CompanyPreferences.Category == 'Company') {
if ($scope.hideSidebar) {
$scope.showFlashMessage('success', 'System settings changed. Please login again to see new changes.');
setTimeout(function () {
$state.go('signout');
setTimeout(function () { location.reload() }, 2000);
}, 200);
}
else
$scope.showFlashMessage('success', 'Calculator Data Updated Successfully.');
appInfo.getFundingProgram(resetPage, true, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramLoanType": $scope.Program.ProgramLoanType,
'LoanTimeFormate': $scope.LoanTime.loanduration,
//'AnnualRevenueScore': $scope.Annual.annualRevenue,
UsingDefault: TRUE
});
} else {
if ($state.params.action != 'add')
$scope.showFlashMessage('success', 'Program Data Saved Successfully');
else if (response.Data.Charge)
$scope.showFlashMessage("info", "Please consider upgrade for plan. $" + response.Data.Charge + " charged for the action.");
$scope.ProgramID = response.Data.Program.ProgramID;
Storage.setItem('ProgramDetails', { ProgramID: $scope.ProgramID, ProgramLoanType: $scope.Program.ProgramLoanType });
if (!_.isUndefined(callback)) {
callback(response);
}
else {
//console.log('not get',setProgramData);
appInfo.getFundingProgram(setProgramData, true, {
LoginSessionKey: $scope.SignIn.LoginSessionKey,
ProgramID: $scope.ProgramID,
"ProgramLoanType": $scope.Program.ProgramLoanType,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
'LoanTimeFormate': $scope.LoanTime.loanduration,
//'AnnualRevenueScore': $scope.Annual.annualRevenue,
'ProcessTypeUpdate': true
});
}
}
} else if (response.ResponseCode == 8) {
$scope.ngConfirm(response.Message, function () {
reqData.SaveFundingProgramData.forceSave = true;
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.disableInputField = true;
}
else {
$scope.showFlashMessage('error', response.Message);
$scope.disableInputField = false;
}
});
}, function () {
$scope.disableInputField = true;
delete $rootScope.loadingFundingData;
initConfig();
});
} else {
$scope.showFlashMessage('error', response.Message);
$scope.disableInputField = false;
}
});
}
else
$scope.disableInputField = false;
}
function vendorAllocation() {
$scope.removeVendors = [];
$scope.removeTeams = [];
setTimeout(function () {
if ($scope.ManageTeam) {
appInfo.getSalesPersons(function () {
appInfo.getAssociationList(function () {
for (var i in $scope.ManageTeam) {
$scope.ManageTeam[i].Association = _.findWhere($rootScope.AssociationData, { CompanyID: $scope.ManageTeam[i].VendorID });
if ($scope.ManageTeam[i].SalesPersonID) {
$scope.ManageTeam[i].PartnerSalesPerson = _.findWhere($rootScope.salesPersons, { ID: $scope.ManageTeam[i].SalesPersonID });
}
}
$scope.vendorSelectionProperties.iterationList = $scope.ManageTeam;
$scope.vendorSelectionProperties.sourceList = $rootScope.AssociationData;
});
$('.vendor-chosen').trigger("chosen:updated");
});
}
}, 600);
}
function teamAllocation() {
$scope.removeTeams = [];
appInfo.getSalesPersons(function () {
if ($scope.salesPersons) {
appInfo.getAssociationList(function () {
for (var i in $scope.TeamData) {
$scope.TeamData[i].Association = _.findWhere($rootScope.AssociationData, { CompanyID: $scope.TeamData[i].VendorID });
$scope.TeamData[i].PartnerSalesPerson = _.findWhere($rootScope.salesPersons, { ID: $scope.TeamData[i].SalespersonID });
}
if ($scope.disableManageTeamInput) {
setTimeout(function () {
angular.element('[hide-cross]').find('.search-choice-close').hide();
angular.element('[hide-cross]').find('.search-choice').css('padding-right', '5px');
}, 200);
}
}, { "ProgramID": $scope.ProgramID });
} else {
$scope.ngConfirm("There is no sales person in your team. Would you like to add now?", function () {
$state.go('company-user');
}, function () {
$scope.ManageTeam = false;
$scope.disableVendorInputField = true;
});
}
});
}
$scope.navigateWizard = function (button, newState) {
if (button == 'jump') {
if ($scope.ProgramID) {
switch (newState) {
case 'program.vendor-allocation':
vendorAllocation();
break;
case 'program.manage-teams':
teamAllocation();
break;
/*case 'program.config':
if(_.isUndefined($scope.Program.TimeInBusinessValue) && $scope.TimeInBusiness){
$scope.updateTimeInBusiness(0);
}
break;*/
}
return $state.go(newState);
} else
return false;
}
switch ($state.current.name) {
case 'program.details':
if ($state.params.action == 'add') {
if (checkstatus('frmAddPrograms', $scope)) {
$scope.saveProgramData(function (response) {
// if($scope.Program.ProgramLoanType == 'Personal'){
// if(!$scope.CompanyPreferences.isAffilate){
// vendorAllocation();
// $state.go('program.vendor-allocation');
// }
// else{
// $state.go('program-list');
// }
// }
// else
$location.path('/program/view/config');
});
}
} else
$state.go('program.config');
break;
case 'program.config':
if (button == "Previous") {
$location.path('/program/view');
}
else {
vendorAllocation();
$scope.saveLoanSettings();
$state.go('program.vendor-allocation');
}
break;
case 'program.vendor-allocation':
if (button == "Previous") {
$location.path('/program/view/config');
}
else {
// teamAllocation();
$state.go('program.required-document');
}
break;
case 'program.manage-teams':
vendorAllocation();
$state.go('program.vendor-allocation');
break;
case 'program.required-document':
$state.go('program.vendor-allocation');
break;
}
}
var setVendorTeamSelected = function (currentTeam) {
var teamMate = null;
currentTeam.VendorSales = [];
if (currentTeam.VendorSalesIDs) {
for (var i in currentTeam.VendorSalesIDs) {
teamMate = _.findWhere($scope.Program.vendorsSalesTeam[currentTeam.Association.Alias], { ID: currentTeam.VendorSalesIDs[i] });
if (teamMate)
currentTeam.VendorSales.push(teamMate);
}
}
}
$scope.prepareVendorSales = function () {
if (this.Team.Association) {
var currentTeam = this.Team;
var currentAssociation = this.Team.Association;
if (!_.isUndefined($scope.Program.vendorsSalesTeam[currentAssociation.Alias]))
setVendorTeamSelected(currentTeam);
else {
appInfo.getSalesPersons(function (response) {
$scope.Program.vendorsSalesTeam[currentAssociation.Alias] = response.Data.salesPersons;
setVendorTeamSelected(currentTeam);
}, false, currentAssociation.Alias);
}
}
}
//popup
$scope.timeInBusinessPopup = function () {
$scope.TimeInBusinessGroups = [];
angular.copy($scope.TimeInBusiness, $scope.TimeInBusinessGroups);
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-dlgAddTimeInBusiness.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope
});
}
$scope.addTimeInBusiness = function () {
if ($scope.TimeInBusinessGroups.length < 6)
$scope.TimeInBusinessGroups.push({ MinYears: "", MaxYears: "", Title: "" });
else
$scope.showFlashMessage('error', 'Maximum six configurations can be defined.');
}
$scope.RemoveTimeInBusinessGroups = [];
$scope.removeTimeInBusiness = function () {
var TimeInBusinessGroup = this.TimeInBusinessGroup;
$scope.RemoveTimeInBusinessGroups.push(TimeInBusinessGroup);
if (this.$index != 0) {
for (var i in $scope.TimeInBusinessGroups) {
if ($scope.TimeInBusinessGroups[parseInt(i) + 1] && $scope.TimeInBusinessGroups[i].TimeInBusinessID == TimeInBusinessGroup.TimeInBusinessID) {
$scope.TimeInBusinessGroups[parseInt(i) + 1].MinYears = $scope.TimeInBusinessGroups[parseInt(i) - 1].MaxYears;
}
}
}
// if(this.$index>0)
// {
if (this.$index == 0) {
$("#iconDel1").hide();
}
else if (this.$index == 1) {
$("#iconDel0").hide();
}
$scope.TimeInBusinessGroups.splice(this.$index, 1);
// }
}
$scope.cancelPopUp = function () {
$scope.RemoveTimeInBusinessGroups = [];
ngDialog.close();
}
$scope.saveTimeInBusiness = function () {
var TimeInBusinessGroups = this.TimeInBusinessGroups;
if (TimeInBusinessGroups[TimeInBusinessGroups.length - 1].MaxYears) {
$scope.showFlashMessage('success', 'Success');
}
var reqData = {
"SaveTimeInBusiness": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"LoanTimeFormate": $scope.LoanTime.loanduration
//'AnnualRevenueScore': $scope.Annual.annualRevenue
}
}
if ($scope.CompanyPreferences.Category == "Bank") {
reqData.SaveTimeInBusiness.ProgramID = $scope.ProgramID;
}
reqData.SaveTimeInBusiness.TimeInBusiness = TimeInBusinessGroups;
if ($scope.RemoveTimeInBusinessGroups) {
reqData.SaveTimeInBusiness.RemoveTimeInBusiness = $scope.RemoveTimeInBusinessGroups;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
ngDialog.close();
delete $scope.TimeInBusiness;
$rootScope.TimeInBusiness = response.Data;
appCache.put('TimeInBusiness' + $scope.ProgramID, response.Data);
delete $rootScope.loadingFundingData;
initConfig();
}
else {
$scope.showFlashMessage("error", response.Message);
}
});
}
$scope.setCreditScore = function () {
var ProgData = this.Prog;
var inActiveCount = _.findWhere($scope.InactiveCreditScores, { TimeInBusinessID: ProgData.TimeInBusinessID });
$scope.ngConfirm("Would you like to update this credit score in all time in business ?", function () {
for (var i in $scope.programData) {
if ($scope.programData[i].CreditScoreID == ProgData.CreditScoreID) {
inActiveCount = _.findWhere($scope.InactiveCreditScores, { TimeInBusinessID: $scope.programData[i].TimeInBusinessID });
if (!ProgData.Status) {
if (inActiveCount.count == 4) {
var temp = _.findWhere($scope.TimeInBusiness, { TimeInBusinessID: $scope.programData[i].TimeInBusinessID });
$scope.showFlashMessage('error', 'At least one credit score is required for ' + temp.Title + '.');
} else {
if ($scope.programData[i].Status != ProgData.Status) {
$scope.programData[i].Status = ProgData.Status;
inActiveCount.count++;
}
}
} else {
if ($scope.programData[i].Status != ProgData.Status) {
$scope.programData[i].Status = ProgData.Status;
inActiveCount.count--;
}
}
continue;
}
}
}, function () {
if (!ProgData.Status) {
if (inActiveCount.count == 4) {
$scope.showFlashMessage('error', 'At least one credit score is required.');
ProgData.Status = 1;
return false;
} else {
inActiveCount.count++;
}
} else {
inActiveCount.count--;
}
});
}
$scope.addVendor = function (event) {
switch (event.target.id) {
case "addButton":
$scope.ManageTeam.push({ CreatedDate: new Date() });
$scope.disableVendorInputField = false;
break;
case "removeButton":
if (this.term.ProgramAccessID)
$scope.removeVendors.push(this.term.ProgramAccessID);
if (this.term.ProgramTeamConfigID)
$scope.removeTeams.push(this.term.ProgramTeamConfigID);
$scope.ManageTeam.splice(this.$index, 1);
break;
case "saveButton":
if (checkstatus('FrmAddVendor', $scope)) {
var vendors = [];
for (var i = 0; i < $scope.ManageTeam.length; i++) {
vendors.push({
"PartnerSideCommissionCap": $scope.ManageTeam[i].PartnerSideCommissionCap,
"VendorID": $scope.ManageTeam[i].Association.CompanyID,
"ProgramAccessID": $scope.ManageTeam[i].ProgramAccessID,
"SalesPersonID": $scope.ManageTeam[i].PartnerSalesPerson.ID,
"ProgramTeamConfigID": $scope.ManageTeam[i].ProgramTeamConfigID
});
$scope.ManageTeam[i].VendorID = $scope.ManageTeam[i].Association.CompanyID;
}
appInfo.requestProgramAccess(function (response) {
var msgClass = "error";
if (response.ResponseCode == 200) {
$scope.disableVendorInputField = true;
initConfig();
msgClass = "success";
}
$scope.showFlashMessage(msgClass, response.message);
// if(response.Data.actionValue.TotalCharge)
// $scope.showFlashMessage("info","Please consider upgrade for plan. $"+response.Data.actionValue.TotalCharge+" charged for the action.");
}, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.ProgramID,
"RequestChannel": "Direct",
"Vendors": vendors,
"RemoveVendors": $scope.removeVendors,
"RemoveTeams": $scope.removeTeams
});
}
break;
case "editButton":
$scope.disableVendorInputField = false;
if (!$scope.ManageTeam) {
$scope.ManageTeam = [];
vendorAllocation();
teamAllocation();
$scope.ManageTeam.push({ CreatedDate: $filter('date')(new Date(), 'dd-MMM-yyyy'), Association: null, PartnerSideCommissionCap: null, PartnerSalesPerson: null });
}
break;
case "cancelButton":
$scope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
appInfo.getFundingProgram(vendorAllocation, true, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.Program.ProgramID,
"ProgramLoanType": $scope.Program.ProgramLoanType,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
'LoanTimeFormate': $scope.LoanTime.loanduration,
'AnnualRevenueScore': $scope.Annual.annualRevenue
});
$scope.disableVendorInputField = true;
})
break;
}
}
$scope.createUpdateTeam = function (event) {
switch (event.target.id) {
case "addButton":
$scope.TeamData.push({ PartnerSalesPerson: null, Association: null, VendorSales: null });
$scope.disableManageTeamInput = false;
break;
case "removeButton":
if (this.Team.ProgramTeamConfigID)
$scope.removeTeams.push(this.Team.ProgramTeamConfigID);
$scope.TeamData.splice(this.$index, 1);
break;
case "saveButton":
if (checkstatus('FrmManageTeam', $scope)) {
var reqData = {
"CreateUpdateTeams": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProgramID": $scope.Program.ProgramID,
"TeamData": $scope.TeamData
}
}
if ($scope.removeTeams.length > 0) {
reqData.CreateUpdateTeams.removeTeams = $scope.removeTeams;
};
var tempData = [];
for (var i in $scope.TeamData) {
var tempSales = [];
// tempData.push($scope.TeamData[i].Association.CompanyID+','+$scope.TeamData[i].PartnerSalesPerson.ID);
tempData.push($scope.TeamData[i].Association.CompanyID);
}
if (checkDuplicateRecord(tempData) == 0) {
$scope.Page.trackLoading('create-team');
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.disableManageTeamInput = true;
$scope.Page.untrackLoading('create-team');
$scope.showFlashMessage('success', response.Message);
}
else {
$scope.Page.untrackLoading('create-team');
$scope.showFlashMessage('error', response.Message);
}
})
}
else
$scope.showFlashMessage('error', 'Duplicate record not permitted');
}
break;
case "editButton":
$scope.disableManageTeamInput = false;
if (!$scope.TeamData.length)
$scope.TeamData.push({});
break;
case "cancelButton":
$scope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
appInfo.getFundingProgram(setProgramData, true, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.Program.ProgramID,
"ProgramLoanType": $scope.Program.ProgramLoanType,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
'LoanTimeFormate': $scope.LoanTime.loanduration,
'AnnualRevenueScore': $scope.Annual.annualRevenue
});
$scope.disableManageTeamInput = true;
})
break;
}
}
function checkDuplicateRecord(checkData) {
var sorted_arr = checkData.slice().sort();
var results = [];
for (var i = 0; i < checkData.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
$scope.requiredDocumentPopup = function (checkDocumentType) {
$scope.checkDocumentType = checkDocumentType;
$scope.Page.documents.selectedFileConditions = {};
if (!checkDocumentType && $scope.Page.documents.selectedFiles.length == 1 && $scope.Page.documents.selectedFiles[0].criteria) {
$scope.Page.documents.selectedFileConditions = $scope.Page.documents.selectedFiles[0].criteria;
if ($scope.Page.documents.selectedFileConditions.requiredAmountThreshold && !_.isString($scope.Page.documents.selectedFileConditions.requiredAmountThreshold) && $scope.Page.documents.selectedFileConditions.requiredAmountThreshold % 1 == 0) {
$scope.Page.documents.selectedFileConditions.requiredAmountThreshold += ".00"
}
if ($scope.Page.documents.selectedFileConditions.requiredCreditScore && !_.isObject($scope.Page.documents.selectedFileConditions.requiredCreditScore)) {
$scope.Page.documents.selectedFileConditions.requiredCreditScore = _.findWhere($scope.CreditScores, { 'CreditScoreID': $scope.Page.documents.selectedFileConditions.requiredCreditScore });
}
if ($scope.Page.documents.selectedFileConditions.requiredIndustries && !_.isObject($scope.Page.documents.selectedFileConditions.requiredIndustries[0])) {
for (i in $scope.Page.documents.selectedFileConditions.requiredIndustries) {
$scope.Page.documents.selectedFileConditions.requiredIndustries[i] = _.findWhere($scope.industryData, { 'IndustryTypeID': $scope.Page.documents.selectedFileConditions.requiredIndustries[i] });
}
}
} else if ($scope.selectedDocumentTypes.length == 1) {
var selectedDocumentType = _.findWhere($scope.requiredDocumentTypes.Application_documents, { ApplicationDocumentID: $scope.selectedDocumentTypes[0] });
if (selectedDocumentType.criteria) {
$scope.Page.documents.selectedFileConditions = selectedDocumentType.criteria;
if ($scope.Page.documents.selectedFileConditions.requiredAmountThreshold && !_.isString($scope.Page.documents.selectedFileConditions.requiredAmountThreshold) && $scope.Page.documents.selectedFileConditions.requiredAmountThreshold % 1 == 0) {
$scope.Page.documents.selectedFileConditions.requiredAmountThreshold += ".00"
}
if ($scope.Page.documents.selectedFileConditions.requiredCreditScore && !_.isObject($scope.Page.documents.selectedFileConditions.requiredCreditScore)) {
$scope.Page.documents.selectedFileConditions.requiredCreditScore = _.findWhere($scope.CreditScores, { 'CreditScoreID': $scope.Page.documents.selectedFileConditions.requiredCreditScore });
}
if ($scope.Page.documents.selectedFileConditions.requiredIndustries && !_.isObject($scope.Page.documents.selectedFileConditions.requiredIndustries[0])) {
for (i in $scope.Page.documents.selectedFileConditions.requiredIndustries) {
$scope.Page.documents.selectedFileConditions.requiredIndustries[i] = _.findWhere($scope.industryData, { 'IndustryTypeID': $scope.Page.documents.selectedFileConditions.requiredIndustries[i] });
}
}
}
}
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-documentRequired.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope
});
}
$scope.tabNum = 1;
$scope.setTab = function (setTab) {
$scope.tabNum = setTab;
}
$scope.tab = function (tab) {
return $scope.tabNum === tab;
}
$scope.selectDocumentType = function () {
var i = $scope.selectedDocumentTypes.indexOf(this.requiredDocumentType.ApplicationDocumentID);
if (i == -1) {
$scope.selectedDocumentTypes.push(this.requiredDocumentType.ApplicationDocumentID);
} else {
$scope.selectedDocumentTypes.splice(i, 1);
}
}
$scope.setLoanDuration = function () {
// call a service to check whether loan settings for this program is saved LoanDuration => days/weeks/months
// if the loan settings are saved in db for this program
// then show a message that program loan settings saved with days/weeks/months if you wish to create new settings with days/weeks/months(input from front end), please create a new program with desired settings.
// set the loanDuration with loan duration from the api.
// else
var reqData = {
"getcheckLoansettingsExist": {
"ProgramID": $scope.Program.ProgramID,
"LoanTimeDurationID": $scope.LoanTime.loanduration,
'AnnualRevenueScore': $scope.Annual.annualRevenue
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode === 200) {
$scope.showFlashMessage('info', response.Message);
$scope.LoanTime.loanduration = response.Data.LoanTimeDurationID;
return true;
} else {
appInfo.getFundingProgram(function (response) {
setProgramData(response);
}, true, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.Program.ProgramID,
"ProgramLoanType": $scope.Program.ProgramLoanType,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"LoanTimeFormate": $scope.LoanTime.loanduration,
'AnnualRevenueScore': $scope.Annual.annualRevenue
});
}
ngDialog.close();
});
}
$scope.setAnnualRevenue = function () {
var reqData = {
"getcheckLoansettingsExist": {
"ProgramID": $scope.Program.ProgramID,
"LoanTimeDurationID": $scope.LoanTime.loanduration,
'AnnualRevenueScore': $scope.Annual.annualRevenue
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode === 200) {
$scope.showFlashMessage('info', response.Message);
$scope.LoanTime.loanduration = response.Data.LoanTimeDurationID;
return true;
} else {
appInfo.getFundingProgram(function (response) {
setProgramData(response);
}, true, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.Program.ProgramID,
"ProgramLoanType": $scope.Program.ProgramLoanType,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"LoanTimeFormate": $scope.LoanTime.loanduration,
'AnnualRevenueScore': $scope.Annual.annualRevenue
});
}
ngDialog.close();
});
}
$scope.saveLoanSettings = function (programData) {
var reqData = {
"getSaveLoanSettings": {
"Settings": (!_.isUndefined(programData)) ? programData : $scope.programData,
"ProgramID": $scope.Program.ProgramID,
"LoanDurationID": $scope.LoanTime.loanduration
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.disableLoanDuration = true;
// Storage.setItem('disableLoanDuration', { disableLoanDurationID: $scope.disableLoanDuration});
//Storage.setItem('disableLoanDuration', true);
//$scope.getProgramsList();
} else {
$scope.showFlashMessage('error', response.Message);
}
ngDialog.close();
});
}
$scope.refreshRequiredDocumentTypeList = function () {
appInfo.getServerData({
"GetRequiredTypedDocuments": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.Program.ProgramID,
"PageNo": _.isObject($scope.requiredDocumentTypes) ? $scope.requiredDocumentTypes.Paginator.current_page : 1
}
}).then(function (response) {
if (response.ResponseCode == 200) {
var pagingData = {};
$scope.requiredDocumentTypes = response.Data;
if (!$scope.requiredDocumentTypes.Application_documents)
$scope.requiredDocumentTypes.Application_documents = [];
$scope.selectedDocumentTypes = [];
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = response.Data.Paginator.total_application_documents;
pagingData.numPerPage = 10;
$scope.showingRequiredDocumentTypeText = appInfo.getPaginationData(pagingData);
} else {
$scope.showFlashMessage('error', response.message);
}
});
}
$scope.saveRequiredDocumentTypes = function ($event) {
switch ($event.target.id) {
case "addButton":
$scope.requiredDocumentTypes.Application_documents.splice(0, 0, {});
break;
case "removeButton":
if (this.requiredDocumentType.ApplicationDocumentID)
$scope.removeRequiredDocumentTypes.push(this.requiredDocumentType.ApplicationDocumentID);
$scope.requiredDocumentTypes.Application_documents.splice(this.$index, 1);
break;
case "saveButton":
if (checkstatus('SaveRequiredTypedDocuments', $scope)) {
appInfo.getServerData({
"SaveRequiredTypedDocuments": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.Program.ProgramID,
"RequiredDocumentTypes": $scope.requiredDocumentTypes.Application_documents,
"RemoveDocumentTypes": $scope.removeRequiredDocumentTypes
}
}).then(function (response) {
msgType = 'error';
if (response.ResponseCode = 200) {
msgType = 'success';
$scope.Program.disableRequiredDocumentTypesInput = true;
$scope.refreshRequiredDocumentTypeList();
}
$scope.showFlashMessage(msgType, response.message);
});
}
break;
case "cancelButton":
$scope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
$scope.refreshRequiredDocumentTypeList();
$scope.Program.disableRequiredDocumentTypesInput = true;
})
break;
}
}
}])
.controller('DefaultCalculatorConfiguration', ['$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', '$state', function ($scope, appInfo, $location, ngDialog, $timeout, Storage, $state) {
/*Function for set configuration regarding to program - start*/
$scope.setDefaultConfiguration = function () {
$scope.DefaultData = {};
$scope.DefaultProgramData = null;
var params = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.CompanyPreferences.DefaultProgramID
};
$scope.getDefaultConfiguration(function (response) {
$scope.DefaultProgramData = response.Data;
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-default-configuration.html',
scope: $scope,
});
if ($scope.DefaultProgramData.ProgramLoanType == 'Business') {
$scope.DefaultData = {
"TimeInBusiness": _.findWhere($scope.DefaultProgramData.TimeInBusiness, { TimeInBusinessID: $scope.CompanyPreferences.DefaultTimeInBusinessID }),
};
} else {
$scope.DefaultProgramData.AppliedCreditData = $scope.DefaultProgramData.CreditData;
$scope.DefaultData.CreditData = _.findWhere($scope.DefaultProgramData.AppliedCreditData, { CreditScoreID: $scope.CompanyPreferences.DefaultCreditScoreID });
}
}, params);
}
/*Function for set configuration regarding to program - end*/
/*Function for set configuration regarding to program - start*/
$scope.getDefaultConfiguration = function (callback) {
var reqData = {
"GetDefaultConfiguration": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.CompanyPreferences.DefaultProgramID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (typeof callback != 'undefined')
callback(response);
});
}
/*Function for set configuration regarding to program - end*/
$scope.$watch('DefaultData.CreditData', function (newValue, oldValue) {
$timeout(function () {
if (_.isObject(newValue) && !angular.equals(newValue, oldValue)) {
if ($scope.DefaultData.TimeInBusiness)
$scope.DefaultProgramData.AppliedTerms = $scope.DefaultProgramData.Terms[$scope.DefaultData.TimeInBusiness.TimeInBusinessID][newValue.CreditScoreID];
else
$scope.DefaultProgramData.AppliedTerms = $scope.DefaultProgramData.Terms[newValue.CreditScoreID];
$scope.DefaultData.LoanTerm = _.findWhere($scope.DefaultProgramData.AppliedTerms, { Term: $scope.CompanyPreferences.DefaultLoanTerm });
if (!$scope.DefaultData.LoanTerm)
$scope.DefaultData.LoanTerm = _.first($scope.DefaultProgramData.AppliedTerms);
}
}, 200);
});
$scope.$watch('DefaultData.TimeInBusiness', function (newValue, oldValue) {
$timeout(function () {
if (_.isObject(newValue) && !angular.equals(newValue, oldValue)) {
$scope.DefaultProgramData.AppliedCreditData = $scope.DefaultProgramData.CreditData[newValue.TimeInBusinessID];
$scope.DefaultData.CreditData = _.findWhere($scope.DefaultProgramData.AppliedCreditData, { CreditScoreID: $scope.CompanyPreferences.DefaultCreditScoreID });
}
}, 200);
});
$scope.updateDefaultData = function () {
var reqData = {
"SaveDefaultConfiguration": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": $scope.CompanyPreferences.DefaultProgramID,
"DefaultData": this.DefaultData
}
};
appInfo.getServerData(reqData).then(function (response) {
ngDialog.close();
setTimeout(function () { location.reload() }, 200);
// $state.reload();
});
}
}])
// ProgramList Controller
.controller('programListCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', '$state', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage, $state) {
$scope.programListFilter = {};
$scope.Program = {};
$scope.currentPage = 1;
$rootScope.loadingFundingData = null;
$scope.Page.Title = 'Program - ' + $rootScope.CompanyPreferences.CompanyName;
$scope.programsRequestsFilter = { Name: null };
$scope.getProgramsRequests = function () {
var reqData = {
"GetProgramsRequests": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ListType": $scope.UpdateFlag,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
}
reqData.GetProgramsRequests.Filter = {
Title: $scope.programsRequestsFilter.Name,
}
$scope.Page.trackLoading('program-list');
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.ProgramsRequests = response.Data.Programaccess;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPrograms = response.Data.Paginator.total_programaccess;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
})
$scope.Page.untrackLoading('program-list');
}
$scope.getProgramsList = function () {
var reqData = {
"GetProgramsList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
}
};
$scope.AddProgram = true;
reqData.GetProgramsList.Flag = $scope.UpdateFlag;
reqData.GetProgramsList.Filter = {
StatusID: ($scope.Program.ProgramStatus) ? $scope.Program.ProgramStatus.StatusID : null,
Title: $scope.programListFilter.Name,
IndustryTypeID: ($scope.programListFilter.IndustryType) ? $scope.programListFilter.IndustryType.IndustryTypeID : null,
}
$rootScope.Page.trackLoading('programs-list');
appInfo.getServerData(reqData).then(function (response) {
// console.log(response);
if (response.ResponseCode == 200) {
pagingData = [];
$scope.UpdateFlag = 1;
$scope.AddProgram = response.Data.AddProgram;
$scope.ProgramList = response.Data.Programs;
if (typeof ($scope.ProgramList) != 'undefined') {
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPrograms = response.Data.Paginator.total_programs
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
for (var i in $scope.ProgramList) {
for (var k in $scope.ProgramList[i].IndustryTypes) {
$scope.ProgramList[i].IndustryTypeList = '';
for (var j in $rootScope.industryData) {
if ($rootScope.industryData[j].IndustryTypeID == $scope.ProgramList[i].IndustryTypes[k]) {
$scope.ProgramList[i].IndustryTypeList += $rootScope.industryData[j].Name;
break;
}
}
}
for (var l in $rootScope.ProgramStatusList) {
if ($rootScope.ProgramStatusList[l].StatusID == $scope.ProgramList[i].StatusID) {
$scope.ProgramList[i].ProgramStatus = $rootScope.ProgramStatusList[l];
break;
}
}
}
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$rootScope.Page.untrackLoading('programs-list');
});
}
if ($state.params.action == 'request') {
$scope.UpdateFlag = 2;
$scope.getProgramsRequests();
}
else {
$scope.UpdateFlag = 1;
appInfo.getIndustryTypes(function () {
appInfo.getProgramStatusList(function () {
$scope.programListFilter.IndustryType = null;
$scope.Program.ProgramStatus = $rootScope.ProgramStatusList[1];
$scope.$watch('programListFilter.IndustryType', function (newVal, oldVal) {
if (newVal && newVal != oldVal)
$scope.getProgramsList();
});
$scope.getProgramsList();
});
$scope.$watch('programListFilter.Name', function (newValue, oldValue) {
if (newValue && newValue != oldValue) {
$scope.currentPage = 1;
$scope.getProgramsList();
}
});
});
}
$scope.navigateToDetails = function (ProgramID) {
Storage.setItem('ProgramDetails', { 'ProgramID': ProgramID });
$location.path('/program/view');
};
$scope.changeStatus = function () {
$scope.selectedProgram = this.Programs;
$scope.selectedProgram.OldProgramStatus = {};
angular.copy($scope.selectedProgram.ProgramStatus, $scope.selectedProgram.OldProgramStatus);
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-changeStatus.html',
//controller: 'programListCtrl',
scope: $scope,
});
}
$scope.revertStatus = function () {
$scope.selectedProgram.ProgramStatus = {};
angular.copy($scope.selectedProgram.OldProgramStatus, $scope.selectedProgram.ProgramStatus);
ngDialog.close();
};
$scope.UpdateProgramStatus = function () {
var reqData = {
"UpdateProgramStatus": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"StatusID": $scope.selectedProgram.ProgramStatus.StatusID,
"ProgramID": $scope.selectedProgram.ProgramID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.getProgramsList();
} else {
$scope.showFlashMessage('error', response.Message);
}
ngDialog.close();
});
}
$scope.SetAsDefault = function () {
appInfo.SetAsDefault("Are you sure you want to set this program as default ?", { ProgramID: this.Programs.ProgramID, ProgramLoanType: this.Programs.ProgramLoanType });
$scope.getProgramsList();
}
$scope.changeProgramTab = function (Flag) {
$scope.currentPage = 1
$scope.ProgramList = null;
$scope.UpdateFlag = Flag;
if (Flag > 1) {
$scope.getProgramsRequests();
}
else {
$scope.getProgramsList();
}
}
$scope.getProgramsRequests = function () {
var reqData = {
"GetProgramsRequests": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ListType": $scope.UpdateFlag - 2,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
}
reqData.GetProgramsRequests.Filter = {
Title: $scope.programsRequestsFilter.Name,
}
$scope.Page.trackLoading('program-requests');
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('program-requests');
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.ProgramsRequests = response.Data.Programaccess;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPrograms = response.Data.Paginator.total_programaccess;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
})
}
$scope.$watch('programsRequestsFilter.Name', function (newValue, oldValue) {
if (newValue != oldValue)
$scope.getProgramsRequests();
});
$scope.addEditCommissionCapPopUp = function () {
$scope.CommissionData = this.Programs;
if ($scope.CommissionData.PartnerSideCommissionCap) {
$scope.CommissionData.PartnerSideCommissionCap = $scope.CommissionData.PartnerSideCommissionCap;
};
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-AddCommissionCap.html',
// controller: '',
scope: $scope,
});
}
$scope.GrantRevokeProgram = function (DisassociateFlag) {
if (checkstatus('addEditCommissionCapfrm', $scope)) {
$scope.Parameters = {
"ProgramAccessID": $scope.CommissionData.ProgramRequestID,
"PartnerSideCommissionCap": $scope.CommissionData.PartnerSideCommissionCap
}
// $scope.Parameters={
// "ProgramAccessID": this.Programs.ProgramRequestID,
// "PartnerSideCommissionCap": 6
// }
appInfo.GrantRevokeProgram(function () {
$scope.getProgramsRequests();
}, $scope.Parameters);
ngDialog.close();
$scope.getProgramsRequests();
}
}
$scope.revokeProgram = function (UpdateFlag) {
appInfo.GrantRevokeProgram(function () {
$scope.UpdateFlag = UpdateFlag;
$scope.getProgramsRequests();
}, { ProgramAccessID: this.Programs.ProgramRequestID }, 1);
$scope.getProgramsRequests();
}
$scope.viewApplications = function () {
var appList = {
"ApplicationNumber": null,
"Filter": {
Name: null,
StartDate: null,
EndDate: null,
appStatus: {
StatusName: null
}
},
"ProgramID": this.Programs.ProgramID,
"ProgramName": this.Programs.ProgramName ? this.Programs.ProgramName : this.Programs.Title,
"currentPage": 1,
"SortBy": this.Programs
};
Storage.setItem('appList', appList);
$location.path('/applications');
}
$scope.setRemovePopup = function (flag) {
//G90console.log(this.Programs);
$scope.currentProgramData = this.Programs;
$rootScope.ngConfirm('Are you sure you want to ' + flag + ' this program as default for Experian?', function () {
var Parameters = {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProgramID": $scope.currentProgramData.ProgramID,
"CompanyID": $scope.CompanyPreferences.CompanyID
};
if (flag == "Set")
var StatusID = 25;
else
var StatusID = 3;
Parameters.StatusID = StatusID;
$rootScope.setRemoveDefaultForExperian(function () {
$scope.getProgramsList();
}, Parameters);
});
}
}])
// uixRating Controller
.controller('uixRatingCtrl', ['$scope', 'appInfo', function ($scope, appInfo) {
$scope.rate = 1;
$scope.max = 5;
$scope.isReadonly = false;
$scope.percent = 20;
$scope.hoveringOver = function (value, object) {
$scope.overStar = value;
$scope.percent = (100 * $scope.overStar) / $scope.max;
};
$scope.hoveringLeave = function (rate) {
$scope.percent = (100 * $scope.rate) / $scope.max;
};
}])
// Share Application Controller
.controller('shareApplicationController', ['$scope', 'appInfo', '$state', 'ngDialog', '$timeout', 'Storage', function ($scope, appInfo, $state, ngDialog, $timeout, Storage) {
$scope.BestMatch = true;
$scope.RecentUpdate = false;
$scope.noMatchFound = "No Such Records";
$scope.shareAppListFilter = {
Association: null,
currentPage: 1
};
$scope.getMatchingPrograms = function () {
$scope.Application = { ApplicationNumber: $state.params.ApplicationNumber };
var reqData = {
"GetMatchingPrograms": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"PageNo": $scope.shareAppListFilter.currentPage,
"ApplicationNumber": $scope.Application.ApplicationNumber,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"Bestmatch": $scope.BestMatch,
"RecentUpdate": $scope.RecentUpdate,
"shareAppFlag": TRUE
}
};
if ($scope.shareAppListFilter) {
reqData.GetMatchingPrograms.Filter = {
ShareApplicationsFilter_Name: $scope.shareAppListFilter.Name,
ShareApplicationsFilter_AssociationID: ($scope.shareAppListFilter.Association) ? $scope.shareAppListFilter.Association.CompanyID : null
};
}
appInfo.getServerData(reqData).then(function (response) {
$scope.Programs = null;
switch (response.ResponseCode) {
case 200:
if (response.Data.Programs) {
$scope.Programs = response.Data.Programs;
var pagingData = [];
$scope.shareAppListFilter.currentPage = pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPrograms = response.Data.Paginator.total_programs;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
break;
case 646:
$scope.noMatchFound = response.Message;
break;
default:
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.recentUpdates = function () {
$scope.RecentUpdate = true;
$scope.shareAppListFilter.currentPage = 1;
$scope.getMatchingPrograms();
}
$scope.$watch('shareAppListFilter.Name', function (newValue, oldValue) {
if (newValue != oldValue) {
$scope.shareAppListFilter.currentPage = 1;
$scope.getMatchingPrograms();
}
});
if ($state.params.ApplicationNumber) {
$scope.getMatchingPrograms();
}
else {
$scope.showFlashMessage('error', 'Application Not Found.')
$state.go('applications');
}
if ($scope.CompanyPreferences.Category != "Bank") {
appInfo.getAssociationList(function () {
$scope.AssociationName = null;
});
}
$scope.filterByAssociate = function (associate) {
$scope.shareAppListFilter.Association = associate;
$scope.shareAppListFilter.currentPage = 1;
$scope.getMatchingPrograms();
};
$scope.updateBestMatch = function (BestMatch) {
$scope.BestMatch = !BestMatch;
$scope.RecentUpdate = false;
$scope.shareAppListFilter.currentPage = 1;
$scope.getMatchingPrograms();
}
$scope.ShareApplication = function () {
var selectedProgram = this.Program;
$scope.ngConfirm("Are you sure you want to Share this application ?", function () {
var reqData = {
"ShareApplication": {
"ApplicationNumber": $scope.Application.ApplicationNumber,
"ProgramID": selectedProgram.ProgramID,
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.Application.ProgramID = reqData.ShareApplication.ProgramID;
$scope.getMatchingPrograms();
Storage.setItem('shareApplication', $scope.Application);
$scope.showFlashMessage('success', response.Message);
} else {
$scope.showFlashMessage('error', response.Message);
}
});
});
}
$scope.revokeApplication = function () {
var Program = this.Program;
appInfo.cancelSharedApplication($scope.Application, function (response) {
if (response.ResponseCode == 200) {
$scope.Application.ProgramID = null;
Storage.setItem('shareApplication', $scope.Application);
$scope.getMatchingPrograms();
$scope.showFlashMessage('success', response.Message);
} else {
$scope.showFlashMessage('error', response.Message);
}
}, Program.ProgramID);
}
$scope.requestProgramAccess = function () {
var selectedProgramData = this.Program;
$scope.ngConfirm("Are you sure you want to Associate this application ?", function () {
appInfo.requestProgramAccess(function () {
$scope.getMatchingPrograms();
}, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": selectedProgramData.ProgramID,
"RequestChannel": "Via Application"
});
});
}
}])
// Unsubscribe Controller
.controller('unsubscribeCtrl', ['$rootScope', '$scope', 'appInfo', '$location', '$stateParams', 'ngDialog', '$timeout', 'Storage', function ($rootScope, $scope, appInfo, $location, $stateParams, ngDialog, $timeout, Storage) {
$scope.AlreadyUnsubscribe = true;
if ($stateParams.Email) {
var reqData = {
"checkUnsubscribeEmail": {
"UnsubscribeEmailID": $stateParams.Email
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.AlreadyUnsubscribe) {
$scope.UnsubscribeMessage = 'You have Already Unsubscribed.';
} else {
$scope.AlreadyUnsubscribe = false;
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
$scope.Unsubscribe = { reasonFlags: {} };
$scope.Email = $stateParams.Email;
appInfo.getMarkerFlags(function () {
$scope.UnsubscribeFlags = $rootScope.markerFlags.UnsubscribeFlag;
$scope.Unsubscribe.reasonFlags = _.first($scope.UnsubscribeFlags);
});
}
$scope.unsubscribeProposal = function () {
$scope.Flag = true;
if (checkstatus('frmUNsubscribeProposal', $scope)) {
var reqData = { "unsubscribeProposal": {} };
if ($stateParams.Email) {
reqData.unsubscribeProposal = {
"Email": $stateParams.Email,
"ReasonFlagID": $scope.Unsubscribe.reasonFlags.MarkerFlagID,
"Comment": $scope.Unsubscribe.reasonComment
}
}
else {
reqData.unsubscribeProposal = {
"ProposalLeadID": $stateParams.ProposalLeadID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.AlreadyUnsubscribe = true;
$location.path('/');
// $scope.UnsubscribeMessage=response.Message;
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
}])
// Decline Proposal Controller
.controller('declineProposalCtrl', ['$rootScope', '$scope', 'appInfo', '$location', '$stateParams', 'ngDialog', '$timeout', 'Storage', function ($rootScope, $scope, appInfo, $location, $stateParams, ngDialog, $timeout, Storage) {
$scope.Decline = { Message: null, Flag: false };
$scope.DeclineProposal = function () {
var reqData = {
"DeclineProposal": {
"Referrer": document.referrer,
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ProposalLeadID": $stateParams.ProposalLeadID,
}
}
if ($scope.Decline.Message) {
reqData.DeclineProposal.DeclineMessage = $scope.Decline.Message;
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.Decline.Flag = true;
if ($scope.Decline.Message) {
$scope.showFlashMessage('success', response.Message);
$location.path('/');
}
}
else {
$scope.Decline.Flag = false;
$scope.Message = response.Message;
}
});
}
$scope.DeclineProposal();
}])
// Program Dashboard Controller
.controller('programDashboardAppCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage) {
$scope.Program = {};
$scope.currentPage = 1;
$scope.AssociatedProgramFlag = true;
$rootScope.loadingFundingData = null;
$scope.programListFilter = Storage.getItem('programListFilter');
if (!_.isObject($scope.programListFilter)) {
$scope.programListFilter = {};
}
$scope.getProgramsList = function () {
var reqData = {
"GetProgramsList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"AssociatedProgramFlag": $scope.AssociatedProgramFlag
}
};
reqData.GetProgramsList.Filter = {
Title: $scope.programListFilter.Name,
IndustryTypeID: ($scope.programListFilter.IndustryType) ? $scope.programListFilter.IndustryType.IndustryTypeID : null,
BankID: $scope.programListFilter.BankID ? $scope.programListFilter.BankID : null
}
$scope.ProgramList = null;
$scope.totalRecord = 0;
$rootScope.Page.trackLoading('programs-list');
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
pagingData = [];
$scope.ProgramList = response.Data.Programs;
//console.log($scope.ProgramList, response);
if (typeof ($scope.ProgramList) != 'undefined') {
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPrograms = response.Data.Paginator.total_programs
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
for (var i in $scope.ProgramList) {
for (var k in $scope.ProgramList[i].IndustryTypes) {
$scope.ProgramList[i].IndustryTypeList = (k == 0) ? '' : ($scope.ProgramList[i].IndustryTypeList + ',');
for (var j in $rootScope.industryData) {
if ($rootScope.industryData[j].IndustryTypeID == $scope.ProgramList[i].IndustryTypes[k]) {
$scope.ProgramList[i].IndustryTypeList += $rootScope.industryData[j].Name;
break;
}
}
}
for (var l in $rootScope.ProgramStatusList) {
if ($rootScope.ProgramStatusList[l].StatusID == $scope.ProgramList[i].StatusID) {
$scope.ProgramList[i].ProgramStatus = $rootScope.ProgramStatusList[l];
break;
}
}
}
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$rootScope.Page.untrackLoading('programs-list');
});
}
appInfo.getIndustryTypes(function () {
appInfo.getProgramStatusList(function () {
$scope.programListFilter.IndustryType = null;
$scope.Program.ProgramStatus = $rootScope.ProgramStatusList[1];
$scope.$watch('programListFilter.IndustryType', function (newVal, oldVal) {
if (newVal != oldVal)
$scope.getProgramsList();
});
$scope.getProgramsList();
});
$scope.$watch('programListFilter.Name', function (newValue, oldValue) {
if (newValue != oldValue)
$scope.getProgramsList();
});
});
$scope.navigateToDetails = function (ProgramID) {
Storage.setItem('ProgramDetails', { 'ProgramID': ProgramID });
$location.path('/program/view');
};
$scope.changeStatus = function () {
$scope.selectedProgram = this.Programs;
$scope.selectedProgram.OldProgramStatus = {};
angular.copy($scope.selectedProgram.ProgramStatus, $scope.selectedProgram.OldProgramStatus);
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-changeStatus.html',
//controller: 'programListCtrl',
scope: $scope,
});
}
$scope.revertStatus = function () {
$scope.selectedProgram.ProgramStatus = {};
angular.copy($scope.selectedProgram.OldProgramStatus, $scope.selectedProgram.ProgramStatus);
ngDialog.close();
};
$scope.UpdateProgramStatus = function () {
var reqData = {
"UpdateProgramStatus": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"StatusID": $scope.selectedProgram.ProgramStatus.StatusID,
"ProgramID": $scope.selectedProgram.ProgramID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.getProgramsList();
} else {
$scope.showFlashMessage('error', response.Message);
}
ngDialog.close();
});
}
$scope.updateAssociatedPrograms = function (Flag) {
$scope.currentPage = 1;
if (Flag == 1) {
$scope.AssociatedProgramFlag = 0;
}
else if (Flag == 0) {
$scope.AssociatedProgramFlag = 1;
}
$scope.getProgramsList();
}
$scope.requestProgramAccess = function () {
var selectedProgramData = this.Program;
$scope.ngConfirm("Are you sure you want to Associate this Program ?", function () {
appInfo.requestProgramAccess(function () {
$scope.getProgramsList();
}, {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramID": selectedProgramData.ProgramID,
"RequestChannel": "Via Application"
});
});
}
$scope.CancelRequest = function () {
var selectedProgramAccessData = this.Program;
$scope.ngConfirm("Are you sure you want to cancel this Request ?", function () {
var reqData = {
"cancelRequest": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ProgramAccessID": selectedProgramAccessData.ProgramAccessID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.getProgramsList();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
});
}
$scope.disassociateProgram = function (DisassociateFlag) {
var selectedProgramData = this.Program;
$scope.ngConfirm("Are you sure you want to Disassociate this Program ?", function () {
appInfo.GrantRevokeProgram(function () {
$scope.getProgramsList();
}, { ProgramAccessID: selectedProgramData.ProgramAccessID }, DisassociateFlag);
});
}
$scope.SetAsDefault = function () {
// var ProgramID=this.Program.ProgramID;
var params = {
ProgramID: this.Program.ProgramID,
ProgramLoanType: this.Program.ProgramLoanType
}
var Massage = "Are you sure you want to set this program as default ?";
if (_.isUndefined(params.ProgramID)) {
Massage = "Are you sure you want to use your own program as default ?";
params.ProgramID = null;
}
appInfo.SetAsDefault(Massage, params);
}
$scope.setRemovePopup = function (flag, Programs) {
$scope.currentProgramData = Programs;
$rootScope.ngConfirm('Are you sure you want to ' + flag + ' this program as default for Experian?', function () {
var Parameters = {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProgramID": $scope.currentProgramData,
"CompanyID": $scope.CompanyPreferences.CompanyID
};
if (flag == "Set")
var StatusID = 25;
else
var StatusID = 3;
Parameters.StatusID = StatusID;
$rootScope.setRemoveDefaultForExperian(function () {
$scope.getProgramsList();
}, Parameters);
});
}
$scope.viewApplications = function () {
var appList = {
"ApplicationNumber": null,
"Filter": {
Name: null,
StartDate: null,
EndDate: null,
appStatus: {
StatusName: null
}
},
"ProgramID": this.Program.ProgramID,
"ProgramName": this.Program.Title,
"currentPage": 1,
"SortBy": null
};
Storage.setItem('appList', appList);
$location.path('/applications');
}
$scope.addEditCommissionCapPopUp = function () {
$scope.showButtonFlag = true;
$scope.CommissionData = this.Program;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-AddVendorSideCommissionCap.html',
// controller: '',
scope: $scope,
});
}
$scope.setVendorCommissionCap = function (DisassociateFlag) {
var CommissionData = this.CommissionData;
if (checkstatus('vendorCommissionCapfrm', $scope)) {
$scope.Parameters = {
"ProgramAccessID": CommissionData.ProgramAccessID,
"PartnerSideCommissionCap": CommissionData.PartnerSideCommissionCap,
"VendorSideCommissionCap": parseInt(CommissionData.VendorSideCommissionCap),
"LockCommission": CommissionData.LockCommission
}
appInfo.GrantRevokeProgram(function () {
// $scope.getProgramsRequests();
}, $scope.Parameters);
ngDialog.close();
// $scope.getProgramsRequests();
}
}
$scope.checkVendorCommissionCap = function (DisassociateFlag) {
if (parseInt($scope.CommissionData.VendorSideCommissionCap) < parseInt($scope.CommissionData.PartnerSideCommissionCap)) {
$scope.showButtonFlag = false;
}
else if ($scope.CommissionData.VendorSideCommissionCap) {
$scope.showButtonFlag = true;
$scope.showFlashMessage('error', 'Vendor side Commission Point must be less than Partner side Commission Point.');
// $scope.CommissionData.VendorSideCommissionCap=parseInt($scope.CommissionData.PartnerSideCommissionCap)-1;
}
else {
if (this.CommissionData.LockCommission)
$scope.showButtonFlag = false;
else
$scope.showButtonFlag = true;
}
}
$scope.openPopup = function () {
$scope.ProgramDetail = this.Program;
// if($scope.ProgramDetail.IndustryTypes && $scope.ProgramDetail.IndustryTypes.length>0)
// {
// $scope.ProgramDetail.Industries=$scope.ProgramDetail.IndustryTypes.split(',');
// }
appInfo.getIndustryTypes(function () {
$scope.IndustryTypes = [];
for (var j in $scope.industryData) {
if (!angular.isNumber($scope.ProgramDetail.IndustryTypes)) {
for (var k in $scope.ProgramDetail.IndustryTypes) {
if ($scope.industryData[j].IndustryTypeID == $scope.ProgramDetail.IndustryTypes[k]) {
$scope.IndustryTypes.push($scope.industryData[j]);
break;
}
}
}
else {
if ($scope.industryData[j].IndustryTypeID == $scope.ProgramDetail.IndustryTypes) {
$scope.IndustryTypes.push($scope.industryData[j]);
break;
}
}
}
});
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-share-app-popup.html',
// controller: 'shareApplicationController',
scope: $scope,
className: 'ng-popup ngdialog-theme-default'
});
}
$scope.resetFilter = function () {
$scope.programListFilter = {};
Storage.setItem('programListFilter', $scope.programListFilter);
$scope.getProgramsList();
}
}])
// Routing Controller
.controller('RoutingCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage) {
$scope.getProgramsList = function () {
var reqData = {
"GetProgramsList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": 1,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"AssociatedProgramFlag": true
}
};
var eliminatePrograms = [];
if ($scope.PreferedPrograms) {
for (var i = 0; i < $scope.PreferedPrograms.length; i++) {
eliminatePrograms.push($scope.PreferedPrograms[i].ProgramID);
}
}
reqData.GetProgramsList.Filter = {
Title: $scope.RoutingProgramFilter.Name,
CompanyID: $scope.RoutingProgramFilter.Association ? $scope.RoutingProgramFilter.Association.CompanyID : null,
EliminatePrograms: eliminatePrograms
}
$scope.ProgramList = null;
$scope.totalRecord = 0;
$rootScope.Page.trackLoading('programs-list');
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
pagingData = [];
$scope.ProgramList = response.Data.Programs;
if (typeof ($scope.ProgramList) != 'undefined') {
// pagingData.currentPage=response.Data.Paginator.current_page;
// pagingData.totalPage=response.Data.Paginator.total_pages;
// pagingData.totalRecord = $scope.AssociatedPrograms.totalPrograms=response.Data.Paginator.total_programs
// pagingData.numPerPage = 10;
// $scope.showingtext = appInfo.getPaginationData(pagingData);
for (var i in $scope.ProgramList) {
for (var k in $scope.ProgramList[i].IndustryTypes) {
$scope.ProgramList[i].IndustryTypeList = (k == 0) ? '' : ($scope.ProgramList[i].IndustryTypeList + ',');
for (var j in $rootScope.industryData) {
if ($rootScope.industryData[j].IndustryTypeID == $scope.ProgramList[i].IndustryTypes[k]) {
$scope.ProgramList[i].IndustryTypeList += $rootScope.industryData[j].Name;
break;
}
}
}
for (var l in $rootScope.ProgramStatusList) {
if ($rootScope.ProgramStatusList[l].StatusID == $scope.ProgramList[i].StatusID) {
$scope.ProgramList[i].ProgramStatus = $rootScope.ProgramStatusList[l];
break;
}
}
}
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$rootScope.Page.untrackLoading('programs-list');
});
}
$scope.getRoutingRuleData = function () {
var reqData = {
"GetRoutingRuleData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200 && response.Data) {
if ($rootScope.CompanyPreferences.EnableSalesOverride != response.Data.EnableSalesOverride) {
Storage.removeItem('uaInfo');
Storage.removeItem('CompanyPreferences');
setTimeout(function () { location.reload() }, 2000);
}
$scope.PreferedPrograms = response.Data.Rule;
}
});
}
$scope.init = function () {
// if($rootScope.CompanyPreferences.PlanID==1){
// $scope.showFlashMessage('error','You are not authorized to access this link.');
// $timeout(function(){
// $location.path('/program-dashboard');
// },100);
// } else {
$scope.RoutingProgramFilter = { Name: null, Association: null };
$scope.PreferedPrograms = [];
$scope.AssociatedPrograms = {
currentPage: 1,
totalPrograms: 0
};
appInfo.getAssociationList(function () {
$scope.EnableSalesOverride = false;
$scope.getRoutingRuleData();
});
// }
}
if ($rootScope.CompanyPreferences)
$scope.init();
else
$rootScope.$on('company-loaded', $scope.init);
$scope.filterByAssociate = function () {
$scope.RoutingProgramFilter.Association = this.Association;
$scope.getProgramsList();
}
$scope.resetFilters = function () {
$scope.RoutingProgramFilter.Association = null;
$scope.getProgramsList();
}
$scope.$watch('RoutingProgramFilter.Name', _.debounce(function (newValue, oldValue) {
$scope.getProgramsList();
}, 800))
$scope.updatePlaceholders = function ($indexTo, $indexFrom, $sourcePart, $targetPart) {
// console.log($indexTo,$indexFrom,$sourcePart,$targetPart);
}
$scope.validateRuleUpdate = function ($item, $index) {
$scope.D.Dest = $scope.D.Src = null;
if ($scope.PreferedPrograms != null && $scope.PreferedPrograms.length >= 10) {
$scope.showFlashMessage('error', 'You can select maximum 10 programs for routing rule.');
$timeout(function () {
var i = _.findIndex($scope.PreferedPrograms, {
"ProgramID": $item.ProgramID
});
$scope.PreferedPrograms.splice(i, 1);
$scope.ProgramList.splice($index, 0, $item);
}, 100);
} else {
$timeout($scope.getProgramsList, 100);
}
}
$scope.triggerUpdate = function (action) {
switch (action) {
case 'add':
if ($scope.PreferedPrograms.length < 10) {
$scope.PreferedPrograms.push(this.Program);
} else {
$scope.showFlashMessage('error', 'You can select maximum 10 programs for routing rule.');
return FALSE;
}
break;
case 'remove':
$scope.PreferedPrograms.splice(this.$index, 1);
break;
}
$scope.getProgramsList();
}
$scope.addEditRoutingRule = function () {
if ($scope.PreferedPrograms.length > 0) {
$scope.ProgramIDs = [];
for (var i in $scope.PreferedPrograms) {
$scope.ProgramIDs.push($scope.PreferedPrograms[i].ProgramID);
}
var reqData = {
"RoutingRule": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"RoutingData": $scope.ProgramIDs,
"EnableSalesOverride": $scope.EnableSalesOverride
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$rootScope.CompanyPreferences.EnableSalesOverride = $scope.EnableSalesOverride;
Storage.setItem('CompanyPreferences', $rootScope.CompanyPreferences);
}
});
}
else {
$scope.showFlashMessage('error', "Please add some programs");
}
}
$scope.enableSalesOverride = function () {
if (this.check)
$scope.EnableSalesOverride = true;
else
$scope.EnableSalesOverride = false;
}
$scope.cancel = function () {
$rootScope.ngConfirm("Are you sure you want to cancel editing ? All changes done will lost.", function () {
$scope.init();
});
}
}])
// Invitation Controller
.controller('invitationCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage) {
$scope.currentPage = 1;
$scope.getVendorsList = function () {
var reqData = {
"GetInvitedVendorsList": {
"PageNo": $scope.currentPage,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF
}
};
if ($scope.invitationListFilter.Name)
reqData.GetInvitedVendorsList.Filter = { "VendorsFilter_Name": $scope.invitationListFilter.Name };
$rootScope.Page.trackLoading('invitation-list');
appInfo.getServerData(reqData).then(function (response) {
pagingData = [];
$scope.Invitations = null;
if (response.ResponseCode == 200 && response.Data) {
$scope.Invitations = response.Data.Vendors;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPrograms = response.Data.Paginator.total_vendors
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
$rootScope.Page.untrackLoading('invitation-list');
});
};
$scope.init = function () {
$scope.Invitation = {
Description: null,
LastName: null,
FirstName: null,
Email: null
}
$scope.invitationListFilter = {
Name: null
}
$scope.getVendorsList();
}
if ($rootScope.CompanyPreferences) {
$scope.init();
} else
$rootScope.$on('company-loaded', function (event, eSrc) {
$scope.init();
});
$scope.sendInvitations = function () {
if (checkstatus('frmInvitations', $scope)) {
var reqData = {
"InviteVendor": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Email": $scope.Invitation.Email,
"VendorType": ($rootScope.CompanyPreferences.Category == 'Bank') ? 2 : 1,
"FirstName": $scope.Invitation.FirstName,
"LastName": $scope.Invitation.LastName,
"Message": $scope.Invitation.Message
}
}
appInfo.getServerData(reqData).then(function (response) {
if ([200, 201].indexOf(response.ResponseCode) != -1) {
$scope.showFlashMessage('success', response.Message);
$scope.init();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.resendInvite = function () {
$scope.currentVendor = this.InvitationData;
var reqData = {
"InviteVendor": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Email": $scope.currentVendor.Email,
"InvitationCode": $scope.currentVendor.InvitationCode
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
var data = response.Data;
$scope.showFlashMessage('success', 'Invitation Sent');
// $location.path('/venders-list');
} else {
$scope.showFlashMessage('errormza', response.Message);
}
});
}
$scope.viewApplications = function () {
var Invitation = this.InvitationData;
appInfo.getAssociationList(function () {
$scope.appListFilter = {
Name: null,
StartDate: null,
EndDate: null,
BorrowerID: null,
Email: null,
appStatus: null,
Association: _.findWhere($rootScope.AssociationData, { CompanyID: Invitation.CompanyID }),
ProposalLeadID: null,
ProgramID: null,
ProgramName: null
};
var appList = {
"Filter": $scope.appListFilter,
"currentPage": $scope.currentPage,
"SortBy": $scope.appSort
};
Storage.setItem('appList', appList);
$location.path('/applications');
});
}
$scope.viewPrograms = function () {
var programListFilter = {
BankID: this.InvitationData.CompanyID,
BankName: this.InvitationData.CompanyName
};
Storage.setItem('programListFilter', programListFilter);
$location.path('/program-dashboard');
}
$scope.$watch('invitationListFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue)
$scope.getVendorsList();
}, 700));
}])
// Preferences Controller
.controller('preferencesCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', '$stateParams', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage, $stateParams) {
$scope.showpopup = 1;
$scope.showflag = TRUE;
$scope.FormData = [];
$scope.LoanType = $scope.IsCorpOnlyBusinessLoanAllowed = $scope.LoanType2 = $scope.HomePage = $scope.DefaultAppWorkFlow = $scope.HomePageDesign = $scope.Heading = $scope.HeadingDescription = null;
var init = function () {
appInfo.getProgramTypeList(function () {
var i = 0, p = null;
angular.forEach($scope.ProgramTypeList, function (val, key) {
p = {
ProgramTypeID: val.ProgramTypeID,
AllowedPrograms: 0
};
$scope.CompanyPreferences.offeredProgramData = $scope.CompanyPreferences.offeredPrograms[i];
if ($scope.CompanyPreferences.offeredProgramData && $scope.CompanyPreferences.offeredPrograms.length && $scope.CompanyPreferences.offeredProgramData.ProgramTypeID == val.ProgramTypeID) {
p.PreferedProgramTypeOfferID = $scope.CompanyPreferences.offeredProgramData.PreferedProgramTypeOfferID;
p.AllowedPrograms = $scope.CompanyPreferences.offeredProgramData.AllowedPrograms;
i++;
}
$scope.FormData.push(p);
});
});
if (!$rootScope.CompanyPreferences.LoanType) {
$scope.showflag = FALSE;
return;
}
$scope.HomePageDesign = $rootScope.CompanyPreferences.HomePageDesign;
$scope.LoanType = $rootScope.CompanyPreferences.LoanType;
$scope.LoanType2 = $rootScope.CompanyPreferences.LoanType2;
$scope.IsCorpOnlyBusinessLoanAllowed = $rootScope.CompanyPreferences.IsCorpOnlyBusinessLoanAllowed ? 'yes' : 'no';
$scope.HomePage = $rootScope.CompanyPreferences.DefaultAppWorkFlow;
$scope.Heading = $rootScope.CompanyPreferences.Heading;
$scope.HeadingDescription = $rootScope.CompanyPreferences.HeadingDescription;
// $scope.Heading=$scope.HeadingDescription
// switch($rootScope.CompanyPreferences.LoanType){
// case 'Personalloan':
// $scope.LoanType2='PersonalLoanHomePage';
// break;
// case 'Businessloan':
// $scope.LoanType2='BusinessLoanHomePage';
// break;
// case 'Both':
// $scope.LoanType2='BothLoanHomePage';
// break;
// }
// if(RELEASE_VERSION.split('-')[1] == '4'){
// $scope.LoanType2='BothLoanHomePage';
// }
// else{
// $scope.LoanType2='BusinessLoanHomePage';
// }
}
if ($rootScope.CompanyPreferences) {
init();
}
else {
$rootScope.$on('company-loaded', function () {
init();
});
}
$scope.changePreferences = function (State, PopupID) {
$scope.currentstate = State;
switch (PopupID) {
case 1:
$scope.showpopup = PopupID;
if (State == 'Back')
$scope.HomePageDesign = $scope.HomePage = $scope.LoanType2 = $scope.IsCorpOnlyBusinessLoanAllowed = null;
break;
case 2:
if (State == 'Next')
$scope.showpopup = PopupID;
else {
if ($rootScope.CompanyPreferences.Category == 'Company') {
if ($scope.LoanType == 'Both')
$scope.showpopup = 4;
else
$scope.showpopup = 2;
}
else
$scope.showpopup = ($scope.LoanType2 == 'BothLoanHomePage') ? 4 : 5;
$scope.HomePageDesign = $scope.LoanType2 = $scope.IsCorpOnlyBusinessLoanAllowed = null;
}
break;
case 3:
if (State == 'Next') {
if (!$scope.HomePage) {
$scope.showFlashMessage("error", 'Select Default Homepage.');
return;
}
if ($scope.LoanType == "Both")
$scope.showpopup = 4;
else if ($rootScope.CompanyPreferences.Category == 'Bank')
$scope.showpopup = 5;
else {
if ($scope.LoanType == 'Business')
$scope.showpopup = 3;
else
$scope.showpopup = 6;
}
}
else {
$scope.IsCorpOnlyBusinessLoanAllowed = $scope.HomePageDesign = $scope.LoanType2 = null;
$scope.showpopup = 2;
}
break;
case 4:
if (State == 'Next') {
if (!$scope.IsCorpOnlyBusinessLoanAllowed) {
$scope.showFlashMessage("error", 'Select Check box.');
return;
}
$scope.showpopup = 6;
}
else {
$scope.HomePageDesign = $scope.LoanType2 = $scope.IsCorpOnlyBusinessLoanAllowed = null;
if ($scope.LoanType == 'Both') {
$scope.showpopup = 4;
}
else {
$scope.showpopup = 2;
}
}
break;
case 5:
if (State == 'Next') {
if (!$scope.LoanType2) {
$scope.showFlashMessage("error", 'Select any work flow.');
return;
}
$scope.errorHeadingfield = $scope.errorHeadingDescriptionfield = null;
if ($scope.LoanType2 == 'BothLoanHomePage') {
$scope.showpopup = 3;
break;
}
if ($rootScope.CompanyPreferences.Category == 'Company') {
if ($scope.LoanType == 'Personal')
$scope.showpopup = 6;
else
$scope.showpopup = 3;
}
else
$scope.showpopup = 5;
}
else {
if ($scope.LoanType == 'Personal')
if ($rootScope.CompanyPreferences.Category == 'Company') {
if ($scope.LoanType == 'Personal')
$scope.showpopup = 2;
else
$scope.showpopup = 3;
}
else
$scope.showpopup = 5;
else
$scope.showpopup = 3;
}
break;
case 6:
if (State == 'Next') {
if (!$scope.HomePageDesign) {
$scope.showFlashMessage("error", 'Select check box.');
return;
}//console.log($scope.LoanType,$scope.HomePageDesign);
if (($scope.HomePageDesign == 'HomePageWithQuote') && (!$scope.HeadingDescription || !$scope.Heading)) {
$scope.errorHeadingfield = $scope.Heading ? null : 'Heading is required.';
$scope.errorHeadingDescriptionfield = $scope.HeadingDescription ? null : 'Heading Description is required.';
return;
}
$scope.errorHeadingfield = $scope.errorHeadingDescriptionfield = null;
if ($scope.LoanType == 'Both' || $scope.LoanType == 'Business') {
$scope.showpopup = 3;
}
else {
$scope.showpopup = 6;
}
}
break;
case 7:
$scope.SetPreferences();
$scope.showpopup = 7;
}
}
$scope.demo = function () {
if (($scope.HomePageDesign == 'HomePageWithQuote') && !$scope.HeadingDescription && !$scope.Heading) {
$scope.errorHeadingfield = 'Heading is required.';
$scope.errorHeadingDescriptionfield = 'Heading Description is required.';
return;
}
$scope.errorHeadingfield = $scope.errorHeadingDescriptionfield = null;
}
$scope.SetPreferences = function () {
var reqData = {
"SetCompanyPreferences": {
"LoanType": $scope.LoanType,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ProgramOfferData": $scope.FormData,
"HomePageStyle": $scope.HomePageDesign,
"LoanType2": $scope.LoanType2 ? $scope.LoanType2 : null
}
};
// if($scope.LoanType=='Both')
if ($scope.LoanType2 == 'BothLoanHomePage') {
reqData.SetCompanyPreferences.HomePageNo = 4;
reqData.SetCompanyPreferences.HomePageStyle = 'HomePageWithCalculator';
}
else {
reqData.SetCompanyPreferences.HomePageNo = 3;
}
if ($scope.HomePage) {
reqData.SetCompanyPreferences.DefaultAppWorkFlow = $scope.HomePage;
}
if ($scope.IsCorpOnlyBusinessLoanAllowed == 'yes')
reqData.SetCompanyPreferences.IsCorpOnlyBusinessLoanAllowed = 1;
else if ($scope.IsCorpOnlyBusinessLoanAllowed == 'no')
reqData.SetCompanyPreferences.IsCorpOnlyBusinessLoanAllowed = 0;
if ($scope.Heading) {
reqData.SetCompanyPreferences.Heading = $scope.Heading;
reqData.SetCompanyPreferences.HeadingDescription = $scope.HeadingDescription;
}
if ($scope.HomePage == 'LeadApplication') {
reqData.SetCompanyPreferences.HomePageStyle = 'LeadApplication';
reqData.SetCompanyPreferences.HomePageNo = 5;
}
if ($scope.HomePage != 'LeadApplication' && $rootScope.CompanyPreferences.Category == 'Company') {
reqData.SetCompanyPreferences.HomePageStyle = 'HomePageWithCalculator';
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
// Storage.clear();
$timeout(function () {
location.reload();
}, 2000);
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.updateLogo = function (e, f) {
$scope.uploadPercentage = '0%';
if (f) {
var reqData = {
"UploadFile": {
"ModuleName": 'CompanyBackGroundImage',
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"File": f
}
};
appInfo.uploadFile(reqData).then(function (response) {
var msgType = 'error';
if (response.ResponseCode == 200) {
$rootScope.CompanyPreferences.BackgroundImage = response.Data.MediaURL;
msgType = 'success';
}
$scope.showFlashMessage(msgType, response.Message);
// $scope.checkEligibility();
}, function () {
$scope.uploadPercentage = '0%';
// $scope.checkEligibility();
}, function (progressPercentage) {
$scope.uploadPercentage = (progressPercentage != '100%') ? progressPercentage : '0%';
});
}
}
$scope.$watch('LoanType', function (newValue, oldValue) {
if (newValue != oldValue) {
if ($scope.LoanType == "Business")
$scope.LoanType2 = "BusinessLoanHomePage";
if ($scope.LoanType == "Personal")
$scope.LoanType2 = "PersonalLoanHomePage";
}
});
}])
// borrowers view
.controller('borrowerviewCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$sce', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage, $stateParams, $state,$sce) {
$scope.LoanCalculatorS4 = $sce.trustAsResourceUrl($rootScope.siteURL+'company/LoanCalculator/S4');
$scope.IsChecked = TRUE;
$scope.PersonalGuarantor = {};
$scope.personalGuarantor = 'False';
$scope.pg = {
isPersonalGuarantor: false
}
// $scope.Login=null;
$scope.FlagForSavePartialApp = true;
var init = function () {
appInfo.getIndustryTypes(function () {
appInfo.getStates(function () {
if ($scope.SignIn && $state.current.name == 'monthly-quote') {
$scope.newApplication($scope.CompanyPreferences.DefaultAppWorkFlow, $scope.mapPartialAppData);
} else
$scope.mapPartialAppData(function () {
switch ($state.current.name) {
case 'custom-quote':
$scope.prepareSliderConfig();
break;
}
});
});
setTimeout(function(){
$('#PersonalGuarantor_StateID').trigger('chosen:updated');
},1000)
});
appInfo.getSalesPersons(function () {
$scope.SalesPerson = null;
});
}
if ($rootScope.CompanyPreferences)
init();
else
$rootScope.$on('company-loaded', init);
$scope.getExperianRate = function () {
// if($scope.Login && $scope.Login.Password!=$scope.Login.ConfirmPassword){
// $scope.showFlashMessage('error','Password & confirm password didnot match.');return;
// }
if ($('#SSNCtrlID').attr('default_workflow') == 'check' && $('#SSNCtrlID').val() == "") {
$scope.showFlashMessage('error', 'Please Fill Social Security Number');
return false;
}
if (checkstatus('form1', $scope) || $rootScope.SignIn) {
$scope.saveSignAppData();
}
else {
focusOnErrorItem();
}
}
$scope.noPGPopUp = function () {
if ($scope.pg.isPersonalGuarantor){
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-personal-gurantor.html',
scope: $scope,
className: 'ng-popup ngdialog-theme-default personal-guarntor'
});
$scope.Noguarantor = function () {
ngDialog.close();
$scope.personalGuarantor = 'True';
}
$scope.closeNoPGDialog = function () {
$scope.personalGuarantor = 'False';
$scope.pg.isPersonalGuarantor = false;
ngDialog.close();
}
}
else{
$scope.personalGuarantor = 'False';
$scope.pg.isPersonalGuarantor = false;
}
}
$scope.CreatePartialApp = function () {
var requestedFlow = false;
if ($rootScope.SignIn) {
var reqData = {
"FetchPreviousAppData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"RequestedFlow": requestedFlow,
"LoanData": $scope.LoanData
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
var PartialApplications = response.Data;
if ($state.current.name == 'monthly-quote') {
PartialApplication.fixedAmount = true;
PartialApplication.LoanData.ApplicationHome.FinanceAmount = parseFloat($state.params.Amount);
PartialApplication.LoanData.ApplicationHome.FinanceTenure = parseInt($state.params.tenure);
}
Storage.setItem('PartialApplications', PartialApplications);
if ($rootScope.hideEMI)
delete $rootScope.hideEMI;
delete $rootScope.custompartialApp;
$location.path('/borrower-view-rate').replace();
} else {
$rootScope.showFlashMessage('error', response.Message);
}
});
}
}
// Function for LeadApplication workflow
$scope.saveSignLeadApplicationData = function (targetURL, customForm) {
if (checkstatus(customForm, $scope)) {
var PartialAppUID = Form1Data = Form2Data = Form3Data = LoanData = null;
Form1Data = {
"SignUpBusiness1": {
"Login_LoginKeyword": null,
"Login_Password": null,
"Users_StateID": null
}
};
var FormNo = 'borrower';
var PartialAppUID = Form1Data = Form2Data = Form3Data = LoanData = null;
if ($scope.PartialApplications && $scope.PartialApplications.PartialAppUID) {
PartialAppUID = $scope.PartialApplications.PartialAppUID;
};
with ($scope.LoanData) {
if (_.isFunction(FinanceAmount.replace))
var finAmount = parseInt(FinanceAmount.replace(',', ''));
else
var finAmount = parseInt(FinanceAmount);
if (isNaN(finAmount)) {
finAmount = $rootScope.CompanyPreferences.DefaultAmount;
} else if (!(LoanData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : $rootScope.CompanyPreferences.DefaultCreditScoreID,
"FinanceAmount": (FinanceAmount) ? finAmount : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && _.isObject(FinanceTenure)) ? FinanceTenure.Term : (_.isNumber(FinanceTenure) ? FinanceTenure : $rootScope.CompanyPreferences.DefaultLoanTerm),
"FinanceTimeInBusiness": (FinanceTimeInBusiness && (typeof FinanceTimeInBusiness == 'object')) ? parseInt(FinanceTimeInBusiness.TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID,
"CommissionPoints": CommissionPoints
}))) {
// Handle Error
}
LoanData.ProgramLoanType = _.isEmpty($scope.LoanData.ProgramLoanType) == false && _.isObject($scope.LoanData.ProgramLoanType) ? $scope.LoanData.ProgramLoanType.key : $rootScope.CompanyPreferences.LoanType;
//LoanData.ProgramLoanType = (typeof ProgramLoanType == "undefined") ? 'Business' : ProgramLoanType;
LoanData.FinancePurposeID = [];
for (var i in $scope.LoanData.FinancePurpose) {
if (typeof $scope.LoanData.FinancePurpose[i] == 'object')
LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i].FinancePurposeID);
else
LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i]);
}
}
if ($rootScope.hideEMI) {
LoanData.hideEMI = $rootScope.hideEMI;
}
with ($scope.Business) {
Form2Data = {
"SignUpBusiness2": {
Business_LegalStructureName: (LegalStructure && (typeof LegalStructure == 'object')) ? LegalStructure.LegalStructureID : null,
Business_Month: (Month && (typeof Month == 'object')) ? Month.key : null,
Business_Year: (Year && (typeof Year == 'object')) ? Year.Year : null,
Business_Address1: Address1,
Business_Address2: Address2,
Business_CityID: City,
Business_Postal: PostalCode,
Business_StateID: 12,//(StateID && (typeof StateID == 'object'))?StateID.StateID:null,
Business_PhoneNumber: PhoneNumber,
Business_ContactName: ContactName,
Business_ContactNumber: ContactNumber,
Business_BusinessName: Name,
Business_DBA: DBA,
Business_TaxID: TaxID,
// Business_IndustryTypes:(IndustryTypes && typeof IndustryTypes == 'object')?IndustryTypes.IndustryTypeID:null,
Business_IndustryTypes: [],
Business_EquipmentDescription: $scope.Equipment.Description,
Business_PurposeOfPurchase: ($scope.Equipment.PurposeOfPurchase && typeof $scope.Equipment.PurposeOfPurchase == 'object') ? $scope.Equipment.PurposeOfPurchase.key : null,
}
};
var medicalDetailsRequired = false;
if (_.isArray($scope.Business.IndustryTypes)) {
for (var j in $scope.Business.IndustryTypes) {
Form2Data.SignUpBusiness2.Business_IndustryTypes.push($scope.Business.IndustryTypes[j].IndustryTypeID);
if (!medicalDetailsRequired && [7, 23, 28].indexOf($scope.Business.IndustryTypes[j].IndustryTypeID) != -1) {
medicalDetailsRequired = true;
}
}
} else {
// Handle Industry Type is not an array
Form2Data.SignUpBusiness2.Business_IndustryTypes.push($scope.Business.IndustryTypes.IndustryTypeID);
if (!medicalDetailsRequired && [7, 23, 28].indexOf($scope.Business.IndustryTypes.IndustryTypeID) != -1) {
medicalDetailsRequired = true;
}
}
if (medicalDetailsRequired) {
Form2Data.SignUpBusiness2.Business_MedicalLicense = $scope.Medical.License;
Form2Data.SignUpBusiness2.Business_MedicalLicenseIssueDate = $scope.Medical.LicenseIssueDate;
Form2Data.SignUpBusiness2.Business_MedicalLicenseStateID = ($scope.Medical.LicenseIssueState && typeof $scope.Medical.LicenseIssueState == 'object') ? $scope.Medical.LicenseIssueState.StateID : null;
Form2Data.SignUpBusiness2.Business_MedicalSpecialityDescription = $scope.Medical.SpecialityDescription;
}
}
with ($scope.PrimaryOwner) {
Form3Data = {
"SignUpBusiness3": {
"Users_FirstName": FirstName,
"Users_LastName": LastName,
"Users_Email": Email,
"Users_MobileNumber": MobileNumber,
"Users_Address1": Address1,
"Users_Address2": Address2,
"Users_CityID": City,
"Users_StateID": (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
"Users_Postal": PostalCode,
"Users_SocialSecurityNumber": SocialSecurityNumber,
"Users_PercentageOwnership": PercentageOwnership,
"AdditionalOwners": null
}
};
// console.log($scope.BusinessPartners);
if (!_.isUndefined($scope.BusinessPartners)) {
Form3Data.SignUpBusiness3.AdditionalOwners = $scope.BusinessPartners;
}
if (SocialSecurityNumber && SocialSecurityNumber.length)
Form3Data.Users_SocialSecurityNumberView = '***-**-' + SocialSecurityNumber.substr(SocialSecurityNumber.length - 4, 4);
}
if (checkstatus('frmCustomQuote', $scope)) {
$rootScope.Page.trackLoading('save-partial-app');
var reqData = {
"SavePartialAppData": {
"LoginSessionKey": ($rootScope.SignIn) ? $rootScope.SignIn.LoginSessionKey : null,
"Form": FormNo,
"Form1Data": Form1Data,
"Form2Data": Form2Data,
"Form3Data": Form3Data,
"LoanData": { 'ApplicationHome': LoanData },
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
'AppWorkFlow': $rootScope.CompanyPreferences.DefaultAppWorkFlow,
"PartialAppUID": PartialAppUID,
"ProposalID": $scope.PartialApplications.ProposalID
}
};
$scope.saveWizardData(targetURL, reqData);
$rootScope.Page.untrackLoading('save-partial-app');
};
} else {
focusOnErrorItem();
}
}
$scope.saveSignAppData = function (targetURL, customForm) {
if (customForm && !checkstatus(customForm, $scope))
return false;
$scope.LoanData.ProgramLoanType = 'Business';
if (_.isUndefined($scope.LoanData.ProgramLoanType) && $state.current.name == 'custom-quote') {
$scope.showFlashMessage('error', 'Please Choose Loan Type');
return false;
}
if ($scope.LoanData.ProgramLoanType == 'Personal') {
if (!$scope.LoanData.FinancePurpose)
return false;
$scope.LoanData.FinancePurposeID = _.isObject($scope.LoanData.FinancePurpose) ? $scope.LoanData.FinancePurpose.FinancePurposeID : 1;
for (var i in $scope.LoanData.FinancePurpose) {
if (typeof $scope.LoanData.FinancePurpose[i] == 'object')
$scope.LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i].FinancePurposeID);
else
$scope.LoanData.FinancePurposeID.push($scope.LoanData.FinancePurpose[i]);
}
}
if ($scope.PartialApplications && _.isUndefined($scope.PartialApplications.DefaultAppWorkFlow))
$scope.PartialApplications.DefaultAppWorkFlow = $scope.CompanyPreferences.DefaultAppWorkFlow;
if (_.isString($scope.LoanData.FinanceAmount))
$scope.LoanData.FinanceAmount = $scope.LoanData.FinanceAmount.replace(',', '');
$scope.LoanData.FinanceTenure = _.isObject($scope.LoanData.FinanceTenure)?$scope.LoanData.FinanceTenure.Term:$scope.CompanyPreferences.DefaultLoanTerm;
$scope.LoanData.FinanceCredit = _.isObject($scope.LoanData.FinanceCredit)?$scope.LoanData.FinanceCredit.CreditScoreID:$scope.CompanyPreferences.DefaultCreditScoreID;
if ($scope.appliedProgram.ProgramType == 'Business')
$scope.LoanData.FinanceTimeInBusiness = $scope.LoanData.FinanceTimeInBusiness.TimeInBusinessID;
var cacheData = { 'LoanData': { 'ApplicationHome': $scope.LoanData } };
// added for custome-quote page
setTimeout(function () {
$('#loanTerm option[label="' + $scope.LoanData.FinanceTenure + '"]').attr("selected", "selected");
var FinanceTenure = $('#loanTerm option[selected="selected"]').val();
$('#loanTerm').val(FinanceTenure).trigger('chosen:updated');
$('#PrimaryOwnerFinanceTimeInBusiness option[label="' + $scope.LoanData.FinanceTimeInBusiness.Title + '"]').attr("selected", "selected");
var FinanceTimeInBusiness = $('#PrimaryOwnerFinanceTimeInBusiness option[selected="selected"]').val();
$('#PrimaryOwnerFinanceTimeInBusiness').val(FinanceTimeInBusiness).trigger('chosen:updated');
}, 2000);
if (_.isFunction($scope.partialCachePreparation))
$scope.partialCachePreparation(cacheData, $scope);
if ($scope.PartialApplications) {
if ($scope.PartialApplications.PartialAppUID) {
$scope.PartialApplications.LoanData = { 'ApplicationHome': $scope.LoanData };
cacheData = $scope.PartialApplications;
} if ($scope.PartialApplications.fixedAmount)
cacheData.fixedAmount = true;
}
Storage.setItem('PartialApplications', cacheData);
console.log("ocean",$scope.PartialApplications);
if ($scope.PartialApplications) {
console.log('LeadApplication',$scope.CompanyPreferences)
switch ($scope.PartialApplications.DefaultAppWorkFlow.toLowerCase()) {
case 'selfcredit':
case 'selfcreditwithchooselender':
return $scope.$parent.saveSignAppData(targetURL);
break;
case 'experianwithchooselender':
case 'experian':
case 'LeadApplication':
case 'experianwithproductmonthlyquote':
if (!targetURL)
$state.go('borrower-view-rate');
break;
}
}
switch ($state.current.name) {
case 'borrower-view-rate':
var FormNo = 'borrower';
break;
case 'custom-quote':
case 'monthly-quote':
case 'calculator':
case 'home':
case 'signin':
case 'recovery':
case 'signout':
if (targetURL) {
$state.go('custom-quote');
break;
}
switch (($scope.PartialApplications ? $scope.PartialApplications.DefaultAppWorkFlow : $scope.CompanyPreferences.DefaultAppWorkFlow).toLowerCase()) {
case 'selfcredit':
case 'selfcreditwithchooselender':
// $state.go('create-account.ca-create-account');
break;
case 'experianwithchooselender':
case 'experian':
case 'experianwithproductmonthlyquote':
if (_.isObject($scope.PartialApplications.Form2Data)) {
$scope.PartialApplications.LoanData = { 'ApplicationHome': $scope.LoanData };
Storage.setItem('PartialApplications', $scope.PartialApplications);
}
$state.go('borrower-view-rate');
break;
}
break;
default:
$scope.$parent.saveSignAppData();
}
if (FormNo == 'borrower' && ($scope.Login || ($scope.SignIn && $scope.SignIn.LoginSessionKey))) {
if (!$scope.SignIn) {
if (!$scope.Login.LoginKeyword && !$scope.PrimaryOwner.MobileNumber) {
$scope.showFlashMessage('error', 'Please enter mobile no. of email for process further.'); return;
}
// if($scope.Login.Password != $scope.Login.ConfirmPassword){
// $scope.showFlashMessage('error',"Passwords Don't Match.");return;
// }
}
var PartialAppUID = Form1Data = Form2Data = Form3Data = LoanData = PGFormData = null;
if ($scope.PartialApplications && $scope.PartialApplications.PartialAppUID) {
PartialAppUID = $scope.PartialApplications.PartialAppUID;
};
switch (FormNo) {
case 'borrower':
if (!$scope.SignIn) {
with ($scope.Login) {
Form1Data = {
"SignUpBusiness1": {
"Login_LoginKeyword": LoginKeyword,
"Login_Password": Password
}
};
}
Form1Data.SignUpBusiness1.Users_StateID = $scope.PrimaryOwner.StateID ? $scope.PrimaryOwner.StateID.StateID : null;
}
if (!$scope.LoanData.FinanceTimeInBusiness)
$scope.LoanData.FinanceTimeInBusiness = $scope.TimeInBusiness[1];
var finAmount = parseInt($scope.LoanData.FinanceAmount);
if (isNaN(finAmount)) {
finAmount = $rootScope.CompanyPreferences.DefaultAmount;
} else if (!(LoanData = appInfo.getCalcData({
"FinancePurposeID": ($scope.LoanData.FinancePurpose && _.isObject($scope.LoanData.FinancePurpose)) ? $scope.LoanData.FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": ($scope.LoanData.FinanceCredit && _.isObject($scope.LoanData.FinanceCredit)) ? $scope.LoanData.FinanceCredit.CreditScoreID : 1,
"FinanceAmount": ($scope.LoanData.FinanceAmount) ? finAmount : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": ($scope.LoanData.FinanceTenure && (_.isObject($scope.LoanData.FinanceTenure) || _.isNumber($scope.LoanData.FinanceTenure))) ? (_.isObject($scope.LoanData.FinanceTenure) ? $scope.LoanData.FinanceTenure.Term : $scope.LoanData.FinanceTenure) : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": ($scope.LoanData.FinanceTimeInBusiness && _.isObject($scope.LoanData.FinanceTimeInBusiness)) ? parseInt($scope.LoanData.FinanceTimeInBusiness.TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID,
"CommissionPoints": !_.isUndefined($scope.LoanData.CommissionPoints) ? $scope.LoanData.CommissionPoints : $scope.CompanyPreferences.DefaultCommissionCap
}))) {
// Handle Error
}
if ($rootScope.hideEMI) {
LoanData.hideEMI = $rootScope.hideEMI;
}
with ($scope.Business) {
Form2Data = {
"SignUpBusiness2": {
// Business_LegalStructureName:(LegalStructure && (typeof LegalStructure == 'object'))?LegalStructure.LegalStructureID:null,
Business_Month: (Month && (typeof Month == 'object')) ? Month.key : null,
Business_Year: (Year && (typeof Year == 'object')) ? Year.Year : null,
Business_Address1: Address1,
Business_Address2: (typeof Address2 == 'undefined') ? null : Address2,
Business_CityID: City,
Business_Postal: PostalCode,
Business_StateID: (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
Business_ContactName: (typeof ContactName == 'undefined') ? null : ContactName,
Business_ContactNumber: ContactNumber,
Business_BusinessName: Name,
Business_DBA: (typeof DBA == 'undefined') ? null : DBA,
Business_TaxID: (typeof TaxID == 'undefined') ? null : TaxID,
Business_IndustryTypes: (IndustryTypes && typeof IndustryTypes == 'object') ? IndustryTypes.IndustryTypeID : null,
Business_EquipmentDescription: $scope.Equipment ? $scope.Equipment.Description : null,
Business_PurposeOfPurchase: ($scope.Equipment && $scope.Equipment.PurposeOfPurchase && typeof $scope.Equipment.PurposeOfPurchase == 'object') ? $scope.Equipment.PurposeOfPurchase.key : null,
Business_CreditScoreType: (typeof CreditScoreType != 'undefined' && typeof CreditScoreType == 'object') ? CreditScoreType.CreditScoreID : null
}
};
if (IndustryTypes && [7, 23, 28].indexOf(IndustryTypes.IndustryTypeID) != -1 && _.isObject($scope.Medical)) {
Form2Data.SignUpBusiness2.Business_MedicalLicense = $scope.Medical.License;
Form2Data.SignUpBusiness2.Business_MedicalLicenseIssueDate = $scope.Medical.LicenseIssueDate;
Form2Data.SignUpBusiness2.Business_MedicalLicenseStateID = ($scope.Medical.LicenseIssueState && typeof $scope.Medical.LicenseIssueState == 'object') ? $scope.Medical.LicenseIssueState.StateID : null;
Form2Data.SignUpBusiness2.Business_MedicalSpecialityDescription = $scope.Medical.SpecialityDescription;
}
}
with ($scope.PrimaryOwner) {
Form3Data = {
"SignUpBusiness3": {
"Users_FirstName": FirstName,
"Users_LastName": LastName,
"Users_MobileNumber": MobileNumber,
"Users_Address1": Address1,
"Users_Address2": (typeof Address2 != 'undefined') ? Address2 : null,
"Users_CityID": City,
"Users_StateID": (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
"Users_Postal": PostalCode,
"AdditionalOwners": null
}
};
}
if ($scope.PartialApplications.DefaultAppWorkFlow == 'LeadApplication' && $scope.personalGuarantor=='False') {
with ($scope.PersonalGuarantor) {
PGFormData = {
"SignUpBusiness4": {
"Guarantor_FirstName": (typeof FirstName != 'undefined') ? FirstName : null,
"Guarantor_LastName": (typeof LastName != 'undefined') ? LastName : null,
"Guarantor_MobileNumber": (typeof MobileNumber != 'undefined') ? MobileNumber : null,
"Guarantor_Address1": (typeof Address1 != 'undefined') ? Address1 : null,
"Guarantor_Address2": (typeof Address2 != 'undefined') ? Address2 : null,
"Guarantor_CityID": (typeof City != 'undefined') ? City : null,
"Guarantor_StateID": (typeof StateID != 'undefined' && typeof StateID == 'object') ? StateID.StateID : null,
"Guarantor_Postal": (typeof PostalCode != 'undefined') ? PostalCode : null
}
};
}
}
// if($scope.PartialApplications)
// Form3Data.SignUpBusiness3.Users_Email=$scope.PartialApplications.Form1Data.SignUpBusiness1.Login_LoginKeyword;
// else
Form3Data.SignUpBusiness3.Users_Email = $scope.Login.LoginKeyword;
}
if ($scope.FlagForSavePartialApp && !$scope.SignIn) {
reqData1 = {
"CheckLoginKeywordExist": {
"LoginKeyword": $scope.Login.LoginKeyword,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
};
appInfo.getServerData(reqData1).then(function (response) {
if (response.ResponseCode != 200) {
$rootScope.ngConfirm(response.Message + ' Would you like to login and apply?', function () {
$rootScope.clickToOpen();
});
}
else {
$scope.FlagForSavePartialApp = TRUE;
}
});
}
if (!$scope.SignIn) {
if (checkstatus('form1', $scope))
$scope.savePartialApplicationData(FormNo, Form1Data, Form2Data, Form3Data, PartialAppUID, $scope.SalesPerson ? $scope.SalesPerson.ID : null,PGFormData)
else
focusOnErrorItem();
}
else {
$scope.savePartialApplicationData(FormNo, Form1Data, Form2Data, Form3Data, PartialAppUID, $scope.SalesPerson ? $scope.SalesPerson.ID : null,PGFormData)
}
}
setTimeout(function () {
$(".chosen-multiple-single").chosen({ max_selected_options: 1 });
}, 2000);
}
$scope.init = function () {
$scope.Invitation = {
Description: null,
LastName: null,
FirstName: null,
Email: null
}
if ($scope.CompanyPreferences.Category == 'Bank')
$scope.Invitation.PartnerSideCommissionCap = null;
else
$scope.Invitation.VendorSideCommissionCap = null;
$scope.invitationListFilter = {
Name: null
}
switch ($state.current.name) {
case 'borrower-view-rate':
var FormNo = 'borrower';
break;
case 'calculator':
case 'home':
if (targetURL) {
$state.go('custom-quote');
break;
}
if (['selfcredit', 'selfcreditwithchooselender'].indexOf($scope.CompanyPreferences.DefaultAppWorkFlow.toLowerCase()) == -1) {
Storage.setItem('PartialAppData', { 'LoanData': $scope.LoanData });
$state.go('borrower-view-rate');
}
break;
default:
$scope.$parent.saveSignAppData();
}
if (FormNo == 'borrower' && ($scope.Login || ($scope.SignIn && $scope.SignIn.LoginSessionKey))) {
if (!$scope.SignIn) {
if (!$scope.Login.LoginKeyword && !$scope.PrimaryOwner.MobileNumber) {
$scope.showFlashMessage('error', 'Please enter mobile no. of email for process further.'); return;
}
// if($scope.Login.Password != $scope.Login.ConfirmPassword){
// $scope.showFlashMessage('error',"Passwords Don't Match.");return;
// }
}
var PartialAppUID = Form1Data = Form2Data = Form3Data = LoanData = null;
if ($scope.PartialApplications && $scope.PartialApplications.PartialAppUID) {
PartialAppUID = $scope.PartialApplications.PartialAppUID;
};
switch (FormNo) {
case 'borrower':
if (!$scope.SignIn) {
with ($scope.Login) {
Form1Data = {
"SignUpBusiness1": {
"Login_LoginKeyword": LoginKeyword,
"Login_Password": Password
}
};
}
Form1Data.SignUpBusiness1.Users_StateID = $scope.PrimaryOwner.StateID ? $scope.PrimaryOwner.StateID.StateID : null;
}
with ($scope.LoanData) {
//var finAmount=parseInt(FinanceAmount.replace(',',''));
var finAmount = parseInt(FinanceAmount);
if (isNaN(finAmount)) {
finAmount = $rootScope.CompanyPreferences.DefaultAmount;
} else if (!(LoanData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : 1,
"FinanceAmount": (FinanceAmount) ? finAmount : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (_.isObject(FinanceTenure) || _.isNumber(FinanceTenure))) ? (_.isObject(FinanceTenure) ? FinanceTenure.Term : FinanceTenure) : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": (FinanceTimeInBusiness && (typeof FinanceTimeInBusiness == 'object')) ? parseInt(FinanceTimeInBusiness.TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID,
"CommissionPoints": CommissionPoints
}))) {
// Handle Error
}
}
if ($rootScope.hideEMI) {
LoanData.hideEMI = $rootScope.hideEMI;
}
with ($scope.Business) {
Form2Data = {
"SignUpBusiness2": {
// Business_LegalStructureName:(LegalStructure && (typeof LegalStructure == 'object'))?LegalStructure.LegalStructureID:null,
Business_Month: (Month && (typeof Month == 'object')) ? Month.key : null,
Business_Year: (Year && (typeof Year == 'object')) ? Year.Year : null,
Business_Address1: Address1,
Business_Address2: (typeof Address2 == 'undefined') ? Address2 : null,
Business_CityID: City,
Business_Postal: PostalCode,
Business_StateID: (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
Business_ContactName: ContactName,
Business_ContactNumber: ContactNumber,
Business_BusinessName: Name,
Business_DBA: DBA,
Business_TaxID: TaxID,
Business_IndustryTypes: (IndustryTypes && typeof IndustryTypes == 'object') ? IndustryTypes.IndustryTypeID : null,
Business_EquipmentDescription: $scope.Equipment.Description,
Business_PurposeOfPurchase: ($scope.Equipment.PurposeOfPurchase && typeof $scope.Equipment.PurposeOfPurchase == 'object') ? $scope.Equipment.PurposeOfPurchase.key : null,
}
};
if (IndustryTypes && [7, 23, 28].indexOf(IndustryTypes.IndustryTypeID) != -1) {
Form2Data.SignUpBusiness2.Business_MedicalLicense = $scope.Medical.License;
Form2Data.SignUpBusiness2.Business_MedicalLicenseIssueDate = $scope.Medical.LicenseIssueDate;
Form2Data.SignUpBusiness2.Business_MedicalLicenseStateID = ($scope.Medical.LicenseIssueState && typeof $scope.Medical.LicenseIssueState == 'object') ? $scope.Medical.LicenseIssueState.StateID : null;
Form2Data.SignUpBusiness2.Business_MedicalSpecialityDescription = $scope.Medical.SpecialityDescription;
}
}
with ($scope.PrimaryOwner) {
Form3Data = {
"SignUpBusiness3": {
"Users_FirstName": FirstName,
"Users_LastName": LastName,
"Users_MobileNumber": MobileNumber,
"Users_Address1": Address1,
"Users_Address2": (typeof Address2 == 'undefined') ? Address2 : null,
"Users_CityID": City,
"Users_StateID": (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
"Users_Postal": PostalCode,
"AdditionalOwners": null
}
};
}
// if($scope.PartialApplications)
// Form3Data.SignUpBusiness3.Users_Email=$scope.PartialApplications.Form1Data.SignUpBusiness1.Login_LoginKeyword;
// else
Form3Data.SignUpBusiness3.Users_Email = $scope.Login.LoginKeyword;
}
if ($scope.FlagForSavePartialApp && !$scope.SignIn) {
reqData1 = {
"CheckLoginKeywordExist": {
"LoginKeyword": $scope.Login.LoginKeyword,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
};
appInfo.getServerData(reqData1).then(function (response) {
if (response.ResponseCode != 200) {
$rootScope.ngConfirm(response.Message + ' Would you like to login and apply?', function () {
$rootScope.clickToOpen();
});
}
else {
$scope.FlagForSavePartialApp = TRUE;
}
});
}
if (!$scope.SignIn) {
if (checkstatus('form1', $scope))
$scope.savePartialApplicationData(FormNo, Form1Data, Form2Data, Form3Data, PartialAppUID)
else
focusOnErrorItem();
}
else {
$scope.savePartialApplicationData(FormNo, Form1Data, Form2Data, Form3Data, PartialAppUID)
}
}
}
$scope.savePartialApplicationData = function (FormNo, Form1Data, Form2Data, Form3Data, PartialAppUID, AssigneeID,PGFormData) {
$rootScope.Page.trackLoading('save-partial-app');
//console.log('sfdsd',PGFormData);
var reqData = {
"SavePartialAppData": {
"LoginSessionKey": ($rootScope.SignIn) ? $rootScope.SignIn.LoginSessionKey : null,
"AssigneeID": AssigneeID,
"Form": FormNo,
"Form1Data": Form1Data,
"Form2Data": Form2Data,
"Form3Data": Form3Data,
"LoanData": { 'ApplicationHome': $scope.LoanData },
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"PartialAppUID": PartialAppUID ? PartialAppUID : null,
'AppWorkFlow': $scope.PartialApplications.DefaultAppWorkFlow,
"ProposalID": $scope.PartialApplications.ProposalID,
"BusinessApplicationPurposeID": ($scope.App.BusinessApplicationPurposeID && (typeof $scope.App.BusinessApplicationPurposeID == 'object')) ? $scope.App.BusinessApplicationPurposeID.BusinessApplicationPurposeID : (typeof $scope.App.BusinessApplicationPurposeID == 'number') ? $scope.App.BusinessApplicationPurposeID : null,
"ThirdParty": $scope.PartialApplications.ThirdParty,
"AnnualRevenueID": ($scope.App.AnnualRevenueID && (typeof $scope.App.AnnualRevenueID == 'object')) ? $scope.App.AnnualRevenueID.AnnualRevenueID : (typeof $scope.App.AnnualRevenueID == 'number') ? $scope.App.AnnualRevenueID : null,
"CreditScoreRangeID": $scope.PartialApplications.CreditScoreRangeID,
}
};
if(PGFormData) {
reqData['SavePartialAppData']["PGFormData"] = PGFormData;
}
if (_.isFunction($scope.prePartialAppSubmit))
$scope.prePartialAppSubmit(reqData, $scope);
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.PartialApplications.PartialAppUID = response.Data.PartialAppUID;
$scope.FlagForSavePartialApp = FALSE;
$scope.submitApplicationData();
$rootScope.Page.untrackLoading('save-partial-app');
} else if (response.ResponseCode != 200) {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.submitApplicationData = function () {
var LoanData = Form3Data = Form2Data = {};
with ($scope.Business) {
Form2Data = {
"BusinessData":
{
LegalStructureID: ((typeof LegalStructure != 'undefined') && _.isObject(LegalStructure)) ? LegalStructure.LegalStructureID : null,
EstablishedMonth: (Month && (typeof Month == 'object')) ? Month.key : null,
EstablishedYear: (Year && (typeof Year == 'object')) ? Year.Year : null,
Address1: Address1,
Address2: (typeof Address2 != 'undefined') ? Address2 : null,
CityID: City,
Postal: PostalCode,
StateID: (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
PhoneNumber: (typeof PhoneNumber != 'undefined') ? PhoneNumber : null,
PrimaryContactNumber: (typeof ContactNumber != 'undefined') ? ContactNumber : null,
BusinessName: (typeof Name != 'undefined') ? Name : null,
BusinessDBA: (typeof DBA != 'undefined') ? DBA : null,
TaxID: (typeof TaxID != 'undefined') ? TaxID : null,
IndustryTypes: [],
EquipmentDescription: $scope.Equipment && $scope.Equipment.Description,
PurposeOfPurchase: ($scope.Equipment && $scope.Equipment.PurposeOfPurchase && typeof $scope.Equipment.PurposeOfPurchase == 'object') ? $scope.Equipment.PurposeOfPurchase.key : null,
}
};
var medicalDetailsRequired = false;
if (_.isArray($scope.Business.IndustryTypes) && $scope.Business.IndustryTypes.length) {
for (var i in $scope.Business.IndustryTypes) {
Form2Data.BusinessData.IndustryTypes.push($scope.Business.IndustryTypes[i].IndustryTypeID);
if (!medicalDetailsRequired && [7, 23, 28].indexOf($scope.Business.IndustryTypes[i].IndustryTypeID) != -1) {
medicalDetailsRequired = true;
}
}
} else if ($scope.CompanyPreferences.DefaultIndustrySelected) {
Form2Data.BusinessData.IndustryTypes.push($scope.CompanyPreferences.DefaultIndustrySelected);
medicalDetailsRequired = [7, 23, 28].indexOf($scope.CompanyPreferences.DefaultIndustrySelected) != -1;
} else {
Form2Data.BusinessData.IndustryTypes.push($scope.Business.IndustryTypes.IndustryTypeID);
if (!medicalDetailsRequired && [7, 23, 28].indexOf($scope.Business.IndustryTypes.IndustryTypeID) != -1) {
medicalDetailsRequired = true;
}
}
if (medicalDetailsRequired && _.isObject($scope.Medical)) {
Form2Data.BusinessData.MedicalLicense = $scope.Medical.License;
Form2Data.BusinessData.MedicalLicenseIssueDate = $scope.Medical.LicenseIssueDate;
Form2Data.BusinessData.MedicalLicenseStateID = ($scope.Medical.LicenseIssueState && typeof $scope.Medical.LicenseIssueState == 'object') ? $scope.Medical.LicenseIssueState.StateID : null;
Form2Data.BusinessData.MedicalSpecialityDescription = $scope.Medical.SpecialityDescription;
}
}
with ($scope.PrimaryOwner) {
Form3Data = {
"UserData":
{
"FirstName": FirstName,
"LastName": LastName,
"MobileNumber": MobileNumber,
"Address1": Address1,
"Address2": (typeof Address2 != 'undefined') ? Address2 : null,
"CityID": City,
"StateID": (StateID && (typeof StateID == 'object')) ? StateID.StateID : null,
"ShortCode": (StateID && (typeof StateID == 'object')) ? StateID.ShortCode : null,
"Postal": (typeof PostalCode != 'undefined') ? PostalCode : null,
"SocialSecurityNumber": SocialSecurityNumber
}
};
}
Form2Data.BusinessData.PrimaryContactName = $scope.PrimaryOwner.FirstName;
// if($scope.PartialApplications)
// Form3Data.UserData.Email=$scope.PartialApplications.Form1Data.SignUpBusiness1.Login_LoginKeyword;
// else
Form3Data.UserData.Email = $scope.Login.LoginKeyword;
// Form1Data.SignUpBusiness1.Users_StateID = $scope.PrimaryOwner.StateID.StateID
var el = angular.element('#financeAmount');
var finAmount = (!$scope.PartialApplications.fixedAmount && el && _.isFunction(el)) ? parseInt(el) : $scope.LoanData.FinanceAmount;
with ($scope.LoanData) {
var minAmount = $rootScope.CompanyPreferences.MinAmount;
var maxAmount = $rootScope.CompanyPreferences.MaxAmount;
if (isNaN(finAmount)) {
finAmount = $rootScope.CompanyPreferences.DefaultAmount;
} else {
LoanData = appInfo.getCalcData({
"FinancePurposeID": (FinancePurpose && (typeof FinancePurpose == 'object')) ? FinancePurpose.FinancePurposeID : 1,
"FinanceCredit": (FinanceCredit && (typeof FinanceCredit == 'object')) ? FinanceCredit.CreditScoreID : (typeof FinanceCredit == 'number') ? FinanceCredit : 1,
"FinanceAmount": (FinanceAmount) ? finAmount : $rootScope.CompanyPreferences.DefaultAmount,
"FinanceTenure": (FinanceTenure && (_.isObject(FinanceTenure) || _.isNumber(FinanceTenure))) ? (_.isObject(FinanceTenure) ? FinanceTenure.Term : FinanceTenure) : $rootScope.CompanyPreferences.DefaultLoanTerm,
"FinanceTimeInBusiness": (FinanceTimeInBusiness && (typeof FinanceTimeInBusiness == 'object')) ? parseInt(FinanceTimeInBusiness.TimeInBusinessID) : $scope.CompanyPreferences.DefaultTimeInBusinessID
});
LoanData.ProgramLoanType = (typeof ProgramLoanType == "undefined") ? $scope.ProgramLoanType : ProgramLoanType;
}
}
// $scope.dataEnable=TRUE;
// if(LoanData && checkstatus('savePartialAppForm',$scope))
// {
// $scope.dataEnable=FALSE;
var reqData = {
"SignUp": {
"Login_LoginKeyword": $scope.Login.LoginKeyword,
"Login_Password": $scope.Login.Password,
"Users_StateID": ($scope.Login.StateID) ? $scope.Login.StateID.StateID : null,
"AdditionalOwners": null,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"DeviceType": 'Web',
"SocialType": 'Web',
"DeviceID": 'Web',
"ResolutionID": $rootScope.uaInfo.ResolutionID,
"UserAgentID": $rootScope.uaInfo.UserAgentID,
"Latitude": null,
"Longitude": null,
"PartialAppUID": $scope.PartialApplications.PartialAppUID,
"NewApplicationType": null,
"DefaultAppWorkFlow": $scope.PartialApplications.DefaultAppWorkFlow,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
},
};
// console.log('asfas',LoanData,Form3Data,Form2Data,$scope.ExperianData)
for (var key in LoanData)
reqData.SignUp[key] = LoanData[key];
for (var key in Form3Data)
reqData.SignUp[key] = Form3Data[key];
for (var key in Form2Data)
reqData.SignUp[key] = Form2Data[key];
if ($rootScope.SignIn) {
reqData.SignUp.NewApplicationType = 'Prefill';
reqData.SignUp.LoginSessionKey = $rootScope.SignIn.LoginSessionKey;
}
if ($scope.SalesPerson) {
reqData.SignUp.AssigneeID = $scope.SalesPerson.ID;
}
if ($scope.ExperianData) {
reqData.SignUp.ExperianData = $scope.ExperianData;
}
if (!$rootScope.SignIn)
reqData.SignUp.AutoLogin = TRUE;
$scope.Page.trackLoading('SignUp');
appInfo.getServerData(reqData).then(function (response) {
if ([200, 201].indexOf(response.ResponseCode) != -1) {
// $scope.showFlashMessage('success',response.Message);
LoanData.CreditScore = $scope.LoanData.CreditScore;
if (!$rootScope.SignIn) {
appInfo.processApplicationLogin(response);
}
var ApplicationData = { 'FetchPreOfferFields': response.Data.isAdditionalInfoRequiredBeforeOffer, ApplicationNumber: response.Data.ApplicationNumber, LoanData: LoanData, 'ApplicationWorkFlow': $scope.PartialApplications.ApplicationWorkFlow ? $scope.PartialApplications.ApplicationWorkFlow : $scope.PartialApplications.DefaultAppWorkFlow };
Storage.setItem('ApplicationData', ApplicationData);
if (EXPERIAN_FETCH_REPORT && $scope.PartialApplications.DefaultAppWorkFlow.toLowerCase() == 'experianwithchooselender' || 'leadapplication') {
if (response.Data.ApplicationCreditScore) {
console.log('herell',response.Data)
$state.go(response.Data.isAdditionalInfoRequiredBeforeOffer ? 'additional-information' : "financing-offers");
}
else {
//$scope.showFlashMessage('error','Unable to provide you with a Pre-Approval, However your application is under review and a funding manager will be in contact shortly.');
$scope.showFlashMessage('success', 'We have received your application. Your application is under review and a funding manager will be in contact shortly.');
setTimeout(function () {
$state.go(response.Data.isAdditionalInfoRequiredBeforeOffer ? 'additional-information' : "applications");
}, 1000);
}
} else {
Storage.setItem('CompletedApplication', {
'ApplicationNumber': response.Data.ApplicationNumber,
'Email': $scope.SignIn.UserDetails.Email
});
if (response.Data.isAdditionalInfoRequiredBeforeOffer) {
$state.go('additional-information');
} else {
$state.go('application-submited');
}
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('SignUp');
}, function () {
$scope.Page.untrackLoading('SignUp');
});
// } else {
// focusOnErrorItem();
// }
}
$scope.isaggred = function () {
if ($scope.IsChecked)
$scope.IsChecked = FALSE;
else
$scope.IsChecked = TRUE;
}
$scope.updateAmount = TRUE;
$scope.updateFinanceAmountValue = TRUE;
$scope.updateFinanceAmount = function () {
if ($scope.LoanData && parseInt($scope.LoanData.FinanceAmount) > 0) {
$scope.updateFinanceAmountValue = !$scope.updateFinanceAmountValue;
if (_.isString($scope.LoanData.FinanceAmount))
$scope.LoanData.FinanceAmount = $scope.LoanData.FinanceAmount.replace(',', '')
} else {
$scope.showFlashMessage('error', 'Please Enter Number');
}
}
}])
// Additional Fields
.controller('additionalFieldsCtrl', ['$rootScope', '$scope', 'appInfo', 'Storage', '$state', '$timeout', function ($rootScope, $scope, appInfo, Storage, $state, $timeout) {
$scope.additionalFields = null;
var ApplicationData = Storage.getItem('ApplicationData');
$scope.redirctToTarget = function (ApplicationWorkFlow) {
switch (ApplicationWorkFlow ? ApplicationWorkFlow.toLowerCase() : $scope.CompanyPreferences.DefaultAppWorkFlow) {
case 'selfcreditwithchooselender':
case 'leadapplication':
case 'experianwithchooselender':
if (ApplicationData.FetchPreOfferFields) {
$state.go('financing-offers');
break;
}
default:
$state.go('application-submited');
Storage.removeItem('ApplicationData');
}
}
if (ApplicationData) {
appInfo.getAdditionalFieldInputs(function (response) {
if (!response.Data || response.Data.length == 0) {
return $scope.redirctToTarget(ApplicationData.ApplicationWorkFlow);
}
$scope.additionalFields = response.Data;
$scope.$parent.LoanData = ApplicationData.LoanData;
$scope.ApplicationNumber = ApplicationData.ApplicationNumber;
$scope.updateFinanceAmountValue = TRUE;
}, ApplicationData);
}
$scope.saveAdditionalFields = function () {
if (checkstatus('frmAdditionalFields', $scope)) {
var reqData = {
"SaveAdditionalFields": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ApplicationNumber": ApplicationData.ApplicationNumber,
"AdditionalData": []
}
};
var configData = null;
for (var i in $scope.additionalFields) {
configData = {
"configID": $scope.additionalFields[i]._id.$id,
fields: []
};
for (var j in $scope.additionalFields[i].Fields) {
var field = $scope.additionalFields[i].Fields[j];
switch (field.type.name) {
case 'Text':
case 'Date':
case 'Paragraph':
case 'List':
if (field.value) {
configData.fields.push({
'name': field.name,
'value': field.value
});
}
break;
case 'Money':
if (field.value) {
configData.fields.push({
'name': field.name,
'value': _.isString(field.value) ? field.value.replace(',', '') : field.value
});
}
break;
case 'MultiChoice':
configData.fields.push({
'name': field.name,
'value': field.optionsValue
});
break;
}
}
reqData.SaveAdditionalFields.AdditionalData.push(configData);
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
//redirect to thirdparty application
if ($rootScope.callback) window.location.href = $rootScope.callback;
var CompletedApplication = Storage.getItem('CompletedApplication');
if (!CompletedApplication)
$state.go('app-details', { ApplicationNumber: ApplicationData.ApplicationNumber, activeTab: 1 });
else
$scope.redirctToTarget(ApplicationData.ApplicationWorkFlow);
} else {
$scope.showFlashMessage('error', response.Message);
}
})
}
}
}])
// Finance offer Collapse Controller
.controller('financeofferCtrl', ['$rootScope', '$scope', 'appInfo', 'Storage', '$state', '$timeout', function ($rootScope, $scope, appInfo, Storage, $state, $timeout) {
$scope.squaredAll = FALSE;
$scope.Program = [];
$scope.shareAppListFilter = { 'currentPage': 1 };
$scope.collapse = 1;
$scope.offer = {};
$scope.affilateMode = false;
$scope.emi = {};
var flag = false;
$scope.getMatchingPrograms = function (callback) {
var reqData = {
"GetMatchingPrograms": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.shareAppListFilter.currentPage,
"ApplicationNumber": ApplicationData.ApplicationNumber,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"Bestmatch": true,
"RecentUpdate": false,
"GetAffilatePrograms": $scope.affilateMode,
"Filter": {
"ShareApplicationsFilter_AssociationID": null
},
"flag": flag
}
};
if ($scope.FinanceTenure) {
reqData.GetMatchingPrograms.Filter.ShareApplicationsFilter_FinanceTenure = $scope.FinanceTenure;
}
$scope.Page.trackLoading('save-partial-app');
$scope.availableTerms = [];
appInfo.getServerData(reqData).then(function (response) {
$scope.Programs = null;
switch (response.ResponseCode) {
case 200:
$scope.Programs = [];
$scope.Page.untrackLoading('save-partial-app');
$scope.ApplicationCreditScore = null;
if (response.Data.Programs) {
$scope.ApplicationCreditScore = response.Data.ApplicationCreditScore;
var LoanData = {};
$scope.Programs = response.Data.Programs;
$timeout(function () {
$scope.$apply(function () {
$scope.Programs[0].selected = true;
if (!$scope.ProgramData.length) {
$scope.checkStatus($scope.Programs[0]);
}
});
}, 300);
$scope.emi = response.Data.EMI;
if ($scope.FinanceTenure > $scope.emi.maxTenure) {
$scope.FinanceTenure = $scope.emi.maxTenure;
}
for (var i = ($scope.emi.minTenure / 12); (i * 12) <= $scope.emi.maxTenure; i++) {
$scope.availableTerms.push(i);
if ((i * 12) == $scope.emi.appliedTenure)
$scope.selected = i - ($scope.emi.minTenure / 12);
}
var programsLength = $scope.Programs[0].Terms.length;
var programsLengthIndex = programsLength + 1;
var paginationLength = programsLengthIndex * 76.6;
$('.finace-pagination .pagination').css('width', paginationLength);
for (var i in $scope.Programs) {
LoanData = {
"FinanceAmount": $scope.Programs[i].FinanceAmount,
"FinanceTenure": $scope.FinanceTenure,
"CommissionCap": $scope.Programs[i].CommissionCap
};
// var matchingTerm=_.findWhere($scope.Programs[i].Terms,{Term:$scope.FinanceTenure});
// if(matchingTerm){
// LoanData.UseCustomRate=matchingTerm.Rate;
// } else {
// LoanData.UseCustomRate=$scope.ApplicationStatusData[i].ROI;
// }
// LoanData=appInfo.getCalcData(LoanData);
$scope.Programs[i].appliedEMI = $scope.Programs[i].AmountPayable;
$scope.Programs[i].appliedRate = $scope.Programs[i].AppliedRate;
if (i == 0) {
// LoanData.FinanceTenure=$scope.Programs[i].MinTenure;
LoanData.UseCustomRate = $scope.Programs[i].MinRate;
LoanData = appInfo.getCalcData(LoanData);
$scope.Programs[i].minEMI = LoanData.AmountPayable;
// console.log($scope.Programs[i].MinTenure,$scope.Programs[i].MinRate,LoanData.AmountPayable);
// LoanData.FinanceTenure=$scope.Programs[i].MaxTenure;
LoanData.UseCustomRate = $scope.Programs[i].MaxRate;
LoanData = appInfo.getCalcData(LoanData);
$scope.Programs[i].maxEMI = LoanData.AmountPayable;
}
}
if ($rootScope.CompanyPreferences.DefaultAppWorkFlow == 'LeadApplication') {
$scope.LeadProgramTypeIDs = {};
$scope.Programs.map(function(program) {
if($scope.LeadAppTerm){
program.Term = $scope.getMaxTerm(program.Terms, $scope.LeadAppTerm);
}else{
program.Term = $scope.getMaxTerm(program.Terms, program.MaxTenure);
}
if(!$scope.LeadProgramTypeIDs.hasOwnProperty(program.ProgramTypeID)) {
$scope.LeadProgramTypeIDs[program.ProgramTypeID] = {
'Programs': [program],
'ProgramTypeName': program.ProgramTypeName,
'ProgramTypeID': program.ProgramTypeID,
'ProgramDescription': program.ProgramDescription
};
} else {
$scope.LeadProgramTypeIDs[program.ProgramTypeID].Programs.push(program);
}
});
}
var pagingData = [];
$scope.shareAppListFilter.currentPage = pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPrograms = response.Data.Paginator.total_programs;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
setTimeout(function(){
$("#OfferTerms").trigger("chosen:updated");
},1000);
}
else {
if ($scope.affilateMode)
$state.go('application-denial');
else {
$scope.affilateMode = true;
return $scope.getMatchingPrograms(callback);
}
}
break;
case 646:
$scope.noMatchFound = response.Message;
$scope.getDefaultPrograms();
break;
case 588:
flag = true;
$scope.showFlashMessage('info', response.Message);
$timeout(function () {
$scope.getMatchingPrograms(function () {
/* Nothing to do */
});
}, 30000);
break;
case 589:
$state.go('application-denial');
$scope.Page.untrackLoading('save-partial-app');
break;
default:
$scope.showFlashMessage('error', response.Message);
if (_.isFunction(callback))
callback();
}
});
}
$scope.getDefaultPrograms = function (callback) {
var reqData = {
"GetDefaultPrograms": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.shareAppListFilter.currentPage,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"ApplicationNumber": ApplicationData.ApplicationNumber
}
};
$rootScope.Page.trackLoading('save-partial-app');
appInfo.getServerData(reqData).then(function (response) {
$scope.Programs = [];
$rootScope.Page.untrackLoading('save-partial-app');
$scope.ApplicationCreditScore = null;
if (response.Data.Programs) {
$scope.ApplicationCreditScore = response.Data.ApplicationCreditScore;
var LoanData = {};
$scope.Programs = response.Data.Programs;
$scope.emi = response.Data.EMI;
if ($scope.FinanceTenure > $scope.emi.maxTenure) {
$scope.FinanceTenure = $scope.emi.maxTenure;
}
for (var i = 1; (i * 12) <= $scope.emi.maxTenure; i++) {
$scope.availableTerms.push(i);
if ((i * 12) == $scope.emi.appliedTenure)
$scope.selected = i - 1;
}
var programsLength = $scope.Programs[0].Terms.length;
var programsLengthIndex = programsLength + 1;
var paginationLength = programsLengthIndex * 76.6;
$('.finace-pagination .pagination').css('width', paginationLength);
for (var i in $scope.Programs) {
LoanData = {
"FinanceAmount": $scope.Programs[i].FinanceAmount,
"FinanceTenure": $scope.FinanceTenure,
"CommissionCap": $scope.Programs[i].CommissionCap
};
// var matchingTerm=_.findWhere($scope.Programs[i].Terms,{Term:$scope.FinanceTenure});
// if(matchingTerm){
// LoanData.UseCustomRate=matchingTerm.Rate;
// } else {
// LoanData.UseCustomRate=$scope.ApplicationStatusData[i].ROI;
// }
// LoanData=appInfo.getCalcData(LoanData);
$scope.Programs[i].appliedEMI = $scope.Programs[i].AmountPayable;
$scope.Programs[i].appliedRate = $scope.Programs[i].AppliedRate;
if (i == 0) {
// LoanData.FinanceTenure=$scope.Programs[i].MinTenure;
LoanData.UseCustomRate = $scope.Programs[i].MinRate;
LoanData = appInfo.getCalcData(LoanData);
$scope.Programs[i].minEMI = LoanData.AmountPayable;
// console.log($scope.Programs[i].MinTenure,$scope.Programs[i].MinRate,LoanData.AmountPayable);
// LoanData.FinanceTenure=$scope.Programs[i].MaxTenure;
LoanData.UseCustomRate = $scope.Programs[i].MaxRate;
LoanData = appInfo.getCalcData(LoanData);
$scope.Programs[i].maxEMI = LoanData.AmountPayable;
}
}
if ($rootScope.CompanyPreferences.DefaultAppWorkFlow == 'LeadApplication') {
$scope.LeadProgramTypeIDs = {};
$scope.Programs.map(function(program) {
if($scope.LeadAppTerm){
program.Term = $scope.getMaxTerm(program.Terms, $scope.LeadAppTerm);
}else{
program.Term = $scope.getMaxTerm(program.Terms, program.MaxTenure);
}
if(!$scope.LeadProgramTypeIDs.hasOwnProperty(program.ProgramTypeID)) {
$scope.LeadProgramTypeIDs[program.ProgramTypeID] = {
'Programs': [program],
'ProgramTypeName': program.ProgramTypeName,
'ProgramTypeID': program.ProgramTypeID,
'ProgramDescription': program.ProgramDescription
};
} else {
$scope.LeadProgramTypeIDs[program.ProgramTypeID].Programs.push(program);
}
});
}
var pagingData = [];
$scope.shareAppListFilter.currentPage = pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPrograms = response.Data.Paginator.total_programs;
pagingData.numPerPage = 10;
$scope.showingtext = appInfo.getPaginationData(pagingData);
}
else {
if ($scope.affilateMode)
$state.go('application-denial');
else {
$scope.affilateMode = true;
return $scope.getMatchingPrograms(callback);
}
}
});
}
// var ApplicationData={ApplicationNumber:'05cf-deeb-d3b6'};
var ApplicationData = Storage.getItem('ApplicationData');
// Storage.setItem('ApplicationData',ApplicationData);
if (ApplicationData) {
$scope.PartialApplications = Storage.getItem('PartialApplications');
if (ApplicationData.LoanData) {
$scope.CreditScore = ApplicationData.LoanData.CreditScore;
// $scope.FinanceTenure = ApplicationData.LoanData.FinanceTenure;
// $scope.selected=($scope.FinanceTenure/12)-1;
setTimeout(function () {
if ($(".finace-pagination-scroll li.active").length)
$(".finace-pagination-scroll").scrollLeft($(".finace-pagination-scroll li.active").position().left);
}, 1000);
}
$scope.getMatchingPrograms(function () {
// Nothing to do
})
}
else {
$state.go('home');
}
$scope.isCollapsed = function (index) {
var collapse_class = 'collapse_' + index;
if ($scope[collapse_class] === undefined) {
//Valid in my application for first usage
$scope[collapse_class] = true;
/*console.log("test1",$scope[collapse_class]);*/
} else {
$scope[collapse_class] = !$scope[collapse_class];
/*console.log("test2",$scope[collapse_class]);*/
}
if ($rootScope.CompanyPreferences.DefaultAppWorkFlow == 'LeadApplication') {
$("#collapse" + index).toggle();
}else{
$("#collapse" + this.$index).toggle();
}
}
$scope.show = false;
$scope.ProgramData = [];
$scope.AffilateSites = [];
$scope.removeIn = function () {
$timeout(function () {
$(this).removeClass('in');
}, 1);
}
$scope.checkAllCheckbox = function (Program) {
if (Program?$scope.offer.squaredAll[Program]:$scope.offer.squaredAll) {
for (var i in $scope.Programs) {
if ($scope.ProgramData.length != 0) {
if ($scope.ProgramData.indexOf($scope.Programs[i].ProgramID) == -1) {
$scope.ProgramData.push($scope.Programs[i].ProgramID);
break;
}
}
else {
$scope.ProgramData.push($scope.Programs[i].ProgramID);
}
}
}
else {
$scope.ProgramData = [];
}
}
$scope.checkStatus = function (CurrentProgram) {
var checkCount = 0;
if (CurrentProgram) {
if ($scope.ProgramData.length != 0) {
for (var i in $scope.ProgramData) {
if ($scope.ProgramData[i] == CurrentProgram.ProgramID) {
return;
}
}
}
$scope.ProgramData.push(CurrentProgram.ProgramID);
if ($scope.affilateMode) {
$scope.AffilateSites.push(CurrentProgram.Website);
}
}
else {
var Currentindex = $scope.ProgramData.indexOf(CurrentProgram.ProgramID);
$scope.ProgramData.splice(Currentindex, 1);
if ($scope.affilateMode) {
$scope.AffilateSites.splice(Currentindex, 1);
}
}
};
$scope.IsChecked = TRUE;
$scope.isAgreed = function () {
if ($scope.IsChecked)
$scope.IsChecked = FALSE;
else
$scope.IsChecked = TRUE;
}
$scope.ShareApplication = function () {
if ($scope.ProgramData.length) {
var reqData = {
"ShareApplication": {
"ApplicationNumber": ApplicationData.ApplicationNumber,
"ProgramID": $scope.ProgramData,
"FinanceTenure": $scope.FinanceTenure,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"LoginSessionKey": $scope.SignIn.LoginSessionKey
}
};
if ($scope.emi.downPayment) {
reqData.ShareApplication.DownPayment = $scope.emi.downPayment;
}
var win = null;
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
var CompletedApplication = { ApplicationNumber: response.Data.ApplicationNumber, Email: $scope.Login.LoginKeyword, 'RequiredDocuments': response.Data.RequiredDocuments, 'PrimaryPhoneNumber': $rootScope.CompanyPreferences.PrimaryPhoneNumber };
Storage.setItem('CompletedApplication', CompletedApplication);
delete ApplicationData.FetchPreOfferFields;
Storage.setItem('ApplicationData', ApplicationData);
if ($scope.affilateMode && $scope.Programs[0].isAffilateProgram) {
$scope.ngConfirm("Please confirm, your further application process will open in a new window on our affiliate's site, while your current session here continues to remain active.", function () {
for (var i in $scope.AffilateSites) {
$("#affilatePage").attr('href', $scope.AffilateSites[i])[0].click();
}
$state.go("additional-information");
}, function () {
$state.go("additional-information");
});
} else {
$state.go("additional-information");
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
} else {
$scope.showFlashMessage("error", "Please select at least one program to proceed.");
}
}
$scope.activeCurrentTab = function (index) {
$scope.selected = index;
$scope.LeadAppTerm = index;
$scope.FinanceTenure = $rootScope.CompanyPreferences.DefaultAppWorkFlow == 'LeadApplication'?index:$scope.availableTerms[index] * 12;
$scope.getMatchingPrograms($scope.FinanceTenure);
}
$scope.getMaxTerm = function(terms, maxTerm) {
return terms.filter(function(term) { return term.Term === maxTerm })[0];
}
}])
// ecommerce Controller
.controller('ecommerceCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage, $stateParams, $state) {
$scope.productList = [
{
productImage: '../assets/img/back-win.png',
productName: 'Asus Laptop',
productDuration: '12',
productCost: '$150',
productQty: 1,
productDelete: ''
},
{
productImage: '../assets/img/back-win.png',
productName: 'Dell Laptop',
productDuration: '12',
productCost: '$150',
productQty: 1,
productDelete: ''
},
{
productImage: '../assets/img/back-win.png',
productName: 'HP Laptop',
productDuration: '12',
productCost: '$150',
productQty: 1,
productDelete: ''
},
{
productImage: '../assets/img/back-win.png',
productName: 'Lenova Laptop',
productDuration: '12',
productCost: '$150',
productQty: 1,
productDelete: ''
}
];
$scope.sellinglaptopList = [
{
sellinglaptopImage: '../assets/img/product1.png',
sellinglaptopPrice: '50',
sellinglaptopName: 'hp'
},
{
sellinglaptopImage: '../assets/img/product1.png',
sellinglaptopPrice: '40',
sellinglaptopName: 'dell'
},
{
sellinglaptopImage: '../assets/img/product1.png',
sellinglaptopPrice: '60',
sellinglaptopName: 'lenova'
},
{
sellinglaptopImage: '../assets/img/product1.png',
sellinglaptopPrice: '50',
sellinglaptopName: 'sony'
},
{
sellinglaptopImage: '../assets/img/product1.png',
sellinglaptopPrice: '40',
sellinglaptopName: 'samsung'
},
{
sellinglaptopImage: '../assets/img/product1.png',
sellinglaptopPrice: '20',
sellinglaptopName: 'hp'
},
{
sellinglaptopImage: '../assets/img/product1.png',
sellinglaptopPrice: '90',
sellinglaptopName: 'dell'
},
{
sellinglaptopImage: '../assets/img/product1.png',
sellinglaptopPrice: '70',
sellinglaptopName: 'lenova'
}
];
$scope.medicalequipmentList = [
{
medicalequipmentImage: '../assets/img/product1.png',
medicalequipmentPrice: '50',
medicalequipmentName: 'hp'
},
{
medicalequipmentImage: '../assets/img/product1.png',
medicalequipmentPrice: '40',
medicalequipmentName: 'dell'
},
{
medicalequipmentImage: '../assets/img/product1.png',
medicalequipmentPrice: '60',
medicalequipmentName: 'lenova'
},
{
medicalequipmentImage: '../assets/img/product1.png',
medicalequipmentPrice: '50',
medicalequipmentName: 'sony'
},
{
medicalequipmentImage: '../assets/img/product1.png',
medicalequipmentPrice: '40',
medicalequipmentName: 'samsung'
},
{
medicalequipmentImage: '../assets/img/product1.png',
medicalequipmentPrice: '20',
medicalequipmentName: 'hp'
},
{
medicalequipmentImage: '../assets/img/product1.png',
medicalequipmentPrice: '90',
medicalequipmentName: 'dell'
},
{
medicalequipmentImage: '../assets/img/product1.png',
medicalequipmentPrice: '70',
medicalequipmentName: 'lenova'
}
];
$scope.accessoriesList = [
{
accessoriesImage: '../assets/img/product1.png',
accessoriesPrice: '50',
accessoriesName: 'hp'
},
{
accessoriesImage: '../assets/img/product1.png',
accessoriesPrice: '40',
accessoriesName: 'dell'
},
{
accessoriesImage: '../assets/img/product1.png',
accessoriesPrice: '60',
accessoriesName: 'lenova'
},
{
accessoriesImage: '../assets/img/product1.png',
accessoriesPrice: '50',
accessoriesName: 'sony'
},
{
accessoriesImage: '../assets/img/product1.png',
accessoriesPrice: '40',
accessoriesName: 'samsung'
},
{
accessoriesImage: '../assets/img/product1.png',
accessoriesPrice: '20',
accessoriesName: 'hp'
},
{
accessoriesImage: '../assets/img/product1.png',
accessoriesPrice: '90',
accessoriesName: 'dell'
},
{
accessoriesImage: '../assets/img/product1.png',
accessoriesPrice: '70',
accessoriesName: 'lenova'
}
];
$scope.productDetails = {
"productimages": [
{
productimageUrl: '../assets/img/product1.png',
productTitle: 'hp'
},
{
productimageUrl: '../assets/img/back-win3.png',
productTitle: 'dell'
},
{
productimageUrl: '../assets/img/back-win.png',
productTitle: 'lenova'
},
{
productimageUrl: '../assets/img/back-win.png',
productTitle: 'samsung'
},
{
productimageUrl: '../assets/img/back-win.png',
productTitle: 'hp'
},
{
productimageUrl: '../assets/img/back-win.png',
productTitle: 'dell'
},
{
productimageUrl: '../assets/img/back-win.png',
productTitle: 'lenova'
},
{
productimageUrl: '../assets/img/back-win.png',
productTitle: 'samsung'
}
]
}
$scope.uploadFileDetail = [
{
uploadHeading: 'Business Bank Statements'
},
{
uploadHeading: 'Business Bank Statements2'
},
{
uploadHeading: 'Business Bank Statements3'
}
];
$scope.increment = function ($index) {
if ($scope.productList[$index].productQty == '' || $scope.productList[$index].productQty == undefined) {
$scope.productList[$index].productQty = 0;
}
$scope.productList[$index].productQty++;
};
$scope.decrement = function ($index) {
if ($scope.productList[$index].productQty > 1) {
$scope.productList[$index].productQty--;
}
};
$scope.deleteProduct = function ($index) {
// $scope.productList[$index].productImage
$scope.ngConfirm("Are you sure Delete " + $scope.productList[$index].productName + " ?",
function () {
$scope.productList.splice($index, 1);
}/*,
function(){
alert('cancel');
}*/
);
}
$scope.qty = 1;
$scope.incrementDetail = function () {
if ($scope.qty == '' || $scope.qty == undefined) {
$scope.qty = 0;
}
$scope.qty++;
}
$scope.decrementDetail = function () {
if ($scope.qty > 1) {
$scope.qty--;
}
}
$scope.disabledButton = "enable";
$scope.disabledIcon = "ic-disabled";
$scope.setFile = function (element) {
$scope.$apply(function ($scope) {
$scope.theFile = element.files[0];
if ($scope.disabledButton == "enable")
$scope.disabledButton = "disabled";
if ($scope.disabledIcon == "ic-disabled")
$scope.disabledIcon = "enable";
});
};
$scope.resetFile = function (element) {
if ($('.upload-value').length > 1) {
$scope.theFile = "";
$scope.disabledButton = "enable";
}
}
}])
// application Denial Controller
.controller('appDenialCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage, $stateParams, $state) {
var ApplicationData = Storage.getItem('ApplicationData');
if (ApplicationData) {
$scope.$parent.LoanData = ApplicationData.LoanData;
$scope.ApplicationNumber = ApplicationData.ApplicationNumber;
$scope.updateFinanceAmountValue = TRUE;
}
}])
//lender profile controller
.controller('LenderProfileController', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage, $stateParams, $state) {
$scope.activeTab = 1;
$scope.isEdit = 1;
$scope.SyndicateData = {
SyndicateUser: null,
};
$scope.CreditData = { fico: {}, paydex: {}, paynet: {} };
$scope.ProfileCompleteStatus = {};
$scope.getAllIndustries = function (callback) {
var reqDataIndustry = {
"GetIndustryTypesList": {
"allIndustries": true
}
};
$rootScope.Page.trackLoading('industries-list');
appInfo.getServerData(reqDataIndustry).then(function (response) {
if (response.ResponseCode == 200) {
$scope.industries = response.Data.Industries;
/*$scope.Config.industryData = [];
for (var i = 0; i < $scope.industries.length; i++) {
$scope.configurationIndustryId = $scope.industries[i].IndustryTypeID;
for (var j = 0; j < $rootScope.CompanyPreferences.IndustryTypes.length; j++) {
$scope.companyPrefrenceId = $rootScope.CompanyPreferences.IndustryTypes[j];
if ($scope.configurationIndustryId == $scope.companyPrefrenceId){
$scope.Config.industryData.push($scope.industries[i]);
}
}
}*/
if (typeof callback != 'undefined')
callback(response);
} else
$rootScope.showFlashMessage('error', response.Message);
$rootScope.Page.untrackLoading('industries-list');
});
}
var loadCompanyData = function () {
$scope.CompanyData = {};
angular.copy($scope.CompanyPreferences, $scope.CompanyData);
$scope.CompanyData.PostalCode = $scope.CompanyPreferences.Postal;
if ($scope.CompanyData.PostalCode && $scope.CompanyData.PostalCode.toString().length < 5) {
$scope.CompanyData.PostalCode = $scope.CompanyData.PostalCode.toString().padStart(5, "0")
}
appInfo.getStates(function () {
$scope.CompanyData.StateID = _.findWhere($rootScope.stateData, { StateID: $scope.CompanyData.StateID });
// appInfo.getequipmenttype(function(){
// $scope.CompanyData.EquipmentType = null;
// $scope.CompanyEquipmentTypes = [];
// });
$scope.getAllIndustries(function () {
$scope.CompanyData.IndustryType = null;
$scope.CompanyIndustryType = [];
})
appInfo.getsyndicateusers(function () {
$scope.SyndicateData.SyndicateUser = null;
});
appInfo.getAnnualVolumeSyndicates(function () {
// $scope.SyndicateData.VolumeSyndicate = null;
$scope.SyndicateData.SyndicatedOriginationVolumeID = null;
$scope.SyndicateData.SyndicatedAnnualVolumeID = null;
});
appInfo.getCompanyTypes(function () {
// $scope.CompanyDetails.CompanyTypes = null;
if ($scope.CompanyData.CompanyTypeID) {
$scope.CompanyData.CompanyTypes = _.findWhere($rootScope.CompanyTypesList, { CompanyTypeID: $scope.CompanyData.CompanyTypeID });
} else {
$scope.CompanyData.CompanyTypes = 0;
}
});
});
}
if ($rootScope.CompanyPreferences)
loadCompanyData();
else
$rootScope.$on('company-loaded', loadCompanyData);
$scope.Page.Title = 'Lender Profile - ' + $rootScope.CompanyPreferences.CompanyName;
$scope.addIndustryType = function () {
if (this.CompanyData.IndustryType) {
for (var i in $scope.CompanyIndustryType) {
if (this.CompanyData.IndustryType.IndustryTypeID == $scope.CompanyIndustryType[i].IndustryType.IndustryTypeID) {
return;
}
}
$scope.CompanyIndustryType.push({
IndustryType: _.findWhere($scope.industries, { IndustryTypeID: this.CompanyData.IndustryType.IndustryTypeID }),
EquipmentTypeValue: 0
});
}
}
$scope.addAllIndustryType = function () {
// $scope.equipments = $rootScope.equipmenttypes;
for (var i in $scope.industries) {
for (var j in $scope.CompanyIndustryType) {
if ($scope.CompanyIndustryType[j].IndustryType.IndustryTypeID == $scope.industries[i].IndustryTypeID) {
$scope.industries.splice(i, 1);
}
}
}
for (var i in $scope.industries) {
$scope.CompanyIndustryType.push({
IndustryType: $scope.industries[i],
EquipmentTypeValue: 1
});
}
}
$scope.clickedval = function (CompanyIndustryType, EquipmentTypeRate) {
for (var i in $scope.CompanyIndustryType) {
if ($scope.CompanyIndustryType[i].IndustryType.IndustryTypeID == CompanyIndustryType.IndustryType.IndustryTypeID) {
$scope.CompanyIndustryType[i].EquipmentTypeValue = EquipmentTypeRate;
}
}
}
$scope.saveProfileData = function () {
$formName = 'lenderProfile';
// if($scope.CompanyData.Category=='Bank' && angular.isUndefined($scope.CompanyData.CompanyTypes)){
// $scope.showFlashMessage('error', 'Please Select Company Type');
// return false;
// }
if (checkstatus($formName, $scope)) {
var saveData = {
"CompanyName": $scope.CompanyData.CompanyName,
"DBA": $scope.CompanyData.DBA,
"Address1": $scope.CompanyData.Address1,
"City": $scope.CompanyData.City,
"StateID": $scope.CompanyData.StateID.StateID,
"Postal": $scope.CompanyData.PostalCode,
"PrimaryPhoneNumber": $scope.CompanyData.PrimaryPhoneNumber,
"Fax": $scope.CompanyData.Fax,
"Website": $scope.CompanyData.Website,
"Description": $scope.CompanyData.HeadingDescription,
"Alias": $scope.CompanyData.Alias,
"CompanyType": $scope.CompanyData.CompanyTypes ? $scope.CompanyData.CompanyTypes.CompanyTypeID : null,
"ShowBookedDeal": $scope.CompanyData.ShowBookedDeal,
"ShowNewApplicationDeal": $scope.CompanyData.ShowNewApplicationDeal
}
var reqData = {
"UpdateLenderProfile": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"GeneralInfo": saveData,
"ModuleName": "GeneralInfo"
}
};
if ($scope.CompanyData.ShowBookedDeal == 0 && $scope.CompanyData.ShowNewApplicationDeal == 0) {
$rootScope.showFlashMessage('error', 'Please Select Atlease One Deal Type.'); return false;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
//Storage.removeItem('CompanyPreferences');
if ($scope.ProfileCompleteStatus.IsProfileComplete == 0) {
$scope.ProfileCompleteStatus.IsProfileComplete = 1;
$scope.ProfileCompleteStatus.ProfilePercent += 15;
}
$scope.showTab(2);
var reqData = {
"GetCompanyPreferences": {
"Alias": SUBDOMAIN
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.CompanyPreferences = response.Data;
Storage.setItem('CompanyPreferences', $rootScope.CompanyPreferences);
}
});
$scope.showFlashMessage('success', response.Message); return false;
}
else {
$scope.showFlashMessage('error', response.Message); return false;
}
});
}
}
$scope.showTab = function (value) {
$scope.activeTab = value;
$scope.isEdit = 0;
if ($scope.activeTab == 1) {
$location.hash('scrollTop');
} else if ($scope.activeTab == 2) {
$scope.getSyndicateData();
} else if ($scope.activeTab == 3) {
$scope.getEquipmentData();
} else if ($scope.activeTab == 4) {
$scope.getCreditData();
} else if ($scope.activeTab == 5) {
//for document upload system
}
}
$scope.getProfileCompleteness = function () {
var reqData = {
"GetProfileCompleteness": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
//Storage.removeItem('CompanyPreferences');
$scope.ProfileCompleteStatus = response.Data;
}
});
}
$scope.getProfileCompleteness();
$scope.checked = true;
$scope.getSyndicateData = function () {
var reqData = {
"GetSyndicateData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length > 0 || response.Data) {
$scope.SyndicateData = response.Data;
$scope.SyndicateData.FundingProgramsBoth = response.Data.FundingProgramsBoth;
$scope.SyndicateData.FundingProgramsSellPaper = response.Data.FundingProgramsSellPaper;
$scope.SyndicateData.FundingProgramsSellPaperOurDocsOnly = response.Data.FundingProgramsSellPaperOurDocsOnly;
$scope.SyndicateData.SyndicateUser = _.findWhere($rootScope.syndicateUsers, { PrimaryContactID: $scope.SyndicateData.PrimarySyndicateID });
for (var j in $rootScope.VolumeSyndicates) {
if ($rootScope.VolumeSyndicates[j].SyndicatedAnnualVolumeID == $scope.SyndicateData.SyndicatedAnnualVolumeID)
$scope.SyndicateData.SyndicatedAnnualVolumeID = $rootScope.VolumeSyndicates[j];
if ($rootScope.VolumeSyndicates[j].SyndicatedAnnualVolumeID == $scope.SyndicateData.SyndicatedOriginationVolumeID)
$scope.SyndicateData.SyndicatedOriginationVolumeID = $rootScope.VolumeSyndicates[j];
}
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.saveSyndicateData = function () {
$formName = 'syndicateDesk';
if (checkstatus($formName, $scope)) {
$scope.SyndicateData.PrimarySyndicateID = $scope.SyndicateData ? $scope.SyndicateData.PrimaryContactID : null;
var reqData = {
"UpdateLenderProfile": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"SyndicateData": $scope.SyndicateData,
"ModuleName": "SyndicateData"
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if ($scope.ProfileCompleteStatus.IsSyndicateDeskComplete == 0) {
$scope.ProfileCompleteStatus.IsSyndicateDeskComplete = 1;
$scope.ProfileCompleteStatus.ProfilePercent += 25;
}
$scope.SyndicateData.CompanySyndicateDeskID = response.Data.CompanySyndicateDeskID;
$scope.showTab(3)
$scope.showFlashMessage('success', response.Message);
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
return false;
}
$scope.changeLeaseDocument = function (data) {
switch (data) {
case "FundingProgramsSellPaperOurDocsOnly":
$scope.SyndicateData.FundingProgramsSellPaperOurDocsOnly = 1;
$scope.SyndicateData.FundingProgramsSellPaper = $scope.SyndicateData.FundingProgramsBoth = 0;
break;
case "FundingProgramsSellPaper":
$scope.SyndicateData.FundingProgramsSellPaper = 1;
$scope.SyndicateData.FundingProgramsSellPaperOurDocsOnly = $scope.SyndicateData.FundingProgramsBoth = 0;
break;
case "FundingProgramsBoth":
$scope.SyndicateData.FundingProgramsBoth = 1;
$scope.SyndicateData.FundingProgramsSellPaperOurDocsOnly = $scope.SyndicateData.FundingProgramsSellPaper = 0;
break;
}
}
$scope.getEquipmentData = function () {
var reqData = {
"GetEquipmentData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
var responseData = response.Data;
$scope.CompanyIndustryType = [];
for (var i in responseData) {
$scope.CompanyIndustryType.push({
IndustryType: _.findWhere($scope.industries, { IndustryTypeID: responseData[i].EquipmentTypeID }),
EquipmentTypeValue: responseData[i].EquipmentTypeValue
});
}
//console.log($scope.CompanyIndustryType)
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.saveIndustryType = function () {
if ($scope.CompanyIndustryType.length) {
var reqData = {
"UpdateLenderProfile": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"IndustryData": $scope.CompanyIndustryType,
"ModuleName": "IndustryData"
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showTab(4);
if ($scope.ProfileCompleteStatus.IsEquipmentComplete == 0) {
$scope.ProfileCompleteStatus.IsEquipmentComplete = 1;
$scope.ProfileCompleteStatus.ProfilePercent += 25;
}
$scope.showFlashMessage('success', response.Message);
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
} else {
$scope.showFlashMessage('error', "Please add equipment type from dropdown.");
}
return false;
}
$scope.getCreditData = function () {
var reqData = {
"GetCreditData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
var res = response.Data[0];
$scope.CreditData = res;
$scope.CreditData.fico = {
minScore: 350,
maxScore: 850
};
$scope.CreditData.paydex = {
minScore: 0,
maxScore: 100
};
$scope.CreditData.paynet = {
minScore: 450,
maxScore: 850
};
$scope.CreditData.fico.minScore = $scope.CreditData.FICOMinScore;
$scope.CreditData.fico.maxScore = $scope.CreditData.FICOMaxScore;
$scope.CreditData.paydex.minScore = $scope.CreditData.PaydexMinScore;
$scope.CreditData.paydex.maxScore = $scope.CreditData.PaydexMaxScore;
$scope.CreditData.paynet.minScore = $scope.CreditData.PaynetMinScore;
$scope.CreditData.paynet.maxScore = $scope.CreditData.PaynetMaxScore;
}
else {
$scope.CreditData.fico = {
minScore: 350,
maxScore: 850
};
$scope.CreditData.paydex = {
minScore: 0,
maxScore: 100
};
$scope.CreditData.paynet = {
minScore: 450,
maxScore: 850
};
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.saveCreditData = function () {
$formName = 'CreditDataForm';
if (checkstatus($formName, $scope)) {
// $scope.CreditData.PrimarySyndicateID = $scope.SyndicateData.PrimaryContactID;
var reqData = {
"UpdateLenderProfile": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"CreditData": $scope.CreditData,
"ModuleName": "CreditData"
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.CreditData.CreditTypeID = response.Data.CreditTypeID;
// $scope.SyndicateData.CreditTypeID = response.Data.CreditTypeID;
$scope.showTab(1);
if ($scope.ProfileCompleteStatus.IsCreditTypeComplete == 0) {
$scope.ProfileCompleteStatus.IsCreditTypeComplete = 1;
$scope.ProfileCompleteStatus.ProfilePercent += 25;
}
$scope.showFlashMessage('success', response.Message);
$scope.showTab(5);
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
return false;
}
$scope.targetColor1 = $scope.CompanyPreferences.BetaSiteThemeSettings.color1;
$scope.targetColor2 = $scope.CompanyPreferences.BetaSiteThemeSettings.color2;
$scope.changeThemeNew = function (targetColor1, targetColor2, tempUpdate) {
var color1 = $scope.targetColor1;
var color2 = $scope.targetColor2;
if (!tempUpdate) {
var reqData = {
"SetCompanyPreferences": {
"UIsettings": { "color1": color1, "color2": color2, "color3": color1, "color4": color1, "color5": color1 },
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.showFlashMessage('success', response.Message);
$rootScope.CompanyPreferences.BetaSiteThemeSettings = { "color1": color1, "color2": color2, "color3": color1, "color4": color1, "color5": color1 };
Storage.setItem('CompanyPreferences', $rootScope.CompanyPreferences);
$rootScope.updateUI();
} else {
$rootScope.showFlashMessage('error', response.Message);
}
});
}
else {
$rootScope.updateUI();
}
};
}])
//deal controller
.controller('DealCtrl', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', 'ulGeo', '$filter', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage, $stateParams, $state, $q, ulGeo, $filter) {
$scope.previousStateData = Storage.getItem('previousStateData');
$scope.moduleName = 'Deal';
$scope.FormData = {};
$scope.RatingData = [{ 'Name': 'Excellent', 'ID': 1 }, { 'Name': 'Very Good', 'ID': 2 }, { 'Name': 'Good', 'ID': 3 }, { 'Name': 'Fair', 'ID': 4 }, { 'Name': 'Poor', 'ID': 5 }];
$scope.FormData.Rating = false;
$scope.FormData.DealType = "Booked Deal";
$scope.firstDealFileLoad = true;
$scope.requestFileUnderProcess = false;
$scope.DealDetail = {};
$scope.DealID = '';
$scope.blockCreateGroup = $scope.blockCreateHeader = false;
$scope.$index = 0;
$scope.file_type = "";
$scope.activeTab = 1;
$scope.notes = { noteCurrentPage: 1, totalPage: null, totalRecord: null };
$scope.noteTab = 'Deal';
//$scope.FormData.DealID=24;
$scope.isEdit = 1;
$scope.Business = {};
$scope.Business.Month = null;
$scope.Business.Year = null;
$scope.selectedDeal = {
IsPrivateSharedOnly: 0,
MarketPlaceUsers: ''
};
$scope.OwnerData = [];
$scope.DealStepComplete = {};
$scope.deal = {
DealUID: $stateParams.DealUID,
secondaryActiveTab: 'All'
};
//Start:Deal list code
$scope.getColor = $rootScope.getColor; // IE Fix
$scope.totalApplications = 0;
$scope.sentMessage = '';
$scope.firstLoad = true;
$scope.requestUnderProcess = false;
$scope.DisabledSortBy = [];
var tabbedPage = { "sAll": 1, "s20": 1, "s22": 1 };
$scope.dealcurrentState = $state.current.name;
$scope.imageExtensionArray = ['jpg', 'jpeg', 'png'];
$scope.SortByOptions = [
{ key: 'FirstName', sortByValue: 'Name' },
{ key: 'BusinessName', sortByValue: 'Business Name' },
{ key: 'FinanceAmount', sortByValue: 'Finance Amount' },
{ key: 'FinanceTenure', sortByValue: 'Finance Tenure' },
{ key: 'CreditScoreID', sortByValue: 'User Credit Score' }
];
ulGeo().then(function (m) {
$scope.displayMap = true;
},
function (m) {
console.log(m);
});
$scope.dealPDFUrl = $location.$$protocol + '://' + $location.$$host + '/deals/details/1/' + $stateParams.DealUID + '.pdf';
$scope.getPdf = function () {
angular.element('#frmDownloadPDF').submit();
};
$scope.maxPossibleRate = function () {
if ($scope.FormData.InternalYield)
return (new Big($scope.FormData.InternalYield).minus(0.1)).toPrecision(3);
else
return 99.99;
}
$scope.saveDealState = function () {
var dealList = {
"Filter": $scope.syndicationDeskFilter,
"currentPage": $scope.currentPage,
"SortBy": $scope.dealSort
};
Storage.setItem('dealList', dealList);
}
$scope.resetFiltersForDeal = function () {
$scope.dealTabFlag = 'All';
$scope.syndicationDeskFilter = {
Name: null, StartDate: null, EndDate: null,
dealStatus: null, BorrowerID: null, ProposalLeadID: null, ProgramID: null, ProgramName: null
};
$scope.dealSort = null;
$scope.currentPage = 1;
$scope.refreshSyndicationDeskList();
}
$scope.refreshSyndicationDeskList = function () {
$scope.Page.trackLoading('syndicationDesk-list');
if (!$scope.requestUnderProcess) {
var reqData = {
"GetSyndicationDeskList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
}
};
if ($scope.syndicationDeskFilter) {
reqData.GetSyndicationDeskList.Filter = {
syndicationDeskFilter_StartDate: $scope.syndicationDeskFilter.StartDate,
syndicationDeskFilter_EndDate: $scope.syndicationDeskFilter.EndDate,
syndicationDeskFilter_Name: $scope.syndicationDeskFilter.Name,
Status: ($scope.syndicationDeskFilter.dealStatus) ? $scope.syndicationDeskFilter.dealStatus.StatusID : null,
ForNewDealPool: (['edit-select-deal', 'select-deal'].indexOf($state.current.name) !== -1) ? TRUE : FALSE
};
}
if ($scope.dealSort) {
reqData.GetSyndicationDeskList.SortBy = $scope.dealSort;
}
if (!$scope.firstLoad)
$scope.saveDealState(null);
$scope.Page.trackLoading('syndicationDesk-list');
$scope.deals = null;
$scope.totalDeals = 0;
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('syndicationDesk-list');
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.deals = response.Data.Deals;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalDeals = response.Data.Paginator.total_deals;
pagingData.numPerPage = 10;
$scope.showingDealtext = appInfo.getPaginationData(pagingData);
if (angular.isNumber($scope.syndicationDeskFilter.dealStatus ? $scope.syndicationDeskFilter.dealStatus.StatusID : null)) {
$scope.dealTabFlag = 'All';
}
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.initFilters = function () {
appInfo.getsyndicateusers(function () {
var dealList = Storage.getItem('dealList');
if (dealList) {
$scope.syndicationDeskFilter = {
Name: dealList.Filter.Name,
StartDate: dealList.Filter.StartDate,
EndDate: dealList.Filter.EndDate,
dealStatus: null
};
if (dealList.SortBy) {
$scope.dealSort = null;
for (var i in $scope.SortByOptions) {
if (angular.equals($scope.SortByOptions[i], dealList.SortBy)) {
$scope.dealSort = $scope.SortByOptions[i];
break;
}
}
}
if (dealList.Filter.dealStatus) {
$scope.syndicationDeskFilter.dealStatus = _.findWhere($scope.StatusList, { StatusID: parseInt(dealList.Filter.dealStatus.StatusID) });
}
$scope.currentPage = dealList.currentPage;
$scope.dealTabFlag = dealList.Filter.dealStatus ? dealList.Filter.dealStatus.StatusID : 'All';
if (_.isUndefined($scope.dealTabFlag)) {
$scope.dealTabFlag = 'All';
}
$scope.refreshSyndicationDeskList();
} else
$scope.resetFiltersForDeal();
$scope.firstLoad = false;
});
};
$scope.updateDealTab = function (dealTabFlag) {
$scope.dealTabFlag = dealTabFlag;
if (dealTabFlag != 'All') {
$scope.syndicationDeskFilter.dealStatus = { 'StatusID': dealTabFlag };
} else {
$scope.syndicationDeskFilter.dealStatus = "";
}
$scope.refreshSyndicationDeskList();
}
appInfo.getStatusList(function () {
$scope.StatusList = $rootScope.statusList;
switch ($state.current.name) {
case "syndication-desk":
case "select-deal":
case "edit-select-deal":
$scope.initFilters();
break;
}
}, TRUE);
$scope.$watch('syndicationDeskFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue)
$scope.refreshSyndicationDeskList();
}, 700));
$scope.$watch('syndicationDeskFilter.StartDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.syndicationDeskFilter.EndDate) {
var StartDate = new Date(newValue);
var EndDate = new Date($scope.syndicationDeskFilter.EndDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.syndicationDeskFilter.StartDate = null;
}
}
});
$scope.$watch('syndicationDeskFilter.EndDate', function (newValue, oldValue) {
if (newValue != oldValue && $scope.syndicationDeskFilter.StartDate) {
var EndDate = new Date(newValue);
var StartDate = new Date($scope.syndicationDeskFilter.StartDate);
if (StartDate > EndDate) {
$scope.showFlashMessage('error', 'Start Date cannot be greater then End Date');
$scope.syndicationDeskFilter.EndDate = null;
}
}
});
$scope.closePopup = function () {
ngDialog.close();
}
$scope.getStatus = function (StatusID) {
var Status = null;
if (StatusID != '') {
Status = _.findWhere($rootScope.statusList, { StatusID: StatusID });
if (Status) {
if (StatusID == 9) {
return "In Process";
}
return Status.StatusName;
}
}
return Status;
};
//End:Deal list code
$scope.FormData.DealTypes = [];
$scope.initAddDeal = function () {
appInfo.getsyndicateusers(function () {
$scope.FormData.SalesRepresentative = null;
//$rootScope.salesPersons;
appInfo.getIndustryTypes(function () {
//$rootScope.industryData
$scope.Business.IndustryTypes = null;
$scope.FormData.Industry = null;
});
appInfo.getProgramTypeList(function () {
//$rootScope.industryData
$scope.FormData.ProgramType = null;
});
appInfo.getLegalStructureName(function () {
//$rootScope.legalStructureData
$scope.Business.LegalStructure = null;
});
appInfo.getSignUpStaticData(function () {
// $scope.Business.Month = null;
// $scope.Business.Year = null;
});
appInfo.getStates(function () {
$scope.Business.StateID = null;
});
appInfo.getSalesPersons(function () {
$scope.FormData.SalesRepresentative = null;
});
/*appInfo.getAnnualVolumeSyndicates(function(){
$scope.CompanyData.VolumeSyndicate = null;
});*/
if ($scope.CompanyPreferences.ShowBookedDeal == 1) {
$scope.FormData.DealTypes.push('Booked Deal');
}
if ($scope.CompanyPreferences.ShowNewApplicationDeal == 1) {
$scope.FormData.DealTypes.push('New Application');
}
$scope.FormData.DealType = null;
if ($stateParams.DealUID) {
if ($state.params.link != "offers") {
$scope.getDeal(function () {
$scope.getFinancialsData();
});
}
// else{
// $scope.getDealSnapshot();
// }
}
});
$scope.Page.Title = 'Deal - ' + $rootScope.CompanyPreferences.CompanyName;
}
$scope.deleteHeader = function (index) {
$scope.ngConfirm('Are you sure you want to delete this header ?', function () {
for (var i in $scope.Business.Financials) {
for (j in $scope.Business.Financials[i].rows) {
$scope.Business.Financials[i].rows[j].splice(parseInt(index) + 1, 1);
}
}
$scope.Business.Financials.HeaderYears.splice(index, 1);
$scope.saveFinancials(true);
});
}
$scope.saveDealFilesState = function () {
var dealFileList = {
"currentPage": $scope.FilesFilter.currentPage
};
Storage.setItem('dealFiles-list', dealFileList);
}
$scope.togglePublishStatus = function (isPrivateSharedOnly, dealID) {
// $scope.selectedDeal = this.deal;
var reqData = {
"ToggleDealPublishPrivacy": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealID": this.deal.DealID ? this.deal.DealID : dealID,
"IsPrivateSharedOnly": (isPrivateSharedOnly === false) ? 1 : 0,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('syndicationDesk-list');
if (response.ResponseCode == 200) {
if ($state.current.name == "syndication-desk")
$scope.refreshSyndicationDeskList();
$scope.showFlashMessage('success', response.Message);
}
}, function () {
// $scope.selectedDeal.IsPrivateSharedOnly=!$scope.selectedDeal.IsPrivateSharedOnly
$scope.showFlashMessage('error', "Error updating Deal Privacy");
});
}
$scope.togglePublicSharing = function () {
$scope.selectedApplicationDocument = this.fileItem;
var reqData = {
"ToggleDealDocumentPublicSharing": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealDocumentId": $scope.selectedApplicationDocument.FolderID,
"isPublic": $scope.selectedApplicationDocument.isPublic,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('syndicationDesk-list');
if (response.ResponseCode != 200) {
$scope.selectedApplicationDocument.isPublic = !$scope.selectedApplicationDocument.isPublic;
$scope.showFlashMessage('error', response.Message);
}
}, function () {
$scope.selectedApplicationDocument.isPublic = !$scope.selectedApplicationDocument.isPublic;
$scope.showFlashMessage('error', "Error updating " + $scope.selectedApplicationDocument.ImageName);
});
}
$scope.showTab = function (value) {
if (value == 1) {
$location.hash('scrollTop');
$scope.activeTab = value;
$scope.isEdit = 0;
} else if (value == 2) {
if (!$scope.FormData.DealID) {
$scope.showFlashMessage('error', "Please add general information.");
return false;
} else
$scope.activeTab = value;
$scope.isEdit = 0;
} else if (value == 3) {
if (!$scope.FormData.BusinessID) {
$scope.showFlashMessage('error', "Please add business information.");
return false;
}
$scope.activeTab = value;
$scope.isEdit = 0;
} else if (value == 4) {
if (!$scope.FormData.DealID) {
$scope.showFlashMessage('error', "Please add the general information.");
} else {
$scope.activeTab = value;
$scope.isEdit = 0;
$timeout($scope.refreshFileList, 200);
}
}
else if (value == 5) {
if (!$scope.FormData.DealID) {
$scope.showFlashMessage('error', "Please add the general information.");
} else {
$scope.activeTab = value;
$scope.isEdit = 0;
}
}
}
$scope.saveDeal = function (isFundingManger) {
$formName = 'addDealForm';
delete $scope.FormData.AppToDeal;
if (checkstatus($formName, $scope)) {
var reqData = {
"SaveDeal": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"DealData": $scope.FormData,
"IsFundingManger": isFundingManger,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
if ($scope.FormData.DealProcessedBy == 1) {
$state.go('add-deal-files', { 'DealUID': response.Data.DealUID });
} else {
$scope.FormData.DealID = response.Data.DealID;
$scope.FormData.DealUID = response.Data.DealUID;
$scope.Page.documents = {
"zipName": $scope.FormData.DealName,
"ModuleEntityID": $scope.FormData.DealUID,
"ModuleName": "DealDocuments",
"selectedFiles": [],
"files": [],
"DocumentsData": [],
"selectedFileIds": [],
"FolderName": [],
"checkedFile": false,
"filter": { "currentPage": 1 },
"shareWithList": $scope.getAccesses,
"blockEdit": $scope.FormData.MarkAsSampleDeal,
"blockSelect": $scope.FormData.MarkAsSampleDeal,
"blockDelete": $scope.FormData.MarkAsSampleDeal
}
$scope.BusinessTab = 1;
//$state.go();
$scope.DealStepComplete.IsGeneralInfoComplete = 1;
$scope.showTab(2)
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.saveBusiness = function (preventTabSwitch) {
$formName = 'BusinessForm';
if (checkstatus($formName, $scope)) {
//$scope.FormData.DealProcessedBy = 1;
var reqData = {
"SaveBusiness": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Business": $scope.Business,
"DealID": $scope.FormData.DealID,
"DealUID": $scope.FormData.DealUID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.Business.BusinessID = response.Data.BusinessID;
if (!$scope.OwnerData.length) {
$scope.AddBusinessOwner();
}
$scope.DealStepComplete.IsBusinessInfoComplete = 1;
$scope.getDeal(function () {
$scope.showTab(3);
})
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
} else {
if (!$scope.Business.BusinessName && $scope.BusinessTab != '8') {
$scope.BusinessTab = 1;
}
}
}
//new function added for spreadsheet
$scope.addFinancialGroup = function () {
$scope.Business.Financials.push({ 'GroupName': $scope.Business.Financials.GroupData, 'BusinessID': $scope.Business.BusinessID, 'rows': [] });
$scope.Business.Financials.EditEnable = true;
$scope.blockCreateGroup = true;
$scope.assembleFinancialItem($scope.Business.Financials.length - 1);
$scope.saveFinancials(true);
$scope.closePopup();
}
$scope.saveFinancials = function (flagForGetFinancialDetails) {
var reqData = {
"SaveFinancials": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"Financials": $scope.Business.Financials,
"DealID": $scope.FormData.DealID,
"DealUID": $scope.FormData.DealUID,
"BusinessID": $scope.Business.BusinessID,
"HeaderYears": $scope.Business.Financials.HeaderYears
}
};
$scope.blockCreateGroup = true;
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
if (flagForGetFinancialDetails)
$scope.getFinancialsData();
else
$scope.blockCreateGroup = false;
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.addFinancialHeader = function (HeaderData) {
$scope.Business.Financials.HeaderYears.push(HeaderData);
$scope.blockCreateHeader = ($scope.Business.Financials.HeaderYears.length == 5) ? true : false;
for (var i in $scope.Business.Financials) {
for (var j in $scope.Business.Financials[i].rows) {
$scope.Business.Financials[i].rows[j].push({ 'key': 'N/A' });
continue;
}
}
$scope.saveFinancials(true);
$scope.closePopup();
}
$scope.getFinancialsData = function () {
if ($scope.FormData && $scope.FormData.AppOnly) {
return false;
}
var reqData = {
"getFinancialsData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"BusinessID": $scope.FormData.BusinessID ? $scope.FormData.BusinessID : $scope.deal.BusinessData.BusinessID,
"DealID": $scope.FormData.DealID,
"DealUID": $scope.FormData.DealUID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
if (response.Data.Financials.Groups && response.Data.Financials.Groups.length > 0) {
$scope.Business.Financials = response.Data.Financials.Groups;
$scope.Business.Financials.EditEnable = true;
$scope.blockCreateGroup = false;
} else {
$scope.Business.Financials = [];
$scope.Business.Financials.EditEnable = true;
}
if (response.Data.Financials.HeaderData && response.Data.Financials.HeaderData.length > 0)
$scope.Business.Financials.HeaderYears = response.Data.Financials.HeaderData;
else
setDefaultHeaders();
setTimeout(function () { $("#financials00").focus(); }, 1500);
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
$scope.closePopup();
}
$scope.closePopup = function () {
ngDialog.close();
}
$scope.createRowGroup = function (dealID) {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-createRowGroup.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
$scope.createHeader = function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-createHeader.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
var setDefaultHeaders = function () {
var date = new Date();
var year = date.getFullYear();
var j = 0;
$scope.Business.Financials.HeaderYears = [];
for (i = year; i > year - 4; i--) {
$scope.Business.Financials.HeaderYears.push('12/31/' + i);
if (j == 0) {
$scope.Business.Financials.HeaderYears.push('6 month ending ' + i);
}
j++;
}
}
$scope.assembleFinancialItem = function (Group) {
Group = Group ? Group : 0;
var date = new Date();
var year = date.getFullYear();
k = [];
for (i = 0; i <= $scope.Business.Financials.HeaderYears.length; i++) {
k.push({ "key": '' });
}
$scope.Business.Financials[Group]['rows'].push(k);
}
$scope.removeFinancialGroupRow = function (parentIndex, Index) {
$scope.Business.Financials[parentIndex].rows.splice(Index, 1);
$scope.saveFinancials();
}
$scope.removeFinancialRow = function (Index) {
$scope.ngConfirm('Are you sure you want to delete this group ?', function () {
$scope.Business.Financials.splice(Index, 1);
$scope.saveFinancials();
});
}
//new function added for spreadsheet
$scope.SaveBusinessOwner = function () {
$formName = 'BusinessOwner';
if (!$scope.OwnerData.length) {
$scope.showFlashMessage('error', "Please add owner information.");
return false;
}
if (checkstatus($formName, $scope)) {
var reqData = {
"SaveBusinessOwner": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"BusinessOwner": $scope.OwnerData,
"DealUID": $scope.FormData.DealUID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.getDealBusiness($scope.FormData.BusinessID);
$scope.DealStepComplete.IsOwnerInfoComplete = 1;
$scope.showTab(4);
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.setAllInactive = function () {
if ($scope.OwnerData.length) {
for (var i in $scope.OwnerData) {
$scope.OwnerData[i].active = false;
}
}
};
$scope.ActiveOwnerTab = function (index) {
if ($scope.OwnerData.length) {
$scope.setAllInactive();
$scope.OwnerData[index].active = true;
}
}
$scope.AddBusinessOwner = function () {
if ($scope.Business.BusinessID) {
$scope.setAllInactive();
$scope.OwnerData.push({ 'BusinessID': $scope.Business.BusinessID, 'active': true });
} else {
$scope.showFlashMessage('error', "Please complete the business section.");
}
}
$scope.removeOwner = function (index) {
$scope.ngConfirm('Are you sure you want to delete this owner ?', function () {
$scope.OwnerData.splice(index, 1);
if (index > 0) {
$scope.OwnerData[index - 1].active = true;
}
});
}
$scope.getDeal = function (callback) {
var reqData = {
"GetDeal": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"DealUID": this.deal ? this.deal.DealUID : $stateParams.DealUID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.FormData = response.Data;
$scope.FormData.DealTypes = [];
if ($scope.CompanyPreferences.ShowBookedDeal == 1) {
$scope.FormData.DealTypes.push('Booked Deal');
}
if ($scope.CompanyPreferences.ShowNewApplicationDeal == 1) {
$scope.FormData.DealTypes.push('New Application');
}
$scope.Business.Financials = [];
$scope.Business.Financials.GroupData = null;
var date = new Date();
var year = date.getFullYear();
$scope.Business.Financials.HeaderYears = [];
var j = 0
for (i = year; i > year - 4; i--) {
if (j == 0) {
$scope.Business.Financials.HeaderYears.push('6 month ending ' + i);
}
$scope.Business.Financials.HeaderYears.push('12/31/' + i);
j++;
}
$scope.Business.Financials.HeaderYears = $scope.Business.Financials.HeaderYears.reverse();
//for spreadsheet
$scope.deal.StatusMessage = response.Message;
angular.forEach(response.Data, function (value, key) {
if ($scope.FormData[key] === 0)
$scope.FormData[key] = null;
});
$scope.DealStepComplete.IsGeneralInfoComplete = 1;
for (var j in $rootScope.industryData) {
if ($rootScope.industryData[j].IndustryTypeID == $scope.FormData.IndustryID)
$scope.FormData.Industry = $rootScope.industryData[j];
}
$scope.FormData.ProgramType = _.findWhere($rootScope.ProgramTypeList, { ProgramTypeID: $scope.FormData.FinanceProductID });
for (var j in $scope.RatingData) {
if ($scope.RatingData[j].ID == $scope.FormData.CreditRating)
$scope.FormData.Rating = $scope.RatingData[j];
}
for (var j in $rootScope.syndicateUsers) {
if ($rootScope.syndicateUsers[j].PrimaryContactID == $scope.FormData.SalesRepresentativeID)
$scope.FormData.SalesRepresentative = $rootScope.syndicateUsers[j];
}
if ($state.current.name == "edit-deal-manual") {
$scope.getDealBusiness($scope.FormData.BusinessID);
}
if ($state.current.name == "deal" || $state.current.name == "edit-deal-manual") {
//set N/A if amount is not saved
if ($scope.FormData.Amount)
$scope.FormData.Amount = $filter('currency')($scope.FormData.Amount);
else
$scope.FormData.Amount = 'N/A';
}
appInfo.getAdditionalData({ 'ModuleID': 17, 'ModuleEntityID': $scope.FormData.DealUID }, function (response) {
if (response.ResponseCode == 200) {
$scope.FormData.others = response.Data;
}
});
if (_.isFunction(callback))
callback(response);
}
else {
$scope.showFlashMessage('error', "Deal not found.");
}
} else {
$scope.showFlashMessage('error', response.Message);
$state.go('syndication-desk');
}
});
return false;
}
$scope.getDealBusiness = function (BusinessID) {
if (!BusinessID) {
return;
}
var reqData = {
"GetDealBusiness": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"CompanyID": $scope.CompanyPreferences.CompanyID,
"BusinessID": BusinessID,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.BusinessData) {
if (response.Data.BusinessData) {
$scope.Business = response.Data.BusinessData;
$scope.Business.Financials = [];
$scope.Business.Financials.GroupData = null;
var date = new Date();
var year = date.getFullYear();
//var month = date.getMonth();
$scope.Business.Financials.HeaderYears = [];
var j = 0
for (i = year; i > year - 4; i--) {
if (j == 0) {
$scope.Business.Financials.HeaderYears.push('6 month ending ' + i);
}
$scope.Business.Financials.HeaderYears.push('12/31/' + i);
j++;
}
$scope.Business.Financials.HeaderYears = $scope.Business.Financials.HeaderYears.reverse();
$scope.getFinancialsData();
for (var j in $rootScope.industryData) {
if ($rootScope.industryData[j].IndustryTypeID == $scope.Business.IndustryTypes)
$scope.Business.IndustryTypes = $rootScope.industryData[j];
}
for (var j in $rootScope.legalStructureData) {
if ($rootScope.legalStructureData[j].LegalStructureID == $scope.Business.LegalStructureID)
$scope.Business.LegalStructure = $rootScope.legalStructureData[j];
}
for (var j in $rootScope.stateData) {
if ($rootScope.stateData[j].StateID == $scope.Business.StateID)
$scope.Business.StateID = $rootScope.stateData[j];
}
if ($scope.Business.Geometry)
$scope.businessCoords = $scope.Business.Geometry.location.lat + "," + $scope.Business.Geometry.location.lng;
var timeinbusiness = $scope.Business.TimeInBusiness;
if (timeinbusiness) {
var split = timeinbusiness.split("-");
var year = parseInt(split[0]);
var month = parseInt(split[1]);
for (var j in $scope.MasterMonths) {
if ($scope.MasterMonths[j].key == month)
$scope.Business.Month = $scope.MasterMonths[j];
}
for (var j in $scope.Years) {
if ($scope.Years[j].Year == year)
$scope.Business.Year = $scope.Years[j];
}
}
$scope.DealStepComplete.IsBusinessInfoComplete = 1;
}
if (response.Data.BusinessOwner.length > 0) {
$scope.OwnerData = response.Data.BusinessOwner;
for (var i in $scope.OwnerData) {
for (var j in $rootScope.stateData) {
if ($rootScope.stateData[j].StateID == $scope.OwnerData[i].StateID)
$scope.OwnerData[i].StateID = $rootScope.stateData[j];
}
}
if ($scope.OwnerData.length > 0) {
$scope.OwnerData[0].active = true;
}
$scope.DealStepComplete.IsOwnerInfoComplete = 1;
} else {
$scope.OwnerData.push({ 'BusinessID': BusinessID, 'active': true });
}
} else {
$scope.showFlashMessage('error', "Deal not found.");
$state.go('syndication-desk');
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
return false;
}
$scope.ChangeStatus = function (StatusID, dealID, $index, isPrivateSharedOnly) {
var DealID = dealID;//this.deal.DealID;
var Index = this.$index;
$formName = 'formPublishDeal';
$scope.selectedDeal.IsPrivateSharedOnly = isPrivateSharedOnly ? isPrivateSharedOnly : 0;
if (!$scope.selectedDeal.IsPrivateSharedOnly || checkstatus($formName, $scope)) {
if (StatusID == 1) {
var text = "Pending";
} else if (StatusID == 35) {
var text = "publish";
} else if (StatusID == 3) {
var text = "Delete";
}
$rootScope.ngConfirm('Are you sure you want to ' + text + ' this deal?', function () {
//publish deal if status 35
var reqData = {
"ChangeDealStatus": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"StatusID": StatusID,
"DealID": DealID,
// "DealUID": this.Deal.DealUID,
"IsPrivateSharedOnly": $scope.selectedDeal.IsPrivateSharedOnly,
"MarketPlaceUsers": $scope.selectedDeal.MarketPlaceUsers
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (StatusID == 3) {
///$scope.deals.splice(Index,1);
//if(!$scope.deals.length)
$scope.refreshSyndicationDeskList();
$scope.showFlashMessage('success', response.Message);
} else if (StatusID == 35) {
if ($stateParams.DealUID) {
// $location.path('/deal/'+$stateParams.DealUID);
$location.path('syndication-desk');
//$state.reload();
$scope.showFlashMessage('success', response.Message);
}
else
$location.path('/deal/' + $scope.deals[Index].DealUID);
}
else if (StatusID == 1) {
$scope.refreshSyndicationDeskList();
}
else {
if ($scope.dealTabFlag != "All") {
$scope.refreshSyndicationDeskList();
} else {
$scope.deals[Index].StatusID = StatusID;
}
$scope.showFlashMessage('success', response.Message);
}
ngDialog.close();
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
});
}
}
$scope.getFileType = function (ImgName) {
return ext = ImgName.substr(ImgName.lastIndexOf('.') + 1);
}
$scope.getSalePersonName = function (id) {
for (var j in $rootScope.salesPersons) {
if ($rootScope.salesPersons[j].ID == id)
return $rootScope.salesPersons[j].Name;
}
}
$scope.getIndustryName = function (id) {
for (var j in $rootScope.industryData) {
if ($rootScope.industryData[j].IndustryTypeID == id)
return $rootScope.industryData[j].Name;
}
}
$scope.downloadDocument = function () {
if (this.fileItem)
$scope.selectedApplicationDocument = this.fileItem;
var form = angular.element('#frmDownload').attr('action', appInfo.appDocumentDownloadUrl);
form.find('[name="FileName"]').val($scope.selectedApplicationDocument.ImageName);
form.find('[name="DownloadURL"]').val($scope.selectedApplicationDocument.ImageUrl);
form.submit();
}
$scope.publishDealDialog = function (dealID) {
$scope.DealID = this.deal.DealID ? this.deal.DealID : dealID;
$scope.$index = this.$index;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-publishDeal.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
$scope.submitFeedback = function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-sendFeedbackPopup.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
$scope.sendFeedback = function () {
var reqData = {
"SendFeedback": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealUID": $scope.deal.DealDetail.DealUID,
"BuyerRating": $scope.deal.DealDetail.BuyerRating,
"BuyerFeedbackComment": $scope.deal.DealDetail.BuyerFeedbackComment
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
ngDialog.close();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.dateDiffInYears = function (dateold) {
if (dateold && dateold != '-') {
var datenew = new Date();
var ynew = datenew.getFullYear();
var mnew = datenew.getMonth();
var oldyear = dateold.split('-');
var yold = oldyear[0];
var mold = oldyear[1];
var months = (ynew - yold) * 12;
months -= mold;
months += mnew;
years = parseInt(months / 12);
months = parseInt(months % 12);
years = (years > 1) ? years + ' years' : ((years) ? years + ' year' : '');
months = (months > 1) ? months + ' months' : ((months) ? months + ' month' : '');
return years + ' ' + months;
}
};
$scope.getSyndicatedTimeDiff = function (dealPublishDate, SyndicatedDate) {
if (dealPublishDate && SyndicatedDate) {
var today = new Date(SyndicatedDate);
var PublishDate = new Date(dealPublishDate);
var diffMs = (today - PublishDate); // milliseconds between publish & syndication date
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
diffDays = ("0" + Math.abs(diffDays)).slice(-2);
diffHrs = ("0" + Math.abs(diffHrs)).slice(-2);
diffMins = ("0" + Math.abs(diffMins)).slice(-2);
return diffDays + ':' + diffHrs + ":" + diffMins;
} else {
return 'n/a';
}
};
$scope.getProgramTypeName = function (id) {
for (var j in $rootScope.ProgramTypeList) {
if ($rootScope.ProgramTypeList[j].ProgramTypeID == id)
return $rootScope.ProgramTypeList[j].ProgramTypeName;
}
};
$scope.getVolumeName = function (id) {
for (var j in $rootScope.VolumeSyndicates) {
if ($rootScope.VolumeSyndicates[j].SyndicatedAnnualVolumeID == id)
return $rootScope.maxDisplayPages[j].SyndicatedAnnualVolumeName;
}
}
$scope.showPlusButton = true;
$scope.toggleIcon = function () {
$scope.showPlusButton = $scope.showPlusButton ? false : true;
}
if ($state.current.name != "edit-deal-manual") {
$scope.$watch('FormData.DealType', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue) {
//add deal/edit deal value blank
/*$scope.FormData.InternalYield =null;
$scope.FormData.ReserveRate =null;
$scope.FormData.RemainingBalance =null;
$scope.FormData.QuotedRate =null;
$scope.FormData.Buyrate =null;
$scope.FormData.LoanAmount =null;*/
}
}, 700));
}
$scope.SeeRecord = function () {
pagingData.numPerPage = $scope.SeeRecordData.maxDisplayPages;
$rootScope.SeeRecordData.maxDisplayPages = $scope.SeeRecordData.maxDisplayPages;
$scope.refreshFileList();
}
$scope.getSampleDealData = function () {
var reqData = {
"GetSampleDealData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"MarkAsSampleDeal": TRUE
}
}
$scope.Page.trackLoading('sample-deal');
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('sample-deal');
if (response.ResponseCode == 200) {
if (response.Data) {
$location.path('/deal/' + response.Data.DealUID);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.navigateWizard = function (button) {
switch ($state.current.name) {
case 'add-deal.generalinfo':
case 'add-deal':
case 'edit-deal.generalinfo':
if (checkstatus('addDealForm', $scope)) {
setTimeout(function () {
$state.go('edit-deal.documents', { DealUID: $scope.FormData.DealUID });
$scope.refreshFileList();
}, 2000);
}
break;
case 'edit-deal.documents':
$state.go('edit-deal.generalinfo', { DealUID: $scope.FormData.DealUID });
break;
}
}
$scope.finish = function () {
if ($scope.previousStateData && $scope.previousStateData.name == 'select-deal') {
Storage.setItem('previousStateData', {});
$scope.previousStateData = {};
$state.go('select-deal');
}
else {
$state.go('syndication-desk');
}
}
$scope.initAddDeal();
}])
//Deal Options controller
.controller('DealOptionsController', ['$rootScope', '$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', '$filter', '$location', function ($rootScope, $scope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q, $filter, $location) {
if ($rootScope.$root.SignIn)
$scope.LoginUsrName = $rootScope.$root.SignIn.UserDetails.FirstName + ' ' + $rootScope.$root.SignIn.UserDetails.LastName;
else
$scope.LoginUsrName = '';
$scope.Page.Title = 'Deal - ' + $rootScope.CompanyPreferences.CompanyName;
$scope.ShowConnections = false;
$scope.isAlreadyPublished = false;
if ($scope.ShowConnections)
$scope.switchDealTabFlag = 'connectionTab';
else {
if ($state.params.link != 'offers')
$scope.switchDealTabFlag = 'dealSnapshotTab';//'requestTab';
}
$scope.dealSnapshotLink = $scope.baseURL + "/partials/deal-snapshot.html";
$scope.ConnectionFilter = {};
$scope.InvitationMessage = $scope.LoginUsrName + ' has published a new deal and invited you to deal.';
$scope.InviteOtherConnections = '';
// $scope.chatRoomNumber='';
$scope.ConnectionFilter.IsOtherConnections = '';
$scope.RatingData = [{ 'Name': 'Excellent', 'ID': 1 }, { 'Name': 'Very Good', 'ID': 2 }, { 'Name': 'Good', 'ID': 3 }, { 'Name': 'Fair', 'ID': 4 }, { 'Name': 'Poor', 'ID': 5 }];
$scope.DealTotalDetails = {};
/*$scope.switchDealTab = function(switchDealTabFlag){
$scope.switchDealTabFlag = switchDealTabFlag;
}*/
$scope.clickEditDeal = function (dealUID) {
if ($scope, this.DealTotalDetails.DealDetail.StatusID == 9)
$location.path('edit-deal/generalinfo/' + dealUID);
else
$location.path('edit-deal-manual/' + dealUID);
}
$scope.getDefaultChatWindow = function (userID) {
//close existing popup
closeNav('marketPlaceUserProfilePopup');
var chatRoom = {
LoginSessionKey: $scope.SignIn.LoginSessionKey,
chatTitle: $scope.deal.DealDetail.DealName + ' - ' + $scope.CompanyPreferences.CompanyName,
associatedEntityType: 'Deal',
associationEntityID: $scope.deal.DealUID,
members: [userID]
};
$scope.chat.openChatRoom(chatRoom);
}
var getCurrentDateTime = function () {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
return (year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds);
};
$scope.switchDealTab = function (switchDealTabFlag, secondaryTab) {
if (!secondaryTab)
$scope.switchDealTabFlag = switchDealTabFlag;
else
$scope.deal.secondaryActiveTab = switchDealTabFlag;
switch (switchDealTabFlag) {
case "dealViewTab":
$scope.deal.secondaryActiveTab = 'GeneralInformation';
if (!$scope.Business.BusinessName)
$scope.getDealBusiness($scope.FormData.BusinessID);
break;
case "BusinessInformation":
case 'Owner':
if (!$scope.Business.BusinessName)
$scope.getDealBusiness($scope.FormData.BusinessID);
break;
case 'connectionTab':
$scope.deal.secondaryActiveTab = 'All';
break;
case 'uploadDocumentsTab':
//
break;
case 'notesTab':
break;
case 'messageTab':
$scope.getChatRooms();
break;
}
};
$scope.isPublished = function (dealData) {
if (dealData) {
var publishStatus = [35, 39, 42, 50, 51];
if (publishStatus.indexOf(dealData.StatusID) !== -1) {
$scope.ShowConnections = FALSE;
if (!$scope.isAlreadyPublished) {
$scope.isAlreadyPublished = true;
$scope.switchDealTabFlag = 'dealSnapshotTab';
}
return true;
}
}
return false;
};
$scope.getDealSnapshot = function (callback) {
if ($state.current.name == 'deal-snapshot') {
$scope.dealSnapshotClass = 'container content-wrapper';
} else {
$scope.dealSnapshotClass = 'content-wrapper1';
}
var reqData = {
"GetDealSnapshot": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"CompanyID": $scope.CompanyPreferences.CompanyID,
"DealUID": $stateParams.DealUID,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.DealTotalDetails = response.Data;
if ($state.current.name == "view-deal") {
if (!response.Data.DealDetail.CanView) {
$scope.showFlashMessage('error', "You are authorize to access this page.");
$state.go('syndication-desk');
} else {
$scope.FormData = response.Data.DealDetail;
$scope.DealStepComplete.IsGeneralInfoComplete = 1;
for (var j in $scope.industryData) {
if ($rootScope.industryData[j].IndustryTypeID == $scope.FormData.IndustryID)
$scope.FormData.Industry = $scope.industryData[j];
}
for (var j in $scope.ProgramTypeList) {
if ($rootScope.ProgramTypeList[j].ProgramTypeID == $scope.FormData.FinanceProductID)
$scope.FormData.ProgramType = $scope.ProgramTypeList[j];
}
for (var j in $scope.RatingData) {
if ($scope.RatingData[j].ID == $scope.FormData.CreditRating)
$scope.FormData.Rating = $scope.RatingData[j];
}
for (var j in $scope.salesPersons) {
if ($scope.salesPersons[j].ID == $scope.FormData.SalesRepresentativeID)
$scope.FormData.SalesRepresentative = $scope.salesPersons[j];
}
}
} else {
//set N/A if amount is not saved
if (response.Data.DealDetail.Amount)
response.Data.DealDetail.Amount = $filter('currency')(response.Data.DealDetail.Amount);
else
response.Data.DealDetail.Amount = 'N/A';
//assign value in array
for (var p in response.Data) {
$scope.deal[p] = response.Data[p];
}
if ($state.params.link == 'offers') {
$scope.moduleEntity = $scope.deal;
$scope.switchDealTabFlag = 'offers';
}
}
} else {
$scope.showFlashMessage('error', "Deal not found.");
$state.go('syndication-desk');
}
if (typeof callback != 'undefined' && callback != '')
callback();
} else if (response.ResponseCode == 404) {
// $scope.showFlashMessage('error', response.Message);
$state.go('not-found');
}
});
return false;
};
$scope.getStateName = function (id) {
var state = _.findWhere($scope.stateData, { StateID: id });
return state.Name;
}
$scope.changeDealStatus = function (StatusID) {
// var currentDealData = this
$rootScope.ngConfirm("Are you sure you want to change deal's status ?", function () {
var reqData = {
"ChangeDealStatus": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID,
"StatusID": StatusID,
"DealID": $scope.deal.DealDetail.DealID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.deal.StatusMessage = response.Message;
$scope.getDealSnapshot();
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
});
};
$scope.showBidDiscription = function () {
//console.log(this.bid);
$scope.currentBidData = this.bid;
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-bid-details-popup.html?v=' + RELEASE_VERSION,
scope: $scope,
className: 'ng-popup ngdialog-theme-default'
});
}
$scope.getChatRooms = function () {
var reqData = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"filters": {
entityType: "Deal",
entityID: $stateParams.DealUID,
}
};
appInfo.getChatRooms(reqData, function (response) {
if (response.ResponseCode == 200) {
$scope.chat.representatives = [];
$scope.deal.chatRooms = response.Data;
for (var i in response.Data) {
// $scope.keys.push(response.Data[i].chatRoomID);
// $scope.chat.rooms[response.Data[i].chatRoomID]=response.Data[i];
if (Array.isArray($scope.chat.representatives) && $scope.chat.representatives.indexOf(response.Data[i].representative.UserID) == -1)
$scope.chat.representatives.push(response.Data[i].representative.UserID);
}
appInfo.getSocketData({ 'checkOnlineUsers': $scope.chat.representatives }, function (r) {
$scope.chat.onlineUsers = r.checkOnlineUsers;
});
}
$scope.Page.untrackLoading("activeChatRooms");
});
}
if ($location.hash()) {
$scope.switchDealTab($location.hash());
} else if ($stateParams.link) {
$scope.switchDealTab($stateParams.link);
}
$scope.FormData.DealType = null;
$scope.FormData.OriginationSource = null;
// $scope.getDeal(function(){
if (!_.isUndefined($scope.Business.BusinessID))
$scope.getFinancialsData();
// });
}])
//Deal Options controller
.controller('ModuleConnectionsController', ['$rootScope', '$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', '$filter', '$location', function ($rootScope, $scope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q, $filter, $location) {
var initController = function () {
switch ($scope.moduleName) {
case 'Deal':
$scope.ModuleKey = $scope.deal.DealDetail ? $scope.deal.DealDetail.DealID : false;
$scope.$parent.$parent.moduleEntity = $scope.deal;
$scope.$parent.$parentModuleEntityID = $scope.deal.DealUID;
break;
case 'Deal Pool':
$scope.ModuleKey = $scope.dealPool.DealPoolID;
$scope.$parent.$parent.moduleEntity = $scope.dealPool;
$scope.$parent.$parent.ModuleEntityID = $scope.dealPool.PoolUID;
break;
}
if (!$scope.ModuleKey)
$timeout(initController, 800);
}
if ($scope.moduleName == 'Deal Pool') {
// $scope.getPoolDetails(function(){
$timeout(initController, 1000);
// })
}
else {
$timeout(initController, 1000);
}
$scope.CreditData = { fico: {}, paydex: {}, paynet: {} };
$scope.ConnectionFilter = {};
$scope.LoginUserName = $scope.SignIn.UserDetails.FirstName + ' ' + $scope.SignIn.UserDetails.LastName;
$scope.InvitationMessage = $scope.LoginUserName + ' has published a new deal and invited you to deal.';
$scope.InviteOtherConnections = '';
// $scope.chatRoomNumber='';
$scope.ConnectionFilter.IsOtherConnections = '';
var getCurrentDateTime = function () {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
return (year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds);
};
$scope.dealOtherConnectionPopup = function () {
$scope.ConnectionFilter.IsOtherConnection = true;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-dealConnectionPopup.html',
className: 'ng-popup ngdialog-theme-default custom-width',
scope: $scope
});
};
$scope.dealConnectionPopup = function (connection, isInvited) {
$scope.SelectedConnection = connection;
$scope.ConnectionFilter.IsInvited = isInvited;
$scope.ConnectionFilter.IsOtherConnection = false;
if (isInvited) {
$rootScope.ngConfirm("Are you sure you want to revoke access to this user ?", function () {
//revoke connection
$scope.inviteConnection(connection);
});
} else {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-dealConnectionPopup.html',
className: 'ng-popup ngdialog-theme-default custom-width',
scope: $scope
});
}
};
$scope.invitationPopup = function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-invitaionPopup.html',
className: 'ng-popup ngdialog-theme-default right',
scope: $scope
});
};
$scope.getStateName = function (id) {
var state = _.findWhere($scope.stateData, { StateID: id });
return state.Name;
}
$scope.inviteConnection = function (connectionData, msg, isOtherConnection, otherConnections) {
$formName = 'formInviteConnection';
if (checkstatus($formName, $scope)) {
//invite Other Connections
if (isOtherConnection) {
appInfo.getServerData({
"InviteOtherConnections": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealID": $scope.deal.DealDetail.DealID,
"DealUID": $scope.deal.DealDetail.DealUID,
"InvitationMessage": msg,
"MarketPlaceUsers": $scope.ConnectionFilter.IsOtherConnections
}
}).then(function (response) {
var msgClass = "error";
if (response.ResponseCode == 200) {
// $scope.deal.access.paginator.currentPage=1;
$scope.getConnections();
$scope.ConnectionFilter.IsOtherConnections = '';
$scope.InvitationMessage = $scope.LoginUsrName + ' has published a new deal and invited you for a deal.';
msgClass = "success";
ngDialog.close();
}
$scope.showFlashMessage(msgClass, response.Message);
});
} else {
if (connectionData.IsInvited || connectionData.DealAccessID) {
//revoke access if already invited
appInfo.getServerData({
"RevokeDealAccess": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealAccessID": connectionData.IsInvited ? connectionData.IsInvited : connectionData.DealAccessID,
"Module": $scope.moduleName,
"ModuleEntityID": $scope.ModuleEntityID,
"ModuleKey": $scope.ModuleKey,
"LenderName": connectionData.FullName,
}
}).then(function (response) {
var msgClass = "error";
if (response.ResponseCode == 200) {
$scope.ConnectionFilter.IsOtherConnections = '';
$scope.InvitationMessage = $scope.LoginUsrName + ' has published a new deal and invited you for a deal.';
msgClass = "success";
ngDialog.close();
closeNav('marketPlaceUserProfilePopup');
switch ($scope.moduleEntity.secondaryActiveTab) {
case 'All':
$scope.moduleEntity.getConnections();
break;
case 'Invited':
$scope.moduleEntity.getAccess();
break;
}
}
$scope.showFlashMessage(msgClass, response.Message);
});
} else {
if (!$scope.ModuleKey) {
$scope.ModuleKey = ($scope.moduleName == 'Deal Pool') ? $scope.dealPool.DealPoolID : $scope.deal.DealDetail.DealID;
}
//Invite for deal access
appInfo.getServerData({
"InviteDealAccess": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Module": $scope.moduleName,
"ModuleEntityID": $scope.ModuleEntityID,
"ModuleKey": $scope.ModuleKey,
"LenderName": connectionData.FullName,
"UserID": connectionData.UserID,
"Email": connectionData.Email,
"InvitationMessage": msg,
/*"Filter":{
"marketPlaceUserFilter_Name":$scope.ConnectionFilter.Name,
},*/
"PageNo": ($scope.moduleEntity && $scope.moduleEntity.connections) ? $scope.moduleEntity.connections.paginator.currentPage : 1,
}
}).then(function (response) {
var msgClass = "error";
if (response.ResponseCode == 200) {
// $scope.deal.access.paginator.currentPage=1;
$scope.moduleEntity.getConnections();
msgClass = "success";
$scope.ConnectionFilter.IsOtherConnections = '';
$scope.InvitationMessage = $scope.LoginUserName + ' has published a new deal and invited you for a deal.';
ngDialog.close();
closeNav('marketPlaceUserProfilePopup');
}
$scope.showFlashMessage(msgClass, response.Message);
});
}
}
}
};
$scope.getSyndicateData = function () {
var reqData = {
"GetSyndicateData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $scope.CompanyData.CompanyID,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
var res = response.Data[0];
$scope.SyndicateData = res;
for (var j in $rootScope.syndicateUsers) {
if ($rootScope.syndicateUsers[j].PrimaryContactID == res.PrimarySyndicateID)
$scope.SyndicateData.SyndicateUser = $rootScope.syndicateUsers[j];
}
for (var j in $rootScope.VolumeSyndicates) {
if ($rootScope.VolumeSyndicates[j].SyndicatedAnnualVolumeID == res.SyndicatedAnnualVolumeID)
$scope.SyndicateData.SyndicatedAnnualVolumeID = $rootScope.VolumeSyndicates[j];
}
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
};
$scope.getEquipmentData = function () {
var reqData = {
"GetEquipmentData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $scope.CompanyData.CompanyID,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
var responseData = response.Data;
$scope.CompanyEquipmentTypes = [];
for (var i in responseData) {
$scope.CompanyEquipmentTypes.push({
EquipmentType: _.findWhere($rootScope.equipmenttypes, { EquipmentTypeID: responseData[i].EquipmentTypeID }),
EquipmentTypeValue: responseData[i].EquipmentTypeValue
});
}
//console.log($scope.CompanyEquipmentTypes)
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
};
$scope.getCreditData = function () {
var reqData = {
"GetCreditData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $scope.CompanyData.CompanyID,
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
var res = response.Data[0];
$scope.CreditData = res;
$scope.CreditData.fico = {
minScore: 350,
maxScore: 850
};
$scope.CreditData.paydex = {
minScore: 0,
maxScore: 100
};
$scope.CreditData.paynet = {
minScore: 450,
maxScore: 850
};
$scope.CreditData.fico.minScore = $scope.CreditData.FICOMinScore;
$scope.CreditData.fico.maxScore = $scope.CreditData.FICOMaxScore;
$scope.CreditData.paydex.minScore = $scope.CreditData.PaydexMinScore;
$scope.CreditData.paydex.maxScore = $scope.CreditData.PaydexMaxScore;
$scope.CreditData.paynet.minScore = $scope.CreditData.PaynetMinScore;
$scope.CreditData.paynet.maxScore = $scope.CreditData.PaynetMaxScore;
}
else {
$scope.CreditData.fico = {
minScore: 350,
maxScore: 850
};
$scope.CreditData.paydex = {
minScore: 0,
maxScore: 100
};
$scope.CreditData.paynet = {
minScore: 450,
maxScore: 850
};
}
}
else {
$scope.showFlashMessage('error', response.Message);
}
});
};
$scope.showMarketPlaceUserProfile = function (data, isInvited, isInviteAllowed) {
$scope.SelectedConnection = data;
$scope.ConnectionFilter.IsInvited = (isInvited) ? true : false;
$scope.ConnectionFilter.IsOtherConnection = false;
$scope.IsInviteAllowed = isInviteAllowed;
appInfo.getCompanyPreferences(function () {
appInfo.getStates(function () {
$scope.CompanyData.StateID = _.findWhere($scope.stateData, { StateID: $scope.CompanyData.StateID });
appInfo.getequipmenttype(function () {
$scope.CompanyData.EquipmentType = null;
$scope.CompanyEquipmentTypes = [];
});
appInfo.getsyndicateusers(function () {
$scope.CompanyData.SyndicateUser = null;
});
appInfo.getAnnualVolumeSyndicates(function () {
$scope.CompanyData.VolumeSyndicate = null;
});
$scope.getSyndicateData();
$scope.getCreditData();
$scope.getEquipmentData();
openNav('marketPlaceUserProfilePopup');
});
}, data);
};
$scope.showBidDiscription = function () {
//console.log(this.bid);
$scope.currentBidData = this.bid;
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-bid-details-popup.html?v=' + RELEASE_VERSION,
scope: $scope,
className: 'ng-popup ngdialog-theme-default'
});
}
}])
//Deal Log controller
.controller('DealLogController', ['$scope', 'appInfo', '$state', function ($scope, appInfo, $state) {
$scope.entity = ($state.current.name == 'view-pool') ? $scope.dealPool : $scope.deal;
$scope.entity.getLog = function () {
var params = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"PageNo": $scope.entity.log ? $scope.entity.log.paginator.currentPage : 1
};
if ($state.params.PoolUID) {
params.PoolUID = $state.params.PoolUID;
} else {
params.DealUID = $state.params.DealUID;
}
appInfo.getServerData({
"GetDealUpdateLog": params
}).then(function (response) {
$scope.entity.log = response.Data;
$scope.entity.showingDealLogText = 'Showing ' + $scope.entity.log.paginator.currentPage + ' to ' + Math.ceil($scope.entity.log.paginator.count / 10) + ' of ' + $scope.entity.log.paginator.count;
});
}
if (!$scope.entity.log) {
$scope.entity.getLog();
}
}])
//Deal Requests controller
.controller('DealRequestsController', ['$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', function ($scope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q) {
switch ($scope.moduleName) {
case 'Deal':
$scope.$parent.$parent.moduleEntity = $scope.deal;
$scope.$parent.$parent.ModuleEntityID = $scope.deal.DealUID;
break;
case 'Deal Pool':
$scope.moduleEntity = $scope.dealPool;
$scope.ModuleEntityID = $scope.dealPool.PoolUID;
break;
}
$scope.getRequests = function () {
appInfo.getServerData({
"ListModuleRequests": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Module": $scope.moduleName,
"ModuleEntityID": $scope.ModuleEntityID,
"PageNo": $scope.moduleEntity.Requests ? $scope.moduleEntity.requests.paginator.currentPage : 1
}
}).then(function (response) {
$scope.moduleEntity.requests = {
list: response.Data[$scope.moduleName == 'Deal' ? 'Dealaccessrequest' : 'Module_requests'],
paginator: {
count: response.Data.Paginator[$scope.moduleName == 'Deal' ? 'total_dealaccessrequest' : 'total_module_requests'],
currentPage: response.Data.Paginator.current_page,
}
};
});
}
$scope.getRequests();
$scope.acceptDealAccessRequest = function (accept) {
appInfo.getServerData({
"ProcessModuleEntityRequest": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Module": $scope.moduleName,
"RequestID": this.request.RequestID,
"accept": accept
}
}).then(function (response) {
var msgClass = "error";
if (response.ResponseCode == 200) {
$scope.moduleEntity.requests.paginator.currentPage = 1;
$scope.getRequests();
msgClass = "success";
if ($scope.moduleEntity.log && $scope.moduleEntity.log.paginator.currentPage == 1)
$scope.moduleEntity.getLog();
}
$scope.showFlashMessage(msgClass, response.Message);
});
}
}])
//Deal Access controller
.controller('DealAccessController', ['$rootScope', '$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', function ($rootScope, $scope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q) {
switch ($scope.moduleName) {
case 'Deal':
$scope.moduleEntity = $scope.deal;
$scope.ModuleEntityID = $scope.deal.DealUID;
break;
case 'Deal Pool':
$scope.$parent.$parent.moduleEntity = $scope.dealPool;
$scope.$parent.$parent.ModuleEntityID = $scope.dealPool.PoolUID;
break;
}
$scope.ConnectionFilter = {};
$scope.moduleEntity.getAccesses = function () {
appInfo.getServerData({
"ListDealAccesses": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Module": $scope.moduleName,
"ModuleEntityID": $scope.ModuleEntityID,
"Filter": {
"marketPlaceUserFilter_Name": $scope.ConnectionFilter.Name,
},
"PageNo": $scope.moduleEntity.Requests ? $scope.moduleEntity.requests.paginator.currentPage : 1,
"SharedFiles": $scope.selectedFileIds
}
}).then(function (response) {
if (response.ResponseCode == 200) {
$scope.moduleEntity.access = {
list: response.Data.Deal_access,
paginator: {
count: response.Data.Paginator.total_deal_access,
currentPage: response.Data.Paginator.current_page,
}
};
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.Page.trackLoading('deal-documents');
setTimeout(function () {
$scope.Page.documents = {
"zipName": $scope.FormData.DealName,
"ModuleEntityID": $scope.ModuleEntityID,
"ModuleName": "DealDocuments",
"selectedFiles": [],
"DocumentsData": [],
"selectedFileIds": [],
"FolderName": [],
"checkedFile": false,
"filter": { "currentPage": 1 },
"shareWithList": $scope.moduleEntity.getAccesses,
"blockEdit": $scope.FormData.MarkAsSampleDeal,
"blockSelect": $scope.FormData.MarkAsSampleDeal,
"blockDelete": $scope.FormData.MarkAsSampleDeal
}
$scope.Page.untrackLoading('deal-documents');
if ($scope.ModuleEntityID)
$rootScope.refreshFileList();
}, 2000);
$scope.RevokeDealAccess = function () {
appInfo.getServerData({
"RevokeDealAccess": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealAccessID": this.access.DealAccessID
}
}).then(function (response) {
var msgClass = "error";
if (response.ResponseCode == 200) {
$scope.moduleEntity.access.paginator.currentPage = 1;
$scope.moduleEntity.getAccesses();
msgClass = "success";
if ($scope.moduleEntity.log && $scope.moduleEntity.log.paginator.currentPage == 1)
$scope.moduleEntity.getLog();
}
$scope.showFlashMessage(msgClass, response.Message);
});
};
$scope.$watch('ConnectionFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue)
$scope.getAccesses();
}, 700));
$scope.tabNum = 1;
$scope.setTab = function (setTab) {
$scope.tabNum = setTab;
//console.log($scope.tabNum);
}
$scope.tab = function (tab) {
return $scope.tabNum === tab;
}
}])
.controller('DealUserConnectionController', ['$scope', '$rootScope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', function ($scope, $rootScope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q) {
$scope.connectionActiveTab = 'All';
$scope.ConnectionFilter = {};
$scope.SelectedConnection = {};
$scope.MarketPlaceUsers = '';
$timeout(function () {
switch ($scope.moduleName) {
case 'Deal':
$scope.moduleEntity = $scope.deal;
$scope.ModuleEntityID = $scope.deal.DealUID;
break;
case 'Deal Pool':
$scope.moduleEntity = $scope.dealPool;
$scope.ModuleEntityID = $scope.dealPool.PoolUID;
break;
}
$scope.moduleEntity.getConnections = function (Status) {
appInfo.getServerData({
"getModuleConnections": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Module": $scope.moduleName,
"ModuleEntityID": $scope.ModuleEntityID,
"Filter": {
"marketPlaceUserFilter_Name": $scope.ConnectionFilter.Name,
},
"PageNo": ($scope.moduleEntity && $scope.moduleEntity.connections) ? $scope.moduleEntity.connections.paginator.currentPage : 1,
}
}).then(function (response) {
$scope.moduleEntity.connections = {
list: response.Data.Userlogins,
paginator: {
count: response.Data.Paginator.total_userlogins,
currentPage: response.Data.Paginator.current_page,
}
};
$scope.currentConnectionData = {};
Storage.setItem('currentConnectionData', $scope.currentConnectionData);
});
};
$scope.moduleEntity.getConnections();
}, 800);
$scope.inviteConnectionsDialog = function (isUserExists, connection) {
$scope.DealID = $scope.deal.DealDetail.DealID;
$scope.IsUserExists = isUserExists;
$scope.$index = this.$index;
$scope.SelectedConnection = connection;
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-inviteConnection.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
/*$scope.inviteConnection=function(connectionData){
$formName = 'formInviteConnection';
if (checkstatus($formName, $scope)){
if(connectionData.IsInvited){
//revoke access if already invited
appInfo.getServerData({
"RevokeDealAccess":{
"LoginSessionKey":$scope.SignIn.LoginSessionKey,
"DealAccessID":connectionData.IsInvited
}
}).then(function(response){
var msgClass="error";
if(response.ResponseCode==200){
// $scope.deal.access.paginator.currentPage=1;
$scope.getConnections();
msgClass="success";
}
$scope.showFlashMessage(msgClass,response.Message);
});
} else {
//Invite for deal access
appInfo.getServerData({
"InviteDealAccess":{
"LoginSessionKey":$scope.SignIn.LoginSessionKey,
"DealID":$scope.deal.DealDetail.DealID,
"LenderName":connectionData.FullName,
"UserID":connectionData.UserID,
"Email":connectionData.Email,
"Filter":{
"marketPlaceUserFilter_Name":$scope.ConnectionFilter.Name,
},
"PageNo":$scope.deal.connections?$scope.deal.connections.paginator.currentPage:1,
}
}).then(function(response){
var msgClass="error";
if(response.ResponseCode==200){
// $scope.deal.access.paginator.currentPage=1;
$scope.getConnections();
msgClass="success";
}
$scope.showFlashMessage(msgClass,response.Message);
});
}
}67 };*/
$scope.$watch('ConnectionFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue)
$scope.moduleEntity.getConnections();
}, 700));
$scope.invitationPopup = function () {
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-invitaionPopup.html',
className: 'ng-popup ngdialog-theme-default right',
scope: $scope
});
}
}])
.controller('OtherInviteController', ['$scope', '$rootScope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', function ($scope, $rootScope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q) {
$scope.invites = {};
$scope.InviteFilter = {};
$scope.getOtherInvites = function () {
appInfo.getServerData({
"ListOtherInvites": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealID": $scope.deal.DealDetail.DealID,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"PageNo": $scope.deal.invites ? $scope.deal.invites.paginator.currentPage : 1,
"Filter": {
"otherInviteFilter_Name": $scope.InviteFilter.Name,
},
}
}).then(function (response) {
$scope.deal.invites = {
list: response.Data.Deal_invites,
paginator: {
count: response.Data.Paginator.total_deal_invites,
currentPage: response.Data.Paginator.current_page,
}
};
});
};
$scope.$watch('InviteFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue)
$scope.getOtherInvites();
}, 700));
$scope.getOtherInvites();
}])
//Deal Bid controller
.controller('DealBidsController', ['$scope', '$rootScope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', function ($scope, $rootScope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q) {
$scope.bidActiveTab = 'All';
$timeout(function () {
switch ($scope.moduleName) {
case 'Deal':
$scope.getDeal(function () {
$scope.ModuleKey = $scope.deal.DealDetail ? $scope.deal.DealDetail.DealID : $scope.FormData.DealID;
$scope.moduleEntity = $scope.deal;
$scope.ModuleEntityID = $scope.deal.DealUID;
$scope.getDealSnapshot();
});
break;
case 'Deal Pool':
$scope.ModuleKey = $scope.dealPool.DealPoolID;
$scope.$parent.$parent.moduleEntity = $scope.dealPool;
$scope.$parent.$parent.ModuleEntityID = $scope.dealPool.PoolUID;
break;
}
$scope.getBids();
}, 800);
$scope.getBids = function (Status) {
if (!_.isUndefined($state.params.PoolUID)) {
// $scope.ModuleEntityID = $state.params.PoolUID;
$scope.ModuleEntityID = $scope.dealPool.DealPoolID;
}
else {
$scope.ModuleEntityID = $state.params.DealUID;
}
appInfo.getServerData({
"GetDealBidList": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Module": $scope.moduleName,
"ModuleEntityID": $scope.ModuleEntityID,
"PageNo": ($scope.moduleEntity && $scope.moduleEntity.bids) ? $scope.moduleEntity.bids.paginator.currentPage : 1,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"Status": Status
}
}).then(function (response) {
if (response.ResponseCode == 200) {
if ($scope.moduleName == 'Deal Pool') {
if ($state.params.DealTabFlag == 'offers') {
$scope.moduleEntity = $scope.dealPool;
}
$scope.moduleEntity.bids = {
list: response.Data.Data,
paginator: {
count: response.Data.Paginator.total_records,
currentPage: response.Data.Paginator.current_page,
}
};
}
else {
$scope.moduleEntity.bids = {
list: response.Data.Bids,
paginator: {
count: response.Data.Paginator.total_bids,
currentPage: response.Data.Paginator.current_page,
}
};
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.acceptBid = function (status) {
var bidData = this.bid;
$rootScope.ngConfirm("Are you sure you want to " + status + " this offer ?", function () {
var reqData = {
"AcceptBid": {
"AccessGrantedToID": bidData.UserID,
"Status": status,
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ModuleEntityID": bidData.DealID,
}
};
if (!_.isUndefined(bidData.DealID) && bidData.DealID) {
reqData.AcceptBid.ModuleName = 'Deal';
}
else {
reqData.AcceptBid.ModuleEntityID = $scope.dealPool.DealPoolID;
reqData.AcceptBid.ModuleName = 'Deal Pool';
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
if ($scope.moduleName == 'Deal Pool') {
$scope.getPoolDetails();
$scope.getPoolDeals();
}
else {
$scope.getBids();
// $scope.getDealSnapshot();
}
}
});
});
}
$scope.changeBidStatus = function (status) {
var bidData = this.bid;
$rootScope.ngConfirm("Are you sure you want to " + status + " this offer ?", function () {
var reqData = {
"ChangeBidStatus": {
"BidID": bidData.BidID,
"StatusID": status == 'Archive' ? '53' : '54',
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"DealID": bidData.DealID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.getBids();
}
});
});
}
}])
// Manage Template
.controller('manageTemplate', ['$rootScope', '$scope', 'appInfo', '$location', 'ngDialog', '$timeout', 'Storage', function ($rootScope, $scope, appInfo, $location, ngDialog, $timeout, Storage) {
$scope.refreshPraposalTemplateList = function () {
$scope.Page.trackLoading('template-list');
if (!$scope.requestUnderProcess) {
var reqData = {
"GetPraposalTemplateList": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF
}
};
if ($scope.syndicationDeskFilter) {
reqData.GetPraposalTemplateList.Filter = {
praposalTemplateFilter_Name: $scope.praposalTemplateFilter.Name
};
}
$scope.Page.trackLoading('template-list');
$scope.praposalTemplates = null;
$scope.totalTemplates = 0;
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('template-list');
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.praposalTemplates = response.Data;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalTemplates = response.Data.Paginator.total_templates;
pagingData.numPerPage = 10;
$scope.showingApplicationtext = appInfo.getPaginationData(pagingData);
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
var initFilters = function () {
$scope.refreshPraposalTemplateList();
};
if ($rootScope.CompanyPreferences)
initFilters();
else
$rootScope.$on('company-loaded', initFilters);
$scope.$watch('syndicationDeskFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue)
$scope.refreshPraposalTemplateList();
}, 700));
$scope.closePopup = function () {
ngDialog.close();
}
}])
.controller('missingController', ['$scope', 'Storage', '$state', function ($scope, Storage, $state) {
if (Storage.getItem('emulate') && !$scope.SignIn)
$state.go('signin');
}])
// User Profile Controller
.controller('userProfileCtrl', ['$rootScope', '$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$q', function ($rootScope, $scope, appInfo, ngDialog, $timeout, Storage, $q) {
/**/
$scope.actualProfileImage = '';
$scope.croppedProfileImage = '';
/**/
$scope.getUserProfile = function () {
var reqData = {
"GetUserProfile": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
$scope.Page.trackLoading('user-profile');
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('user-profile');
if (response.ResponseCode == 200) {
if (response.Data) {
$scope.userData = response.Data;
$scope.userData.ProfilePicture = IMAGE_SERVER_PATH + $scope.userData.ProfilePicture;
}
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.uploadProfilePicture = function () {
$scope.isAttachementUploading = true;
var reqData = {
"UploadFile": {
"ModuleName": 'ProfilePicture',
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ImageString": $scope.croppedProfileImage.replace(/^data:image\/[a-z]+;base64,/, ""),
"UserID": $scope.userData.UserID,
}
};
appInfo.CallUploadFilesApi(reqData, function (response) {
$rootScope.uploading = false;
$scope.isAttachementUploading = false;
if (response.ResponseCode == 200) {
$scope.userData.ProfilePicture = IMAGE_SERVER_PATH + response.Data.MediaURL;
$rootScope.SignIn.UserDetails.ProfilePicture = response.Data.MediaURL;
Storage.setItem('SignIn', $rootScope.SignIn);
ngDialog.close();
} else {
$scope.showFlashMessage('error', response.Message);
}
},
function (response) {
$rootScope.uploading = false;
$scope.isAttachementUploading = false;
$scope.showFlashMessage("error", file.name + " Upload Failed.");
},
function (evt) {
$scope.uploadProgress = evt.uploadPercentage ? evt.uploadPercentage : 100;
}, false);
}
$scope.getUserProfile();
$scope.showCropperPopUp = function (imageFile) {
if (!imageFile)
return FALSE;
var reader = new FileReader();
reader.onload = function (evt) {
$scope.$apply(function ($scope) {
$scope.actualProfileImage = evt.target.result;
});
};
reader.readAsDataURL(imageFile);
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-crop-popup.html?v=' + RELEASE_VERSION,
className: 'ng-popup ngdialog-theme-default',
scope: $scope,
closeByEscape: false,
closeByDocument: false,
showClose: false
});
}
$scope.editUser = function (editContact) {
if (checkstatus('frmUserDetails', $scope)) {
var reqData = {
"EditCompanyUser": {
"1": {
"FirstName": $scope.userData.FirstName,
"LastName": $scope.userData.LastName,
"UserID": $scope.userData.UserID,
"MobileNumber": $scope.userData.MobileNumber,
"UserTypeID": $scope.userData.RoleID,
"Extension": $scope.userData.Extension ? $scope.userData.Extension : null
},
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyID": $rootScope.CompanyPreferences.CompanyID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
}
$scope.targetColor1 = $scope.CompanyPreferences.BetaSiteThemeSettings.color1;
$scope.targetColor2 = $scope.CompanyPreferences.BetaSiteThemeSettings.color2;
$scope.changeThemeNew = function (targetColor1, targetColor2, tempUpdate) {
var color1 = $scope.targetColor1;
var color2 = $scope.targetColor2;
if (!tempUpdate) {
var reqData = {
"SetCompanyPreferences": {
"UIsettings": { "color1": color1, "color2": color2, "color3": color1, "color4": color1, "color5": color1 },
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.showFlashMessage('success', response.Message);
$rootScope.CompanyPreferences.BetaSiteThemeSettings = { "color1": color1, "color2": color2, "color3": color1, "color4": color1, "color5": color1 };
Storage.setItem('CompanyPreferences', $rootScope.CompanyPreferences);
$rootScope.updateUI();
} else {
$rootScope.showFlashMessage('error', response.Message);
}
});
}
else {
$rootScope.updateUI();
}
};
}])
// Setting Controller
.controller('PermittedActionsController', ['$rootScope', '$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$state', function ($rootScope, $scope, appInfo, ngDialog, $timeout, Storage, $state) {
$scope.companysUserData = Storage.getItem('companysUserData');
appInfo.getCompanyPermissions(function (response) {
$scope.UserPermissionModule = response.Data.permissions;
}, {
"CompanyID": $scope.CompanyPreferences.CompanyID,
"UserID": $scope.companysUserData.UserID,
"OtherUser": true
});
$scope.saveCompanyUserPermissions = function () {
var reqData = {
"SaveCompanyPermissions": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"PermittedActions": $scope.UserPermissionModule,
"CompanyID": $scope.CompanyPreferences.CompanyID,
"RoleID": $scope.companysUserData.RoleID,
"UserID": $scope.companysUserData.UserID,
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.showFlashMessage('success', response.Message);
$state.go('company-user');
} else {
$rootScope.showFlashMessage('error', response.Message);
}
});
}
$scope.selectAll = function () {
if (this.module.All) {
for (var i in this.module.PermittedActions) {
this.module.PermittedActions[i] = 1;
}
$scope.isChecked = true;
}
else {
for (var i in this.module.PermittedActions) {
this.module.PermittedActions[i] = 0;
}
$scope.isChecked = false;
}
}
$scope.checkSelectAll = function () {
for (var i in this.module.PermittedActions) {
if (this.module.PermittedActions[i] == 0) {
this.module.All = 0;
break;
return;
}
this.module.All = 1;
}
}
}])
// Notification Controller
.controller('NotificationController', ['$rootScope', '$timeout', '$scope', 'appInfo', '$location', 'ngDialog', 'Storage', '$q', function ($rootScope, $timeout, $scope, appInfo, $location, ngDialog, Storage, $q) {
$scope.LastRetrivedNotificationID = null;
$rootScope.chat = { rooms: {}, activeRoom: false };
$rootScope.unreadNotifications = [];
$scope.unreadMsgNotifications = [];
$scope.unreadMsgCount = 0;
$scope.unreadNotificationCount = 0;
$rootScope.chatWindows = {};
$rootScope.chatRooms = [];
$rootScope.selectedChatWindow = null;
$rootScope.fetchAppNotification = null;
$scope.markNotificationsRead = function (notificationsType) {
if ($scope.LastRetrivedNotificationID) {
appInfo.getSocketData({
'markNotifications': {
"notificationsType": notificationsType,
"lastRetrivedNotificationID": $scope.LastRetrivedNotificationID
}
}, function () {
$scope.$apply(function () {
if (notificationsType == 'message')
$scope.unreadMsgCount = 0;
else
$scope.unreadNotificationCount = 0;
});
});
}
}
$scope.viewNotificationDetail = function () {
var notification = this.Notification;
var viewNotification = function () {
if (notification.Parameters['##APPLICATIONNUMBER##']) {
var ApplicationNumber = notification.Parameters['##APPLICATIONNUMBER##'];
var subSection = '';
switch (parseInt(notification.EventID)) {
case 12:
subSection = 'documents';
break;
default:
subSection = 'view';
}
// console.log(this.Notification);
$location.path('/app-details/' + subSection + '/' + ApplicationNumber);
}
else if (notification.Parameters['##DEAL_LINK##']) {
switch (parseInt(notification.EventID)) {
case 49:
$location.path('/deal/offers/' + notification.Parameters['dealUID']);
break;
case 45:
$location.path('/deal/requests/' + notification.Parameters['dealUID']);
break;
default:
window.location = notification.Parameters['##DEAL_LINK##'];
}
}
else if (notification.Parameters['##MODULE_ENTITY_REQUEST_LINK##']) {
switch (parseInt(notification.EventID)) {
case 49:
$location.path('/deal/' + notification.Parameters['dealUID']);
break;
case 45:
$location.path('/deal_pool/requests/' + notification.Parameters['dealUID']);
break;
default:
window.location = notification.Parameters['##MODULE_ENTITY_REQUEST_LINK##'];
}
} else if (notification.Parameters['##ACT_LINK##']) {
window.location = notification.Parameters['##ACT_LINK##'];
} else if (notification.Parameters['##MESSAGELINK##']) {
$location.path('/inbox/' + notification.Parameters.chatRoomID);
} else if (notification.Parameters['##FILE_URL##']) {
window.location.assign(notification.Parameters['##FILE_URL##']);
}
else if (notification.Parameters["##MODULE_ENTITY_LINK##"]) {
window.location.assign(notification.Parameters['##MODULE_ENTITY_LINK##']);
}
}
if (!$rootScope.$$pharse)
$timeout(viewNotification, 100);
else
viewNotification();
}
$scope.chat.changeRoomSubscription = function (chatRoomID, callback) {
appInfo.getSocketData({ changeRoomSubscription: { ChatRoomID: chatRoomID } }, function () {
$scope.showFlashMessage('success', 'Subscription Updated.');
});
}
$scope.chat.getMessages = function (chatRoomID, callback) {
appInfo.getServerData({ "getChatMessages": { 'chatRoomID': chatRoomID, 'LoginSessionKey': $scope.SignIn.LoginSessionKey, 'ClientTZDIFF': $scope.uaInfo.ClientTZDIFF } }).then(function (response) {
if (response.ResponseCode == 200) {
if (response.Data.length) {
$scope.chat.rooms[chatRoomID].messages = $scope.chat.rooms[chatRoomID].messages.concat(response.Data);
$scope.chat.scrollToEnd(chatRoomID);
$scope.chat.activeRoom = $scope.chat.rooms[chatRoomID];
}
var reqData = {
"checkOnlineUsers": {
"chatRoomID": chatRoomID
}
};
appInfo.getSocketData(reqData, function (r) {
$scope.$apply(function () {
$scope.chat.rooms[chatRoomID].onlineMembers = r.checkOnlineUsers;
});
});
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading("openChatRoom");
}, function () {
$scope.Page.untrackLoading("openChatRoom");
$scope.showFlashMessage('error', 'Unable to connect with messaging service.');
});
}
$scope.chat.openChatRoom = function (roomData, callback) {
if (roomData.chatRoomID) {
if ($scope.chat.rooms[roomData.chatRoomID]) {
$scope.chat.activeRoom = $scope.chat.rooms[roomData.chatRoomID];
if (!$scope.chat.activeRoom.messages.length)
$scope.chat.getMessages($scope.chat.activeRoom.chatRoomID);
return false;
} else if (!roomData.LoginSessionKey) {
roomData.LoginSessionKey = $scope.SignIn.LoginSessionKey;
}
}
$scope.Page.trackLoading("openChatRoom");
appInfo.getServerData({ "openChatRoom": roomData }).then(function (response) {
if (response.ResponseCode == 200) {
$scope.chat.rooms[response.Data.chatRoomID] = response.Data;
$scope.chat.getMessages(response.Data.chatRoomID);
} else {
$scope.showFlashMessage('error', response.Message);
$scope.Page.untrackLoading("openChatRoom");
}
}, function () {
$scope.Page.untrackLoading("openChatRoom");
$scope.showFlashMessage('error', 'Unable to connect with messaging service.');
});
}
$scope.chat.closeChatRoom = function (chatRoomID) {
if ($scope.chat.activeRoom && $scope.chat.activeRoom.chatRoomID == chatRoomID)
$scope.chat.activeRoom = false;
delete $scope.chat.rooms[chatRoomID];
}
$scope.chat.sendMessage = function (e, chatRoom, callback) {
$scope.chat.activeRoom = chatRoom;
if (chatRoom.message) {
if (e.type == 'click' || e.keyCode == 13) {
var reqData = {
"sendChatMessage": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"Message": chatRoom.message,
"ChatRoomID": chatRoom.chatRoomID
}
};
appInfo.getSocketData(reqData, function () {
$scope.$apply(function () {
chatRoom.message = "";
});
});
/*appInfo.getServerData(reqData).then(function(response){
if(response.ResponseCode==200){
// scrollToLatestMessage($rootScope.selectedChatWindow.roomIndex);
appInfo.getSocketData(JSON.stringify(reqData.sendChatMessage));
clearTimeout($scope.nextCall);
$scope.refreshNotificationList();
if(callback)
callback();
} else {
$rootScope.showFlashMessage('error',response.Message);
}
});*/
}
}
}
$scope.chat.scrollToEnd = function (chatRoomID) {
setTimeout(function () {
switch ($scope.currentName) {
case "inbox":
case "entityMessage":
$("#inboxScrollArea").animate({
scrollTop: $("#inboxScrollArea .media").last().offset().top
});
break;
default:
$("#chatRoom" + chatRoomID + " .chat-body").animate({
scrollTop: $("#chatRoom" + chatRoomID + " .chat-post:last-child").offset().top
});
}
}, 200);
}
$scope.chat.uploadDocument = function (chatRoomID, files, errFiles) {
var promises = [];
if ((files.length > 0)) {
$scope.isAttachementUploading = true;
var failedFiles = 0;
var chatFileCurrentIndex = 0;
angular.forEach(files, function (fileToUpload, key) {
(function (file, fileIndex) {
var reqData = {
"UploadFile": {
"ModuleName": 'ChatDocuments',
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"chatRoomID": chatRoomID,
"File": file
}
};
$scope.documentBeingUploaded = file.name;
var promise = appInfo.CallUploadFilesApi(reqData,
function (response) {
if (response.ResponseCode != 200) {
$scope.showFlashMessage('error', response.Message);
failedFiles++;
}
},
function (response) {
$scope.showFlashMessage('error', 'Failed to upload ' + file.name + '.');
failedFiles++;
},
function (evt) {
$scope.uploadProgress = evt.uploadProgress
}
);
promises.push(promise);
})(fileToUpload, chatFileCurrentIndex);
chatFileCurrentIndex++;
});
$q.all(promises).then(function (data) {
$scope.isAttachementUploading = false;
// if(!failedFiles)
// $scope.showFlashMessage('success', "Files uploaded successfully.");
});
} else {
$rootScope.uploading = false;
var msg = '';
angular.forEach(errFiles, function (errFile, key) {
msg += '\n' + errFile.$errorMessages;
promises.push(makeResolvedPromise(msg));
});
$q.all(promises).then(function (data) {
$scope.showFlashMessage('success', msg);
});
}
};
$scope.chat.renameRoom = function (chatRoomID, roomTitle) {
appInfo.getSocketData({
"renameChatRoom": {
'LoginSessionKey': $scope.SignIn.LoginSessionKey,
'chatRoomID': chatRoomID,
'roomTitle': roomTitle
}
}, function () {
$scope.chat.rooms[response.renameChatRoom.chatRoomID] = response.renameChatRoom.roomTitle;
});
}
$rootScope.downloadDocument = function (selectedDocument) {
if (selectedDocument)
$rootScope.selectedApplicationDocument = selectedDocument;
var form = angular.element('#frmDownload').attr('action', appInfo.appDocumentDownloadUrl);
form.find('[name="FileName"]').val($scope.selectedApplicationDocument.ImageName);
form.find('[name="DownloadURL"]').val($scope.selectedApplicationDocument.ImageUrl);
form.submit();
}
$scope.chat.viewDownloadDoc = function (Attachment) {
$rootScope.selectedApplicationDocument = Attachment;
if (Attachment.CanView) {
$scope.selectedApplicationDocument.DocPath = IMAGE_SERVER_PATH + $scope.selectedApplicationDocument.ImageUrl;
$scope.selectedApplicationDocument.loadViewer = true;
openNav('html5Viewer');
} else {
$scope.downloadDocument();
}
}
$scope.$on('$stateChangeSuccess', function (event, current) {
if (current.name != 'inbox' && $scope.chat.inboxLoaded) {
$scope.chat.rooms = {};
$scope.chat.activeRoom = false;
delete $scope.chat.representatives;
delete $scope.chat.onlineUsers;
}
});
$scope.IsVisibleIcon = false;
$scope.minimizeIcon = function () {
$scope.IsVisibleIcon = $scope.IsVisibleIcon ? false : true;
}
var initSockets = function () {
appInfo.getSocketData({
'getNotifications': {
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
}, function (r) {
r = r.getNotifications;
$scope.$apply(function () {
var tracker = null;
for (var updateType in r) {
switch (updateType) {
case 'onAssociatedEntityUpdated':
$scope.unreadNotificationCount += r.onAssociatedEntityUpdated.length;
$rootScope.unreadNotifications = $rootScope.unreadNotifications.concat(r.onAssociatedEntityUpdated);
if ($rootScope.unreadNotifications.length > 20)
$rootScope.unreadNotifications.splice(0, $rootScope.unreadNotifications.length - 10);
$rootScope.unreadNotifications = $rootScope.unreadNotifications.reverse();
break;
case 'offlineMessages':
$scope.unreadMsgCount += r.offlineMessages.length;
$scope.unreadMsgNotifications = $scope.unreadMsgNotifications.concat(r.offlineMessages);
if ($scope.unreadMsgNotifications.length > 20)
$scope.unreadMsgNotifications.splice(0, $scope.unreadMsgNotifications.length - 10);
break;
case 'dealUpdateReceived':
for (var i in r.dealUpdateReceived) {
$scope.showToasterMessage('info', r.dealUpdateReceived[i].Title, $scope.viewNotificationDetail, r.dealUpdateReceived[i]);
}
$timeout(function () {
$scope.markNotificationsRead('dealUpdateReceived');
}, 200);
break;
case 'downloadReady':
for (var i in r.downloadReady) {
$scope.showToasterMessage('info', r.downloadReady[i].Title, $scope.viewNotificationDetail, r.downloadReady[i]);
tracker = $scope.Page.zipBeingPrepared.indexOf(r.downloadReady[i].Parameters['##FILE##']);
if (tracker > -1) {
$scope.Page.zipBeingPrepared.splice(tracker, 1);
}
}
$timeout(function () {
if ($scope.Page.zipDialog && ngDialog.isOpen($scope.Page.zipDialog.id))
$scope.Page.zipDialog.close();
$scope.markNotificationsRead('downloadReady');
}, 200);
break;
case 'LastRetrivedNotificationID':
$scope.LastRetrivedNotificationID = r.LastRetrivedNotificationID;
}
}
});
}, true);
appInfo.getSocketData({
'getChatRoomUpdates': {
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
}, function (r) {
r = r.getChatRoomUpdates;
$scope.$apply(function () {
switch (r.updateType) {
case 'newChatMessage':
var m = r.message;
if ($scope.chat.rooms[m.chatRoomID]) {
$scope.chat.rooms[m.chatRoomID].messages.push(m);
$scope.chat.scrollToEnd(m.chatRoomID);
} else {
$scope.chat.openChatRoom({ chatRoomID: m.chatRoomID, LoginSessionKey: $scope.SignIn.LoginSessionKey }, function () {
$scope.chat.rooms[m.chatRoomID].messages.push(m);
$scope.chat.scrollToEnd(m.chatRoomID);
});
}
break;
case 'chatRoomConnectionsUpdated':
if ($scope.chat.rooms[r.chatRoomID])
$scope.chat.rooms[r.chatRoomID].onlineMembers = r.onlineUsers;
if (r.expiredConnection && $scope.chat.onlineUser && (expiredIndex = $scope.chat.onlineUsers.indexOf(r.expiredConnection)) > -1) {
$scope.chat.onlineUsers.splice(expiredIndex, 1);
}
if (r.newConnection && $scope.chat.representatives && (newConnection = $scope.chat.representatives.indexOf(r.newConnection)) > -1) {
$scope.chat.onlineUsers.push(r.newConnection);
}
break;
}
});
}, true);
}
if ($scope.CompanyPreferences)
initSockets();
else
$rootScope.$on('company-loaded', initSockets);
}])
// Inbox Controller
.controller('InboxController', ['$timeout', '$scope', 'appInfo', '$location', 'ngDialog', 'Storage', '$q', '$stateParams', function ($timeout, $scope, appInfo, $location, ngDialog, Storage, $q, $stateParams) {
$scope.chatRoomTitle = '';
$scope.keys = [];
$scope.Page.Title = 'Inbox - ' + $scope.CompanyPreferences.CompanyName;
$scope.getChatRooms = function () {
var reqData = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"RoomsLoaded": $scope.chat.rooms.length,
"chatRoomTitle": $scope.chatRoomTitle
}
if ($stateParams.entityType) {
$scope.filteredEntity = $stateParams.entityType + " : " + $stateParams.entityID;
reqData.filters = {
entityType: $stateParams.entityType,
entityID: $stateParams.entityID,
}
}
appInfo.getChatRooms(reqData, function (response) {
if (response.ResponseCode == 200) {
$scope.chat.representatives = [];
$scope.chat.inboxLoaded = true;
for (var i in response.Data) {
$scope.keys.push(response.Data[i].chatRoomID);
$scope.chat.rooms[response.Data[i].chatRoomID] = response.Data[i];
if (Array.isArray($scope.chat.representatives) && $scope.chat.representatives.indexOf(response.Data[i].representative.UserID) == -1)
$scope.chat.representatives.push(response.Data[i].representative.UserID);
if ($stateParams.ChatRoomID && response.Data[i].chatRoomID == $stateParams.ChatRoomID) {
$scope.chat.openChatRoom($scope.chat.rooms[response.Data[i].chatRoomID]);
}
}
appInfo.getSocketData({ 'checkOnlineUsers': $scope.chat.representatives }, function (r) {
$scope.chat.onlineUsers = r.checkOnlineUsers;
});
}
$scope.Page.untrackLoading("activeChatRooms");
});
}
$scope.$watch('chatRoomTitle', _.debounce(function () {
$scope.chat.rooms = {};
$scope.getChatRooms();
}, 500));
}])
.controller('CustomURLController', ['$rootScope', '$timeout', '$scope', 'appInfo', '$location', 'ngDialog', 'Storage', '$q', function ($rootScope, $timeout, $scope, appInfo, $location, ngDialog, Storage, $q) {
$scope.customApplicationFlowURL = null;
$scope.Page.Title = 'Custom Url - ' + $rootScope.CompanyPreferences.CompanyName;
$scope.createCustomUrl = function (URL) {
$scope.customApplicationFlowURL = $rootScope.siteURL + 'custom-quote/' + URL;
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/custom_application_flow_url.html',
className: 'ng-popup ngdialog-theme-default ',
scope: $scope
});
}
}])
.controller('SetConfigurationController', ['$rootScope', '$timeout', '$scope', 'appInfo', '$location', 'ngDialog', 'Storage', '$q', '$state', function ($rootScope, $timeout, $scope, appInfo, $location, ngDialog, Storage, $q, $state) {
$scope.targetColor1 = $scope.CompanyPreferences.BetaSiteThemeSettings.color1;
$scope.targetColor2 = $scope.CompanyPreferences.BetaSiteThemeSettings.color2;
$scope.Page.Title = 'Set Configuration - ' + $rootScope.CompanyPreferences.CompanyName;
$scope.saveCompanyData = function (targetColor1, targetColor2, tempUpdate) {
var color1 = $scope.targetColor1;
var color2 = $scope.targetColor2;
if ($scope.CompanyPreferences.RestrictIndustryDefault) {
var DefaultIndustrySelected = FALSE;
for (var i in $scope.Config.industryData) {
if ($scope.Config.industryData[i].IndustryTypeID == $scope.CompanyPreferences.DefaultIndustrySelected) {
DefaultIndustrySelected = TRUE;
}
}
for (var i in $scope.industries) {
if ($scope.industries[i].IndustryTypeID == $scope.CompanyPreferences.DefaultIndustrySelected) {
$scope.Config.industryData.push($scope.industries[i]);
}
}
if (!DefaultIndustrySelected) {
$rootScope.showFlashMessage('error', 'You connot remove default industry.');
return;
}
}
if (!tempUpdate && checkstatus('frmCompanyDetails', $scope)) {
var reqData = {
"SetCompanyPreferences": {
"UIsettings": { "color1": color1, "color2": color2, "color3": color1, "color4": color1, "color5": color1 },
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"IndustryTypes": $scope.Config.industryData
}
};
$rootScope.Page.trackLoading('save-companydata');
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.showFlashMessage('success', response.Message);
$rootScope.CompanyPreferences.BetaSiteThemeSettings = { "color1": color1, "color2": color2, "color3": color1, "color4": color1, "color5": color1 };
Storage.setItem('CompanyPreferences', $rootScope.CompanyPreferences);
setTimeout(function () {
$state.go('signout');
setTimeout(function () { location.reload() }, 2000);
}, 200);
$rootScope.updateUI();
} else {
$rootScope.showFlashMessage('error', response.Message);
}
$rootScope.Page.untrackLoading('save-companydata');
});
}
else {
$rootScope.updateUI();
}
};
$scope.getAllIndustries = function () {
var reqDataIndustry = {
"GetIndustryTypesList": {
"allIndustries": true
}
};
$rootScope.Page.trackLoading('industries-list');
appInfo.getServerData(reqDataIndustry).then(function (response) {
if (response.ResponseCode == 200) {
$scope.industries = response.Data.Industries;
$scope.Config.industryData = [];
for (var i = 0; i < $scope.industries.length; i++) {
$scope.configurationIndustryId = $scope.industries[i].IndustryTypeID;
for (var j = 0; j < $rootScope.CompanyPreferences.IndustryTypes.length; j++) {
$scope.companyPrefrenceId = $rootScope.CompanyPreferences.IndustryTypes[j];
if ($scope.configurationIndustryId == $scope.companyPrefrenceId) {
$scope.Config.industryData.push($scope.industries[i]);
}
}
}
} else
$rootScope.showFlashMessage('error', response.Message);
$rootScope.Page.untrackLoading('industries-list');
});
}
// $scope.saveCompanyData=function(){
// if(checkstatus('frmCompanyDetails',$scope)){
// var reqDataIndustry={
// "SetCompanyPreferences": {
// "LoginSessionKey":$scope.SignIn.LoginSessionKey,
// }
// };
// $rootScope.Page.trackLoading('save-companydata');
// appInfo.getServerData(reqDataIndustry).then(function(response){
// if(response.ResponseCode==200){
// setTimeout(function(){
// $state.go('signout');
// setTimeout(function(){location.reload()},2000);
// },200);
// } else
// $rootScope.showFlashMessage('error',response.Message);
// $rootScope.Page.untrackLoading('save-companydata');
// });
// }
// }
$scope.Config = {};
$scope.getAllIndustries();
}])
//Deal Document Controller
.controller('CompanyDocumentController', ['$scope', '$rootScope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', function ($scope, $rootScope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q) {
$rootScope.SeeRecordData = { maxDisplayPages: '10' };
$scope.Page.documents = {
"ModuleEntityID": $scope.CompanyPreferences.CompanyID,
"ModuleName": 'CompanyDocument',
"selectedFiles": [],
"DocumentsData": [],
"selectedFileIds": [],
"FolderName": [],
"checkedFile": false,
"zipName": $stateParams.ApplicationNumber,
"filter": { "currentPage": 1 }
}
$scope.refreshFileList();
$scope.$index = 0;
$scope.file_type = "";
$scope.validateUpload = function (f) {
if ($rootScope.uploading) {
$scope.showFlashMessage('error', "Please wait,Another upload in progress.");
return false;
}
return true;
}
$scope.togglePublishStatus = function (isPrivateSharedOnly, dealID) {
// $scope.selectedDeal = this.deal;
var reqData = {
"ToggleDealPublishPrivacy": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealID": this.deal.DealID ? this.deal.DealID : dealID,
"IsPrivateSharedOnly": (isPrivateSharedOnly === false) ? 1 : 0,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('syndicationDesk-list');
if (response.ResponseCode == 200) {
if ($state.current.name == "syndication-desk")
$scope.refreshSyndicationDeskList();
$scope.showFlashMessage('success', response.Message);
}
}, function () {
// $scope.selectedDeal.IsPrivateSharedOnly=!$scope.selectedDeal.IsPrivateSharedOnly
$scope.showFlashMessage('error', "Error updating Deal Privacy");
});
}
}])
//Profile Common admin Documents Controller
.controller('CommonDocumentController', ['$scope', '$rootScope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', function ($scope, $rootScope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q) {
$rootScope.SeeRecordData = { maxDisplayPages: '10' };
$scope.setDocumentType = function (fileItem) {
var reqData = {
"setAsNda": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"MediaID": fileItem.MediaID,
"MediaURL": fileItem.ImageUrl
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.showFlashMessage('success', response.Message);
$rootScope.addfolderVisible = false;
$rootScope.refreshFileList();
} else {
$rootScope.showFlashMessage('error', response.Message);
}
});
}
$scope.Page.documents = {
"ModuleEntityID": $scope.CompanyPreferences.CompanyID,
"ModuleName": 'CommonDocuments',
"selectedFiles": [],
"DocumentsData": [],
"selectedFileIds": [],
"FolderName": [],
"blockSelect": true,
"blockDelete": true,
"blockEdit": true,
"filter": { "currentPage": 1 },
"additionalFields": [
{ "key": "DocumentType", "label": "Document Type" }
],
"selectedFileActions": [
{ "icon": "icon-tooltip-edit asp-row-icon", "label": "Set As NDA", "perform": $scope.setDocumentType }
]
}
$scope.refreshFileList();
$scope.$index = 0;
}])
//Deal Pool List Controller
.controller('DealPoolsController', ['$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$stateParams', '$state', '$q', function ($scope, appInfo, ngDialog, $timeout, Storage, $stateParams, $state, $q) {
$scope.getDrafts = function () {
var reqData = {
"ListDealPoolDrafts": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.poolDrafts = response.Data.Deal_pools;
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.discardDealPoolDraft = function () {
var reqData = {
"DiscardDealDraft": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"DraftID": this.draft.DraftID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.getDrafts();
} else {
$scope.showFlashMessage('error', response.Message);
}
});
}
$scope.updateDealPoolsTab = function (dealTabFlag) {
$scope.dealTabFlag = dealTabFlag;
$scope.getDealPoolsListFilter.dealStatus = { 'StatusID': dealTabFlag };
switch (dealTabFlag) {
case 'drafts':
$scope.getDrafts();
break;
case 'All':
$scope.getDealPoolsListFilter.dealStatus = "";
default:
$scope.getDealPoolsList();
}
}
$scope.getDealPoolsList = function () {
var reqData = {
"GetDealPoolsList": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"PageNo": $scope.currentPage,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
if ($scope.getDealPoolsListFilter) {
reqData.GetDealPoolsList.Filters = {
StartDate: $scope.getDealPoolsListFilter.StartDate,
EndDate: $scope.getDealPoolsListFilter.EndDate,
Name: $scope.getDealPoolsListFilter.Name,
Status: ($scope.getDealPoolsListFilter.dealStatus) ? $scope.getDealPoolsListFilter.dealStatus.StatusID : null
};
}
$scope.Page.trackLoading('deal-pool-list');
$scope.dealPools = null;
$scope.totalDealPools = 0;
appInfo.getServerData(reqData).then(function (response) {
$scope.Page.untrackLoading('deal-pool-list');
if (response.ResponseCode == 200) {
if (response.Data) {
pagingData = [];
$scope.dealPools = response.Data.Deal_pools;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalDeals = response.Data.Paginator.total_deal_pools;
pagingData.numPerPage = 10;
$scope.showingDealtext = appInfo.getPaginationData(pagingData);
if (angular.isNumber($scope.getDealPoolsListFilter.dealStatus ? $scope.getDealPoolsListFilter.dealStatus.StatusID : null)) {
$scope.dealTabFlag = 'All';
}
}
} else {
$scope.showFlashMessage('error', response.Message);
}
}, function () {
$scope.showFlashMessage('error', 'Failed to fetch Deal Pool List.');
$scope.Page.untrackLoading('deal-pool-list');
});
}
$scope.init = function () {
if ($scope.companyPermissions['Deal Pool'].PermittedActions.List) {
$scope.currentPage = 1;
$scope.resetFiltersForDealPool();
appInfo.getStatusList(function () {
$scope.getDealPoolsListFilter.dealStatus = {};
}, true);
$scope.moduleName = 'Deal Pool';
$scope.Page.Title = 'Deal Pool - ' + $scope.CompanyPreferences.CompanyName;
}
}
$scope.resetFiltersForDealPool = function () {
$scope.dealTabFlag = 'All';
$scope.currentPage = 1;
$scope.getDealPoolsListFilter = {};
$scope.getDealPoolsList();
}
$scope.deleteDealPool = function (PoolUID) {
$scope.ngConfirm('Are you sure you want to delete this pool?', function () {
var reqData = {
"DeleteDealPool": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"PoolUID": PoolUID
}
};
appInfo.getServerData(reqData).then(function (response) {
var msgType = "error";
if (response.ResponseCode == 200) {
msgType = "success";
}
$scope.showFlashMessage(msgType, response.Message);
$scope.getDealPoolsList();
});
});
}
appInfo.getCompanyPermissions($scope.init, {});
}])
.controller('DealPoolController', ['$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$state', '$q', '$window', '$filter', function ($scope, appInfo, ngDialog, $timeout, Storage, $state, $q, $window, $filter) {
$scope.noteTab = "DealPool";
$scope.moduleName = 'Deal Pool';
$scope.publishDealDialog = function (dealID) {
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-publishDeal.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
$scope.showSelectVisualOptions = function () {
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-selectVisualOptions.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
$scope.updateDealPoolVisuals = function () {
appInfo.getServerData({
"UpdateDealPoolCache": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"PoolUID": $state.params.PoolUID,
"preference": $scope.dealPool.preference,
}
}).then(function (response) {
if (response.ResponseCode == 200) {
$scope.getPoolDetails($scope.getPoolDeals);
ngDialog.close();
} else
$scope.showFlashMessage('error', response.Message);
});
};
$scope.toggleDealForOutstandingVisual = function () {
appInfo.getServerData({
"ToggleDealForOutstandingVisual": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"PoolUID": $state.params.PoolUID,
"DealUID": this.deal.DealUID,
"UseInOutstangingChart": !this.deal.UseInOutstangingChart,
}
}).then(function (response) {
if (response.ResponseCode == 200) {
$scope.getPoolDetails($scope.getPoolDeals);
} else
$scope.showFlashMessage('error', response.Message);
});
}
$scope.getChatRooms = function () {
var reqData = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"filters": {
entityType: "Deal Pool",
entityID: $state.params.PoolUID,
}
};
appInfo.getChatRooms(reqData, function (response) {
if (response.ResponseCode == 200) {
$scope.chat.representatives = [];
$scope.dealPool.chatRooms = response.Data;
for (var i in response.Data) {
// $scope.keys.push(response.Data[i].chatRoomID);
// $scope.chat.rooms[response.Data[i].chatRoomID]=response.Data[i];
if (Array.isArray($scope.chat.representatives) && $scope.chat.representatives.indexOf(response.Data[i].representative.UserID) == -1)
$scope.chat.representatives.push(response.Data[i].representative.UserID);
}
appInfo.getSocketData({ 'checkOnlineUsers': $scope.chat.representatives }, function (r) {
$scope.chat.onlineUsers = r.checkOnlineUsers;
});
}
$scope.Page.untrackLoading("activeChatRooms");
});
}
$scope.switchDealTab = function (switchDealTabFlag, secondaryTab) {
if (!secondaryTab)
$scope.switchDealTabFlag = switchDealTabFlag;
else
$scope.dealPool.secondaryActiveTab = switchDealTabFlag;
switch (switchDealTabFlag) {
case "snapshotTab":
$timeout(function () {
Highcharts.chart('outstandingDealsChart', $scope.outstandingChart);
Highcharts.chart('paynetDealsChart', $scope.paynetChart);
Highcharts.chart('paymentDealsChart', $scope.paymentChart);
Highcharts.chart('daysOutstandingDealsChart', $scope.daysOutstandingChart);
Highcharts.chart('daysEquipmentCostDealsChart', $scope.equipmentCostChart);
}, 500);
break;
case "viewTab":
break;
case 'connectionTab':
$scope.dealPool.secondaryActiveTab = 'All';
break;
case 'notesTab':
break;
case 'messageTab':
$scope.getChatRooms();
break;
}
};
$scope.pagingData = { currentPage: 1 };
$scope.getPoolDeals = function () {
var reqData = {
"GetDealPoolDeals": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"PoolUID": $state.params.PoolUID,
"PageNo": $scope.pagingData.currentPage
}
};
if ($scope.dealPool && $scope.dealPool.FilterDealsByName) {
reqData.GetDealPoolDeals.filters = { "keyword": $scope.dealPool.FilterDealsByName };
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.dealPool.Deals = response.Data.Deal_pools;
$scope.pagingData.currentPage = response.Data.Paginator.current_page;
$scope.pagingData.totalPage = response.Data.Paginator.total_pages;
$scope.pagingData.totalRecord = $scope.totalDeals = response.Data.Paginator.total_deal_pools;
$scope.pagingData.numPerPage = 10;
$scope.pagingData.recordsInfo = appInfo.getPaginationData($scope.pagingData);
/*var options = {
interpolateNulls:true,
chartArea:{left:0,top:0, width:"100%", height:"88%"},
legend: { position: 'bottom' },
// bar: { groupWidth: "50%" },
colors: ['#990099', '#FF9900', '#E34444', '#40AC42', '#8C0000'],
// vAxis: { gridlines: { count: (7) }, minValue: 0, maxValue: 60 }
};
var dataTable = google.visualization.arrayToDataTable(response.Data);
var chart = new google.visualization.ColumnChart(document.getElementById('getPaymentByDateChart'));
chart.draw(dataTable, options);*/
} else {
$scope.showFlashMessage('error', response.Message);
}
}, function () {
$scope.showFlashMessage('error', 'Failed to fetch Pool Deals.');
});
}
$scope.getPoolDetails = function (callback) {
var reqData = {
"GetDealPool": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"PoolUID": $state.params.PoolUID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.dealPool = response.Data;
if ($scope.dealPool.chartsData) {
/*var data = google.visualization.arrayToDataTable($scope.dealPool.chartsData.outStanding);
var options = {
title: "Top accounts by outstandings receivables.",
width: '100%',
height: $('#outstandingDealsChart').parents(".row").height(),
hAxis: {
format: 'currency'
},
style: {
'color':$scope.CompanyPreferences.BetaSiteThemeSettings.color1
},
// bar: {groupWidth: "95%"},
legend: { position: "none" },
// titleTextStyle :{color:'#666666',fontSize : '16', fontName :'open_sansregular'}
};
var chart = new google.visualization.BarChart(document.getElementById('outstandingDealsChart'));
chart.draw(data, options);
angular.element($window).bind('resize',function(){
chart.draw(data, options);
});*/
$scope.outstandingChart = {
chart: {
type: 'bar',
marginLeft: 50
},
title: {
text: "Top accounts by outstandings receivables."
},
xAxis: {
type: 'category',
title: {
text: null
},
min: 0,
max: 5,
scrollbar: {
enabled: true
},
labels: {
formatter: function () {
if (_.isString(this.value))
return 'D' + this.value.substring(1, 3) + '';
else
return this.value;
},
useHTML: true
}
},
yAxis: {
// min: 0,
// max: 1200,
title: {
text: null
},
labels: {
format: '${value}'
}
},
tooltip: {
// Nice and easy number formatting
valuePrefix: "$",
valueDecimals: 2,
shared: true
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
formatter: function () {
return $filter('currency')(this.y, '$', 2);
}
}
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
series: [{
name: 'Balance',
data: $scope.dealPool.chartsData.outStanding
}]
};
$scope.paynetChart = {
chart: {
type: 'bar',
marginLeft: 50
},
title: {
text: "Top accounts by paynet."
},
xAxis: {
type: 'category',
title: {
text: null
},
min: 0,
max: 5,
scrollbar: {
enabled: true
},
labels: {
formatter: function () {
if (_.isString(this.value))
return 'D' + this.value.substring(1, 3) + '';
else
return this.value;
},
useHTML: true
}
},
yAxis: {
// min: 0,
// max: 1200,
title: {
text: null
},
labels: {
format: '${value}'
}
},
tooltip: {
// Nice and easy number formatting
valuePrefix: "$",
valueDecimals: 2,
shared: true
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
formatter: function () {
return $filter('currency')(this.y, '', 2);
}
}
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
series: [{
name: 'Master Score',
data: $scope.dealPool.chartsData.paynet
}]
};
$scope.paymentChart = {
chart: {
type: 'column'
},
title: {
text: "Top accounts by Payment."
},
xAxis: {
type: 'category',
title: {
text: null
},
scrollbar: {
enabled: true
},
labels: {
formatter: function () {
if (_.isString(this.value))
return 'D' + this.value.substring(1, 3) + '';
else
return this.value;
},
useHTML: true
}
},
yAxis: {
min: 0,
title: {
text: null
}
},
legend: {
enabled: false
},
tooltip: {
valuePrefix: "$",
valueDecimals: 2,
shared: true
},
series: [{
name: 'Payment',
data: $scope.dealPool.chartsData.payment,
}]
}
$scope.daysOutstandingChart = {
chart: {
type: 'bar',
marginLeft: 50
},
title: {
text: "Outstanding receivables 31 + 60Days."
},
xAxis: {
type: 'category',
title: {
text: null
},
min: 0,
max: 5,
scrollbar: {
enabled: true
},
labels: {
formatter: function () {
if (_.isString(this.value))
return 'D' + this.value.substring(1, 3) + '';
else
return this.value;
},
useHTML: true
}
},
yAxis: {
// min: 0,
// max: 1200,
title: {
text: null
},
labels: {
format: '${value}'
}
},
tooltip: {
// Nice and easy number formatting
valuePrefix: "$",
valueDecimals: 2,
shared: true
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
formatter: function () {
return $filter('currency')(this.y, '$', 2);
}
}
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
series: [{
name: 'Balance',
data: $scope.dealPool.chartsData.daysOutstanding
}]
};
$scope.equipmentCostChart = {
chart: {
type: 'pie'
},
title: {
text: 'Equipment Cost'
},
tooltip: {
headerFormat: '{series.name}
',
pointFormat: '{point.name}: {point.y:.2f} $
'
},
"series": [
{
"name": "Balance",
"colorByPoint": true,
"data": $scope.dealPool.chartsData.EquipmentCost
}
]
};
$timeout(function () {
$scope.outstandingChart.chart.height = $('#outstandingDealsChart').parents(".row").height();
Highcharts.chart('outstandingDealsChart', $scope.outstandingChart);
$scope.paynetChart.chart.height = $('#paynetDealsChart').parents(".row").height();
Highcharts.chart('paynetDealsChart', $scope.paynetChart);
$scope.paymentChart.chart.height = $('#paymentDealsChart').parents(".row").height();
Highcharts.chart('paymentDealsChart', $scope.paymentChart);
$scope.daysOutstandingChart.chart.height = $('#daysOutstandingDealsChart').parents(".row").height();
Highcharts.chart('daysOutstandingDealsChart', $scope.daysOutstandingChart);
$scope.equipmentCostChart.chart.height = $('#daysEquipmentCostDealsChart').parents(".row").height();
Highcharts.chart('daysEquipmentCostDealsChart', $scope.equipmentCostChart);
}, 500);
}
if ($state.params.DealTabFlag != 'offers')
$scope.switchDealTabFlag = $state.params.DealTabFlag + 'Tab';
else {
$scope.switchDealTabFlag = $state.params.DealTabFlag;
$scope.switchDealTab('offers');
}
if (_.isFunction(callback))
callback();
} else {
$scope.showFlashMessage('error', response.Message);
}
}, function () {
$scope.showFlashMessage('error', 'Failed to fetch Pool Details.');
});
}
$scope.ChangeStatus = function (statusID, dealID, index, isPrivateSharedOnly) {
var updateData = {
"StatusID": statusID,
"isPrivateSharedOnly": isPrivateSharedOnly
}
$scope.updateDealPool(updateData, function () {
ngDialog.close();
$scope.getPoolDetails($scope.getPoolDeals);
});
}
$scope.updateDealPool = function (updateData, callback) {
var reqData = {
"UpdateDealPool": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"PoolUID": $state.params.PoolUID,
"Data": updateData
}
};
appInfo.getServerData(reqData).then(function (response) {
var msgType = "errormza";
if (response.ResponseCode == 200) {
msgType = "successmza";
if (_.isFunction(callback))
callback();
}
$scope.showFlashMessage(msgType, response.Message);
});
}
$scope.getStateName = function (id) {
var state = _.findWhere($scope.stateData, { StateID: id });
return state ? state.Name : null;
}
$scope.toggleHighlight = function () {
var reqData = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"PoolUID": $scope.dealPool.PoolUID,
"DealUID": this.deal.DealUID,
"IsHighlighted": !this.deal.IsHighlighted
};
appInfo.getServerData({ "ToggleDealHighlightInPool": reqData }).then(function (response) {
var msgType = 'error';
if (response.ResponseCode == 200) {
msgType = 'success';
$scope.getPoolDeals();
delete $scope.dealPool.log;
}
$scope.showFlashMessage(msgType, response.Message);
});
}
$scope.toggleState = function (AllowIndependentSaleFlag, dealID) {
var reqData = {
"ToggleDealAllowIndependentSale": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"DealID": this.deal.DealID ? this.deal.DealID : dealID,
"AllowIndependentSale": AllowIndependentSaleFlag,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.showFlashMessage('success', response.Message);
$scope.getPoolDeals();
}
}, function () {
$scope.showFlashMessage('error', "Error updating Deal ");
});
}
$scope.removeDealFromPool = function () {
var reqData = {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF,
"PoolUID": $scope.dealPool.PoolUID,
"DealUID": this.deal.DealUID,
};
appInfo.getServerData({ "RemoveDealFromPool": reqData }).then(function (response) {
var msgType = 'error';
if (response.ResponseCode == 200) {
msgType = 'success';
$scope.getPoolDeals();
delete $scope.dealPool.log;
}
$scope.showFlashMessage(msgType, response.Message);
});
}
$scope.downloadOriginalDoc = function () {
var form = angular.element('#frmDownload').attr('action', appInfo.appDocumentDownloadUrl);
form.find('[name="FileName"]').val($scope.dealPool.ImageName);
form.find('[name="DownloadURL"]').val($scope.dealPool.ImageUrl);
form.submit();
}
$scope.init = function () {
if ($scope.companyPermissions['Deal Pool'].PermittedActions.View) {
$scope.currentPage = 1;
$scope.getPoolDetails(function () {
$scope.$watch("dealPool.FilterDealsByName", _.debounce($scope.getPoolDeals, 1000));
});
appInfo.getStatusList(null, true);
$scope.notes = { noteCurrentPage: 1, totalPage: null, totalRecord: null };
$scope.Page.Title = 'Deal Pool - ' + $scope.CompanyPreferences.CompanyName;
}
}
appInfo.getCompanyPermissions($scope.init, {});
}])
//Deal Pool Add/Edit/View Controller
.controller('DealPoolDraftController', ['$scope', 'appInfo', 'ngDialog', '$timeout', 'Storage', '$state', '$q', '$location', function ($scope, appInfo, ngDialog, $timeout, Storage, $state, $q, $location) {
$scope.stateName = $state.current.name;
if ($state.current.name == 'edit-select-deal') {
$scope.dealPool = { PoolUID: $state.params.PoolUID };
}
$scope.AddDealToPool = function () {
if (!$scope.poolDraft.SelectedDeals.length) {
$scope.showFlashMessage('error', 'Please add some deal to the pool.');
return;
}
appInfo.getServerData({
"AddDealToPool": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"selectedDeals": $scope.poolDraft.SelectedDeals,
"PoolUID": $scope.dealPool.PoolUID
}
}).then(function (response) {
var msgType = 'error';
if (response.ResponseCode == 200) {
msgType = 'success';
$state.go('pool');
}
$scope.showFlashMessage(msgType, response.Message);
});
}
$scope.getPreparedDraft = function (data) {
$scope.Page.trackLoading('getPreparedDraft');
if (_.isObject(data.Data)) {
return _.delay($scope.getPreparedDraft, 1000, { MediaID: data.Data.Media.MediaID });
}
var reqData = {
"GetDealPoolDraft": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"ClientTZDIFF": $scope.uaInfo.ClientTZDIFF
}
};
if (data.MediaID) {
reqData.GetDealPoolDraft.MediaID = data.MediaID;
} else if ($state.params.DraftID) {
reqData.GetDealPoolDraft.DraftID = $state.params.DraftID;
} else {
return $scope.Page.untrackLoading('getPreparedDraft');
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.poolDraft = response.Data;
$scope.poolDraft.MappingIndexes = [];
$scope.Page.documents.documentBeingUploaded = response.Data.AttachedMedia;
var propertyIndex = -1;
for (var i in $scope.poolDraft.SampleData) {
if (!$scope.poolDraft.SampleData[i].mappedField)
continue;
propertyIndex = _.findIndex($scope.dealPropertiesForMappings, { "field": $scope.poolDraft.SampleData[i].mappedField });
if (propertyIndex > -1)
$scope.saveMapping(propertyIndex, parseInt(i));
}
} else {
$scope.showFlashMessage('error', response.Message);
}
$scope.Page.untrackLoading('getPreparedDraft');
}, function () {
$scope.showFlashMessage('error', 'Failed to fetch deal pool draft.');
$scope.Page.untrackLoading('getPreparedDraft');
});
}
$scope.Page.documents = {
"ModuleEntityID": null,
"ModuleName": 'DealPoolDocuments',
"selectedFiles": [],
"DocumentsData": [],
"selectedFileIds": [],
"FolderName": [],
"blockSelect": true,
"blockDelete": true,
"blockEdit": true,
"filter": { "currentPage": 1 },
"postSingleUploadSuccessCallback": $scope.getPreparedDraft
}
$scope.stepCompleted = [];
switch ($state.current.name) {
case 'upload-pool':
$scope.stepCompleted.push('prepare');
$scope.currentStep = 'uploaded';
break;
case 'select-deal':
case 'edit-select-deal':
$scope.currentStep = 'prepare';
$scope.poolDraft = { SelectedDeals: [] }
break;
}
appInfo.getDealPropertiesForMappings(function () {
$scope.getPreparedDraft({});
});
$scope.saveMapping = function (propertyIndex, fieldIndex) {
if ($scope.poolDraft.SampleData[fieldIndex].mappedIndex) {
var im = $scope.poolDraft.MappingIndexes[$scope.poolDraft.SampleData[fieldIndex].mappedIndex];
if (_.isArray(im)) {
var i = im.indexOf(fieldIndex);
im.splice(i, 1);
}
}
$scope.poolDraft.SampleData[fieldIndex].mappedProperty = $scope.dealPropertiesForMappings[propertyIndex];
if (_.isArray($scope.poolDraft.MappingIndexes[propertyIndex])) {
$scope.poolDraft.MappingIndexes[propertyIndex].push(fieldIndex);
} else {
$scope.poolDraft.MappingIndexes[propertyIndex] = [fieldIndex];
}
$scope.poolDraft.SampleData[fieldIndex].mappedIndex = propertyIndex;
}
$scope.mappingUpdated = function () {
var propertyIndex = _.findIndex($scope.dealPropertiesForMappings, { "field": this.SampleDataField.mappedProperty.field });
$scope.saveMapping(propertyIndex, this.$index);
}
$scope.navigateWizard = function (action) {
switch (action) {
case 'Next':
switch ($scope.currentStep) {
case 'prepare':
if (!$scope.poolDraft.SelectedDeals.length)
$scope.showFlashMessage('error', 'Please add some deal to the pool.');
else {
$scope.stepCompleted.push('prepare');
$scope.stepCompleted.push('uploaded');
$scope.currentStep = 'details';
}
break;
case 'uploaded':
if (!$scope.poolDraft)
$scope.showFlashMessage('error', 'Please complete the upload first.');
else if (!Object.keys($scope.poolDraft.SampleData).length)
$scope.showFlashMessage('error', 'Unable to find data for mapping. Please select different file.');
else {
$scope.stepCompleted.push('uploaded');
$scope.currentStep = 'details';
}
break;
case 'details':
if (checkstatus('frmDealPoolDetails')) {
switch ($state.current.name) {
case 'upload-pool':
appInfo.updateDealPoolDraft({
"DraftID": $scope.poolDraft.DraftID,
"Data": { "Details": $scope.poolDraft.Details }
}, function () {
$scope.stepCompleted.push('details');
$scope.currentStep = 'properties';
});
break;
case 'select-deal':
case 'edit-select-deal':
appInfo.getServerData({
"CreateDealPool": {
"LoginSessionKey": $scope.SignIn.LoginSessionKey,
"selectedDeals": $scope.poolDraft.SelectedDeals,
"Details": $scope.poolDraft.Details
}
}).then(function (response) {
var msgType = 'error';
if (response.ResponseCode == 200) {
msgType = 'success';
$state.go('pool');
}
$scope.showFlashMessage(msgType, response.Message);
});
break;
}
}
break;
case 'properties':
if (checkstatus('frmDealProperties', $scope)) {
appInfo.updateDealPoolDraft({
"DraftID": $scope.poolDraft.DraftID,
"Data": { "MappingIndexes": $scope.poolDraft.MappingIndexes, "SampleData": $scope.poolDraft.SampleData }
}, function () {
$scope.stepCompleted.push('properties');
$scope.stepCompleted.push('confirmed');
$timeout(function () {
$state.go('pool');
}, 5000);
$scope.currentStep = 'confirmed';
});
}
}
break;
case 'Previous':
var i = $scope.stepCompleted.indexOf($scope.currentStep);
$scope.stepCompleted.splice(i, 1);
switch ($scope.currentStep) {
case 'details':
switch ($state.current.name) {
case 'upload-pool':
$scope.currentStep = 'uploaded';
break;
case 'select-deal':
case 'edit-select-deal':
$scope.stepCompleted.splice(i - 1, 1);
$scope.currentStep = 'prepare';
break;
}
break;
case 'properties':
$scope.currentStep = 'details';
break;
}
break;
}
}
$scope.tooglePoolEntry = function () {
var i = $scope.poolDraft.SelectedDeals.indexOf(this.deal.DealID);
if (i < 0) {
$scope.poolDraft.SelectedDeals.push(this.deal.DealID);
} else {
$scope.poolDraft.SelectedDeals.splice(i, 1);
}
}
$scope.goToCreateDeal = function () {
// console.log($state.current);
Storage.setItem('previousStateData', $state.current);
$location.path('/add-deal/generalinfo');
}
}])
.controller('mailAccountAppCtrl', ['$rootScope', '$scope', '$state', 'appInfo', '$location', 'ngDialog', '$timeout', '$window', 'Storage', function ($rootScope, $scope, $state, appInfo, $location, ngDialog, $timeout, $window, Storage) {
$scope.currentPage = 1;
$scope.addSMTP = function () {
$state.go("add-mail-account");
}
$scope.init = function () {
if ($location.path() == '/company-smtp-details') {
var CompanySmtp = Storage.getItem('CompanySmtp');
$scope.CompanySmtpForPhone = CompanySmtp;
} else {
$scope.addSMTP = {
"UserName": null,
"Password": null,
"SmtpPort": null,
"SmtpHost": null
};
$scope.addSMTP.EmailProvider = $rootScope.EmailProviders[0];
$scope.smtpListFilter = {};
appInfo.checkMailAccount(function (response) {
if (response.ResponseCode = 200 && !$scope.defaultSmtpUserName && response.Data) {
$scope.defaultSmtpUserName = response.Data[0].UserName;
if ($scope.defaultSmtpUserName.indexOf('@') == -1)
$scope.defaultSmtpUserName += '@' + response.Data[0].EmailProvider;
}
});
}
if ($state.params.OAuthToken) {
var token = $state.params.OAuthToken.split('/');
if (token[0] == "gmail") {
if (token[2] != "success") {
$scope.addSMTP.UserName = token[1];
$scope.addSMTP.EmailProvider = $scope.EmailProviders[1];
$timeout($scope.confirmSecurityFix, 10);
} else {
$scope.showFlashMessage('success', "GMail account added Successfully.");
}
}
}
}
$scope.enableEdit = function () {
$scope.enableUserEdit = true;
}
$scope.$watch("addSMTP.EmailProvider", function (newValue) {
if (newValue) {
$scope.addSMTP.SmtpHost = newValue.Host;
$scope.addSMTP.SmtpPort = newValue.Port;
if (newValue.isOAuthMode == 1)
$scope.addSMTP.Password = "";
}
});
$scope.$watch('smtpListFilter.Name', _.debounce(function (newValue, oldValue) {
if (newValue != oldValue)
appInfo.checkMailAccount(function () {
}, {
"Filter": $scope.smtpListFilter
}
);
}, 700));
$scope.confirmSecurityFix = function () {
if (checkstatus('frmAddSMTP', $scope)) {
if ($scope.addSMTP.EmailProvider.Title == "Gmail") {
// "Please enable app access to gmail by clicking on the following link
"+
// "https://www.google.com/settings/security/lesssecureapps
"+
// "Also please enable the IMAP to save sent mail in your Sent Folder
"+
// "https://mail.google.com/mail/u/0/#settings/fwdandpop"
$scope.ngConfirm("Please allow us to send email from your account."
, function () {
angular.element('#frmAddSMTP').attr('action', $location.$$protocol + "://account." + MASTER_DOMAIN + "/getGmailAccess").submit();
}, function () {
$scope.showFlashMessage("info", "Please provide the different SMTP host.");
});
} else
$scope.addEditSMTPDetails();
}
}
$scope.addEditSMTPDetails = function () {
var reqData = {
"AddEditSMTPDetails": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"SmtpHost": $scope.addSMTP.SmtpHost,
"SmtpPort": $scope.addSMTP.SmtpPort,
"UserName": $scope.addSMTP.UserName,
"Password": $scope.addSMTP.Password,
"EmailProviderID": $scope.addSMTP.EmailProvider.EmailProviderID
}
}
if (!_.isUndefined($scope.addSMTP.CompanyMailID)) {
reqData.AddEditSMTPDetails.CompanyMailID = $scope.addSMTP.CompanyMailID;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.addSMTP = {};
appInfo.checkMailAccount(function () {
});
$rootScope.showFlashMessage("success", response.Message);
}
else {
$rootScope.showFlashMessage("error", response.Message);
}
});
}
$scope.setDefaultSMTP = function () {
$rootScope.UseSMTP = {};
var reqData = {
"SetDefaltSmtp": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyMailID": this.SMTP.CompanyMailID
}
};
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$scope.addSMTP = {};
$rootScope.SignIn.UserDetails.SmtpUserName = response.Data.SmtpUserName;
$rootScope.showFlashMessage("success", "Success");
appInfo.checkMailAccount(function () {
});
$rootScope.showFlashMessage("success", response.Message);
}
else {
$rootScope.showFlashMessage("error", response.Message);
}
});
}
$scope.editSMTPDialog = function () {
$scope.addSMTP = this.SMTP;
for (var i in $scope.SortByOptions) {
if ($scope.SortByOptions[i].key == "CreditScoreID") {
$scope.SortByOptions.splice(i, 1);
}
}
ngDialog.open({
template: $rootScope.baseURL + '/partials/dlg-templates/dlg-editSMTP.html',
className: 'ng-popup ngdialog-theme-default',
scope: $scope
});
};
$scope.saveSmtpPhoneViewState = function (MantainState) {
Storage.setItem('CompanySmtp', this.SMTP);
}
$scope.showDeleteSMTPPopup = function () {
console.log(this.SMTP);
$scope.SMTP = this.SMTP;
$rootScope.ngConfirm('Are you sure you want to delete this Smtp ? default smtp will change to other existing. If not exist other smtp then default system smtp will work.', function () {
$scope.deleteSMTP();
});
}
$scope.deleteSMTP = function () {
var reqData = {
"DeleteSMTPDetails": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"CompanyMailID": $scope.SMTP.CompanyMailID,
"CompanyID": $scope.SMTP.CompanyID
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
if ($location.path() == '/company-smtp-details') {
$state.go('list-mail-account');
} else {
$rootScope.showFlashMessage("success", response.Message);
appInfo.checkMailAccount(function () {
});
}
}
else
$rootScope.showFlashMessage("error", response.Message);
});
}
$scope.showSmtpDeletePopup = function () {
$scope.SMTP = (this.CompanySmtpForPhone) ? angular.copy(this.CompanySmtpForPhone) : {};
$scope.ngConfirm('Are you sure you want to delete this SMTP Account ?', function () {
$scope.deleteSMTP();
});
}
if ($rootScope.CompanyPreferences) {
appInfo.getMailProviders($scope.init);
} else
$rootScope.$on('company-loaded', function (event, eSrc) {
appInfo.getMailProviders($scope.init);
});
}])
.controller('paymentCtrl', ['$rootScope', '$scope', '$state', 'appInfo', '$location', 'ngDialog', '$timeout', '$window', 'Storage', function ($rootScope, $scope, $state, appInfo, $location, ngDialog, $timeout, $window, Storage) {
$scope.currentPage = 1;
$scope.getPayments = function () {
if ($scope.SignIn.UserDetails.UserTypeID == 4)
return false;
var reqData = {
"Get_payments": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ModuleEntityID": $scope.ModuleEntityID,
"ClientTZDIFF": $rootScope.uaInfo.ClientTZDIFF,
"currentPage": $scope.currentPage
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
pagingData = [];
$scope.Data = response.Data.Payments;
pagingData.currentPage = response.Data.Paginator.current_page;
pagingData.totalPage = response.Data.Paginator.total_pages;
pagingData.totalRecord = $scope.totalPayments = response.Data.Paginator.total_payments;
pagingData.numPerPage = 10;
$scope.showingDealtext = appInfo.getPaginationData(pagingData);
}
else {
$rootScope.showFlashMessage("error", response.Message);
}
});
}
if ($scope.moduleName == 'Deal') {
$scope.ModuleEntityID = $state.params.DealUID;
}
else {
$scope.ModuleEntityID = $state.params.ApplicationNumber;
}
$scope.init = function () {
appInfo.getPaymentSourceType(function () {
$scope.PaymentData = { Amount: "", PaymentDate: "", Source: {}, Remarks: "" };
$scope.getPayments();
});
}
$scope.changePaymentStatus = function (ID, StatusID) {
if (StatusID != 'Delete')
Status = 'change';
else
Status = StatusID;
$scope.ngConfirm('Are you sure you want to ' + Status + ' status of this record ?', function () {
var reqData = {
"ChangePaymentStatus": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"ModuleEntityID": $scope.ModuleEntityID,
"StatusID": StatusID,
"ID": ID,
"ModuleName": $scope.moduleName
}
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.showFlashMessage("success", response.Message);
$scope.getPayments();
}
else {
$rootScope.showFlashMessage("error", response.Message);
}
});
});
}
$scope.savePaymentData = function (forceInsert) {
if (checkstatus('addPaymentForm', $scope)) {
var reqData = {
"SavePaymentData": {
"LoginSessionKey": $rootScope.SignIn.LoginSessionKey,
"PaymentData": $scope.PaymentData,
"ModuleName": $scope.moduleName,
"ModuleEntityID": $scope.ModuleEntityID
}
}
if ($scope.moduleName == 'Deal') {
reqData.SavePaymentData.ModuleID = 17;
}
else {
reqData.SavePaymentData.ModuleID = 1;
}
if (forceInsert) {
reqData.SavePaymentData.forceInsert = forceInsert;
}
appInfo.getServerData(reqData).then(function (response) {
if (response.ResponseCode == 200) {
$rootScope.showFlashMessage("success", response.Message);
$scope.init();
}
else {
if (response.ResponseCode == 542) {
$rootScope.ngConfirm(response.Message, function () {
$scope.savePaymentData(true);
});
} else {
$rootScope.showFlashMessage("error", response.Message);
}
}
});
}
}
$scope.showRemarks = function (Data) {
$scope.Payment = Data;
ngDialog.open({
template: $scope.baseURL + '/partials/dlg-templates/dlg-remarks-details-popup.html?v=' + RELEASE_VERSION,
scope: $scope,
className: 'ng-popup ngdialog-theme-default'
});
}
$scope.init();
}])
// Resources Controller
.controller('resourcesCtrl', ['$rootScope', '$timeout', '$scope', 'appInfo', '$location', 'ngDialog', function ($rootScope, $timeout, $scope, appInfo, $location, ngDialog) {
$scope.resourcesImages = [
$rootScope.siteURL + "assets/img/banners/banner_style_1.jpg",
$rootScope.siteURL + "assets/img/banners/banner_style_2.jpg",
$rootScope.siteURL + "assets/img/banners/banner_style_3.jpg",
$rootScope.siteURL + "assets/img/banners/banner_style_4.jpg",
$rootScope.siteURL + "assets/img/banners/banner_style_5.jpg",
$rootScope.siteURL + "assets/img/banners/banner_style_6.jpg",
$rootScope.siteURL + "assets/img/banners/banner_style_7.jpg",
$rootScope.siteURL + "assets/img/banners/banner_style_8.jpg",
$rootScope.siteURL + "assets/img/banners/banner_style_9.jpg",
];
}]);