Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fmquaglia
Created March 30, 2016 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmquaglia/cd0808a7683c9eeaa5d782860112eafd to your computer and use it in GitHub Desktop.
Save fmquaglia/cd0808a7683c9eeaa5d782860112eafd to your computer and use it in GitHub Desktop.
'use strict';
angular.module('circleBackApp').controller(
'UICtrl',
function($scope,
$analytics,
$filter,
$location,
$log,
$q,
$route,
$routeParams,
$rootScope,
$timeout,
Alert,
Agent,
AuthService,
CBCore,
Confirm,
Contacts,
ContactIssues,
ExternalPrincipals,
Groups,
Media,
Mode,
Notification,
Selection,
SigCapture,
Sorting,
Status,
Suggestions,
UserProfile) {
function handleInit() {
$scope.navigation = null;
$scope.Groups = Groups;
$scope.Mode = Mode;
$scope.ContactIssues = ContactIssues;
$scope.Contacts = Contacts;
$scope.SigCapture = SigCapture;
$scope.Sorting = Sorting;
$scope.status = Status;
$scope.Status = Status;
$scope.Suggestions = Suggestions;
$scope.Agent = Agent;
$scope.groups = [];
$scope.selectedGroups = [];
$scope.selectedGroupsUI = [];
$scope.view_trash = $location.path() == '/trash';
$scope.new_group = {
'color' : '',
'name' : ''
};
$scope.UserProfile = UserProfile;
$scope.date = new Date();
}
/////////////////////// UTILITY STUFF ////////////////////////
function flattenSelectedContactsGroups() {
return _.chain(Selection.get())
.map(function(contactId) {return Contacts.getContact(contactId).groups})
.flatten()
.map(
function(group) {
if (group) {
return $filter('getGroupNameByGroupId')(group.name, $scope.groups);
}
}
)
.uniq()
.compact()
.sort()
.value();
}
// ************ Listeners ********************
$scope.$on('$routeChangeSuccess', function() {
// reset header's navigation
if ($route.current &&
$route.current.navigation &&
typeof $route.current.navigation == "string")
$scope.navigation = $route.current.navigation;
$scope.page_type = ($route.current && $route.current.page_type) ? $route.current.page_type : 'generic';
});
$scope.$on('userLogin', function() {
handleInit();
Suggestions.refreshSuggestions();
});
$scope.$on('UserAccountCtrl.save', function() {
UserProfile.fetchProfile();
});
// ************* Root Scope Actions Broadcasters *************
$scope.saveAccountInfo = function() {
$scope.$broadcast('saveAccountInfo');
};
$scope.notifyPurge = function() {
var selectedContactsIds = Selection.get();
if (angular.isArray(selectedContactsIds) && selectedContactsIds.length) {
var isPlural = selectedContactsIds.length > 1;
var modal = Confirm.open({
message: 'Are you sure you want to delete the selected contact' + (isPlural ? 's' : '') + '?',
okBtn: 'Yes', cancelBtn: 'No'
});
modal.result.then(function() {
Alert.info('Deleting contact' + (isPlural ? 's' : '') + ' permanently, please wait...');
var promise = Contacts.purge(selectedContactsIds);
promise.then(function() {
Alert.success('Contact' + (isPlural ? 's' : '') + ' successfully deleted.');
});
}
);
}
};
$scope.notifyRestore = function() {
var selectedContactIds = Selection.get();
if (angular.isArray(selectedContactIds) && selectedContactIds.length) {
var isPlural = selectedContactIds.length > 1;
Alert.info('Restoring contact' + (isPlural ? 's' : '') + ', please wait...');
var promise = Contacts.restore(selectedContactIds);
promise.then(function() {
Alert.success('Contact' + (isPlural ? 's' : '') + ' successfully restored');
Selection.clear();
ContactIssues.fetchCounts();
ContactIssues.refreshIdentity();
ContactIssues.refreshContact();
Suggestions.getFuzzyCount();
Suggestions.refreshSuggestions();
SigCapture.refreshEnabledSigCaptures();
});
}
};
$scope.notifyReScan = function() {
$scope.$broadcast('reScanRequested');
};
$scope.contactId = function() {return $routeParams.contactId};
$scope.isLoggedIn = function() {
return AuthService.isLoggedIn();
};
$scope.hasExternalLayout = function() {
return !$scope.isLoggedIn() ||
$location.path().match(/account\/networks$|\/accounts\/loading$/i);
};
$scope.handleLogout = function() {
AuthService.logout();
};
$scope.onGroupsOpen = function() {
$scope.selectedGroups = flattenSelectedContactsGroups();
};
$scope.refreshAndGoToContacts = function() {
if (!Status.processing) {
Contacts.refreshContacts();
Suggestions.refreshSuggestions();
SigCapture.refreshEnabledSigCaptures();
if ($location.path() != '/contacts') {
$location.path('contacts');
}
}
};
$scope.refreshAndGoToSigCapture = function() {
var sigCaptureContext = SigCapture.getFirstEnabledSigCapture();
if (!Status.processing) {
SigCapture.refreshEnabledSigCaptures();
if (angular.isString(sigCaptureContext)) {
var sigCaptureRoute = 'dashboard/signature_capture/' + sigCaptureContext;
if ($location.path() != '/' + sigCaptureRoute) {
$location.path(sigCaptureRoute);
}
} else {
//TODO: do what?
}
}
};
$scope.refreshAndGoToDashboard = function() {
if (Suggestions.count > 0) {
$location.path('dashboard');
ContactIssues.fetchCounts();
ContactIssues.refreshIdentity();
ContactIssues.refreshContact();
} else {
$location.path('dashboard/issues/identity');
Suggestions.getFuzzyCount();
Suggestions.refreshSuggestions();
}
};
$scope.isGroupSelected = function(group) {
return _.contains($scope.selectedGroups, group.name);
};
$scope.handleGroupsChange = function(index, isSelected, group) {
if (!group.groupId || !group.name) return;
Alert.info(
(isSelected ? 'Adding contacts to ' : 'Removing contacts from ')
+ group.name + ', please wait...'
);
var defer;
if (isSelected) {
defer = Contacts.addContactToGroup(Selection.get(), group);
} else {
defer = Contacts.removeContactFromGroup(Selection.get(), group);
}
defer.then(function() {
Alert.success(
'Contacts successfully ' +
(isSelected ? 'added to ' : 'removed from ') +
group.name
);
},
function() {
Alert.error('Oops, something went wrong...');
});
};
$scope.handleContactsViewChange = function(currentView) {
Status.contactsView.set(currentView);
$scope.contactsView = currentView;
Selection.clear();
};
$scope.notifyBulkDelete = function() {
var selectedContactIds = Selection.get();
if (angular.isArray(selectedContactIds) && selectedContactIds.length) {
var isPlural = selectedContactIds.length > 1,
message = 'Are you sure you want to delete ';
if (isPlural) {
message += selectedContactIds.length + ' contacts';
} else {
var contact = Contacts.getContact(selectedContactIds[0]);
if (contact && contact.firstName || contact.lastName) {
message += contact.firstName.trim() ? contact.firstName : '';
message += contact.firstName.trim() && contact.lastName.trim() ? ' ' : '';
message += contact.lastName.trim() ? contact.lastName : '';
} else if (
contact &&
angular.isArray(contact.jobs) &&
angular.isObject(contact.jobs[0]) &&
angular.isObject(contact.jobs[0].value) &&
angular.isString(contact.jobs[0].value.organization)
) {
message += contact.jobs[0].value.organization;
} else {
message += 'this contact';
}
}
message += '?';
var modal = Confirm.open({
'message': message,
'okBtn': 'Yes',
'cancelBtn': 'No'
});
modal.result.then(function() {
Alert.info('Deleting selected contact' + (isPlural ? 's' : '') + ', please wait...');
var promise = Contacts.trash(selectedContactIds);
promise.then(
function() {
Alert.success('Selected contact' + (isPlural ? 's' : '') + ' successfully deleted');
Selection.clear();
},
function() {
Alert.error('Something went wrong deleting the contact' + (isPlural ? 's' : ''));
Selection.clear();
}
);
});
}
};
// ---------------------------------------------------------------------------
// Listeners
// ---------------------------------------------------------------------------
$scope.$on('Contacts.purge', function() {
Status.safeApply(function() {
$scope.status = Status;
});
});
$scope.$on('Contacts.restore', function() {
Status.safeApply(function() {
$scope.status = Status;
});
});
$scope.$on('Contacts.trash', function() {
Status.safeApply(function() {
$scope.status = Status;
});
});
$scope.$on('Suggestions.dismiss', function() {
Status.safeApply(function() {
$scope.status = Status;
});
});
$scope.$on('AuthService.userLogout', function() {
$scope.Suggestions.count = 0;
$location.path('/accounts/login');
});
// ---------------------------------------------------------------------------
// Syncronization
// ---------------------------------------------------------------------------
var refreshEveryMillis = 15000; // 15 seconds by default
var refreshTimer = null;
var previousContactsLength = 0;
$rootScope.$on('Contacts.fetchContacts', function(event, contactsLength) {
if (previousContactsLength === 0 && contactsLength > 0) {
previousContactsLength = contactsLength;
refreshEveryMillis = 60000; // 1 minute after the initial batch of contacts has been fetch
refresh();
}
});
function refresh() {
if (AuthService.isLoggedIn()) {
$log.log('UICtrl.refresh');
// Cancel the old timer
if (refreshTimer != null) {
$timeout.cancel(refreshTimer);
refreshTimer = null;
}
return $q.all(
[
Groups.refresh(),
Contacts.refreshContacts(),
Contacts.refreshImages(),
UserProfile.fetchProfile(),
SigCapture.refreshEnabledSigCaptures()
]
).then(
function() {
refreshTimer = $timeout(refresh, refreshEveryMillis); // 15 secs until first contact batch, then 1 Min
},
function(status) {
// if the api is returning 401's force the user to login again
if (status == 401) {
$log.log("not authorized", status);
AuthService.logout();
} else {
$log.log("Failed to refresh", status);
refreshTimer = $timeout(refresh, refreshEveryMillis); // 15 secs until first contact batch, then 1 Min
}
}
);
}
}
$scope.$watch('AuthService.currentAuthInfo', function(currentAuthInfo) {
if (currentAuthInfo != null) {
// Logged in
// call resume on the API
var applicationName = Mode.getApplicationName();
CBCore.resume(applicationName);
// Start refreshing
refresh();
// Fetch contact issue counts
ContactIssues.fetchCounts();
$q.all([SigCapture.getCount('EmailScanGmail'), SigCapture.getCount('EmailScanGmail1')])
.then(function() {
SigCapture.getFuzzyCount();
Status.safeApply(
function() {
$scope.SigCapture.count.EmailScanGmail = SigCapture.count.EmailScanGmail;
$scope.SigCapture.count.EmailScanGmail1 = SigCapture.count.EmailScanGmail1;
}
)
});
} else {
// Logged out
// Cancel the refresh timer
$timeout.cancel(refreshTimer);
refreshTimer = null;
// Clear the contacts service and groups
Contacts.clear();
Groups.clear();
}
});
$scope.withoutNetworks = true;
$scope.$watch(function() {
return ExternalPrincipals.connectedNetworkCount() <= 0 &&
$scope.page_type === 'contact_list';
}, function(newValue) {
$scope.withoutNetworks = newValue;
Status.safeApply('withoutNetworks');
});
// -------------------------------------------------------------------------
// Allowed URLs
// -------------------------------------------------------------------------
function isAllowedUrl() {
var allowedUrls = /\/(?:esc|oauth|resetPassword|accounts\/(?:create|login|app_login)|forgotPassword|viewupdates|viewsignatures|enablesync)(?:\?.+)?/;
return allowedUrls.test($location.path());
}
$scope.$watch(
function() {return Mode.val();},
function(mode) {
if (mode === undefined && !isAllowedUrl()) {
$location.path('accounts/loading')
}
}
);
$scope.$watch(
AuthService.isLoggedIn,
function(isLoggedIn) {
if (!isLoggedIn && !isAllowedUrl()) {
$location.path(Mode.getDefaultUrl());
}
}
);
// -------------------------------------------------------------------------
// Notifications
// -------------------------------------------------------------------------
function getNewContactsMessage(count) {
var plural = (count === 0 || count > 1) ? 's' : '';
return count + ' Contact' + plural + ' Pending Review';
}
var deregisterSigcaptureCountWatcher = $scope.$watch(
SigCapture.getExactCount,
function(newCount, oldCount) {
if (newCount > oldCount) {
$rootScope.$broadcast('UICtrl.sigCapturesFound');
if ($location.path() === '/account/networks') {
if (Mode.isESC()) {
Notification.info(
'<span class="pointer">' +
getNewContactsMessage(newCount) +
'</span>',
function() {
$location.path('dashboard/signature_capture/EmailScanGmail');
},
null
);
}
} else {
Notification.info(
'<span class="pointer">' +
getNewContactsMessage(newCount) +
'</span>'
);
}
}
}
);
function getContextIdFromContextTypeValue(contextTypeValue) {
var ret = 10;
var value = parseInt(contextTypeValue);
if (angular.isNumber(value) && value >= 200) {
ret = value - 190;
}
return ret;
}
function buildReauthMessage(deAuthNetworks) {
return 'Reauthorization Required ' +
(angular.isString(deAuthNetworks[0].oAuthUserId) ? 'for ' + deAuthNetworks[0].oAuthUserId : '') +
': <a>Reauthorize now &raquo;</a>';
}
function deAuthCallback(deAuthNetworks) {
$location.path('/account');
$timeout(
function() {
Notification.clear();
if (ExternalPrincipals.hasDeAuth()) {
$rootScope.$broadcast(
'ManageNetworkCtrl.reAuthorizeNetwork',
getContextIdFromContextTypeValue(
deAuthNetworks[0].contextTypeValue
)
);
}
},
2000
);
}
function deAuthHandler(hasDeAuthNetworks) {
if (hasDeAuthNetworks && Mode.isESC()) {
var deAuthNetworks = ExternalPrincipals.deAuthNetworks();
if (
angular.isArray(deAuthNetworks) && deAuthNetworks.length > 0 &&
_.any(
deAuthNetworks,
function(deAuthNetwork) {
return ExternalPrincipals.isEmailScanNetwork(deAuthNetwork);
}
)
) {
Notification.danger(
buildReauthMessage(deAuthNetworks),
function() {
deAuthCallback(deAuthNetworks);
},
null,
{}
)
}
}
}
function hasDeAuthByMode() {
return Mode.isESC() ?
ExternalPrincipals.hasEmailScanEnabledDeAuth :
ExternalPrincipals.hasDeAuth;
}
var deregisterDeAuthWatcher = $scope.$watch(
hasDeAuthByMode(),
function(hasDeauth) {
deAuthHandler(hasDeauth);
}
);
$scope.$on('ExternalPrincipals.fetch', function() {
if (Mode.isESC()) {
deAuthHandler(ExternalPrincipals.hasEmailScanEnabledDeAuth())
}
});
function deRegisterWatchers(watchers) {
if (angular.isArray(watchers)) {
angular.forEach(
watchers,
function(watcher) {
if (angular.isFunction(watcher)) {
watcher();
}
}
)
}
}
function resetWatchersAndRefreshTimer() {
deRegisterWatchers(
[
deregisterSigcaptureCountWatcher,
deregisterDeAuthWatcher
]
);
refreshEveryMillis = 15000; // on logout reset default refresh timer
}
$scope.$on('AuthService.logout', resetWatchersAndRefreshTimer);
$scope.$on('UserProfile.delete', resetWatchersAndRefreshTimer);
handleInit();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment