angular.module('Library', ['pascalprecht.translate']); angular.module('LocalStorage', []); angular.module('Settings', ['LocalStorage', 'ng-sortable']); angular.module('Security', ['LocalStorage']); angular.module('Session', ['LocalStorage']); angular.module('Facets', ['Session']); angular.module('Properties', ['Session', 'LocalStorage']); angular.module('CommonDirectives', ['Facets', 'LocalStorage', 'Library']); angular.module('Document', ['Session']); angular.module('DocumentInquiry', [ 'Session', // Session data 'LocalStorage', // Altec Key-value storage for settings 'pascalprecht.translate', // localization directives 'Settings', 'CommonDirectives', 'nzToggle', 'Properties', 'angular-growl', // support for growl notifications ]); angular.module('SmartForms', ['cfp.hotkeys']); angular.module('DocumentViewer', [ 'Library', 'pascalprecht.translate', 'Properties', 'Session', 'angular-growl', 'colorpicker' //support for color picker in annotation settings ]); angular.module('Workflow', [ 'Session', // Session data 'LocalStorage', // Altec Key-value storage for settings 'pascalprecht.translate', // localization directives 'angular-growl', // support for growl notifications 'ngTable', // Table 'Library', // Library Functions 'DocumentViewer' // Viewer Directives ]); angular.module('test', []); var app = angular.module('docLinkWeb', [ //'ngAnimate', // animations 'ngRoute', // routing 'ngSanitize', // sanitization 'ngLocale', // localization 'Security', // Authentication and Authorization 'LocalStorage', // Altec Key-value storage for settings 'Settings', // Settings 'ngCookies', // required for pascalprecht.translate. Unused elsewhere. 'pascalprecht.translate', // localization directives 'tmh.dynamicLocale',// Dynamically switch Angular locale 'Properties', // Master Properties 'Document', // Document-Specific logic 'DocumentInquiry', // Document Inquiry 'Workflow', // Workflow 'DocumentViewer', // Viewer 'ngIdle', // Idle checking 'Library', // Library Functions 'treeControl', // TreeView Control 'ngCsv', // csv export 'angular-growl', // support for growl notifications 'ngTagsInput', // multiselect for document inquiry top level folders and document types 'ui.bootstrap', // angular bootstrap controls 'ui.layout', // angular resizable panels 'SmartForms', // Smartforms 'test', // Testing 'ngTouch', // touch events 'SignalR', // Signal-R Library 'colorpicker' //support for color picker in annotation settings ]); // Set up the cache ‘docLinkWebCache’ app.factory('docLinkWebCache', ['$cacheFactory', function ($cacheFactory) { return $cacheFactory('docLinkWebCache'); }]); //#region Ripple Effect app.directive('rippleEffect', function () { return { restrict: 'A', link: function (scope, element, attrs) { //var x, y, size, offsets; //var func = function (e) { // var eventType = e.type; // if ($(this).find(".ripple-wrapper").length > 0) { // $(".ripple-wrapper").remove(); // } // var $wrapper = $('
'); // var btnOffset = $(this).offset(); // var xPos = event.pageX - btnOffset.left; // var yPos = event.pageY - btnOffset.top; // var height = parseInt($(this).css("height")); // var width = parseInt($(this).css("width")); // $wrapper.css("height", $(this).css("height")); // $wrapper.css("width", $(this).css("width")); // var $rippleeffect = $('
'); // $rippleeffect.css("top", yPos - 25); // $rippleeffect.css("left", xPos - 25); // $rippleeffect.appendTo($wrapper); // $wrapper.appendTo($(this)); // var rippletimer = window.setTimeout(function () { // $wrapper.remove(); // clearTimeout(rippletimer); // }, 900); //} //element.on('touchend mouseup', func); ////remove the event listener on scope destroy //scope.$on('$destroy', function () { // element.off('touchend mouseup', func); //}); } }; }); //#endregion Ripple Effect app.constant('AUTH_EVENTS', { loginSuccess: 'auth-login-success', loginFailed: 'auth-login-failed', logoutSuccess: 'auth-logout-success', logoutFailed: 'auth-logout-failed', sessionTimeout: 'auth-session-timeout', notAuthenticated: 'auth-not-authenticated', notAuthorized: 'auth-not-authorized', serviceNotAvailable: 'service-not-available', sessionRefreshed: 'auth-session-refreshed' }); app.constant('USER_ROLES', { internal: 'INTERNAL', external: 'EXTERNAL', administrator: 'ADMINISTRATOR' }); app.constant('CACHE_KEYS', { documentsToOpen: 'viewer-document_ids', resultsViewSettings: 'results-view-settings', quickSearches: 'quick-searches', currentQuickSearch: 'current-quick-search', currentQuickSearchRequest: 'current-quick-search-request', quickSearchResults: 'quick-search-results', savedSearches: 'saved-searches', currentSavedSearch: 'current-saved-search', currentAdvancedSearchRequest: 'current-advanced-search-request', currentFullTextSearchRequest: 'current-fulltext-search-request', advancedSearchResults: 'advanced-search-results', workflowFavorites: 'workflow-favorites', workflows: 'workflows', workflowDelegations: 'workflowDelegations', currentWorkflowRequest: 'current-workflow-request' }); app.config(['$uibModalProvider', function($modalProvider) { $modalProvider.options.animation = false; }]); app.config(['$provide', '$routeProvider', '$httpProvider', 'IdleProvider', 'USER_ROLES', function ($provide, $routeProvider, $httpProvider, IdleProvider, USER_ROLES) { //$provide.decorator("$exceptionHandler", function ($delegate, errorLogService) { // return function (exception, cause) { // $delegate(exception, cause); // return errorLogService; // }; //}); //================================================ // Add an interceptor for AJAX //================================================ //#region Add an interceptor for AJAX var requestCount = 0; $httpProvider.interceptors.push(['$q', '$rootScope', '$location', 'AUTH_EVENTS', '$timeout', '$translate', function ($q, $rootScope, $location, AUTH_EVENTS, $timeout, $translate) { return { 'responseError': function (response) { //console.log("responseError in interceptor: " + JSON.stringify(response)); requestCount--; if (response.status === 401) { if ($location.path() !== "/") { //not at the login page $rootScope.$broadcast(AUTH_EVENTS.notAuthorized); } } if (response.status === 404 && response.config.url.lastIndexOf("App/", 0) !== 0) { //this is not a template request $rootScope.$broadcast(AUTH_EVENTS.serviceNotAvailable); } if (response.status === 0 && response.config.url.lastIndexOf("App/", 0) !== 0) { if ($location.path() === "/") { $rootScope.serverMessage = $translate.instant("GLOBAL_NORESPONSE"); //"No Response from Service. Please try again."; GLOBAL_NORESPONSE } else { $rootScope.$broadcast(AUTH_EVENTS.serviceNotAvailable); } } if (response.data !== null && response.data.ExceptionType && response.data.ExceptionType === "Altec.Framework.AuthenticationFailedException") { $rootScope.serverMessage = $translate.instant("SESSIONLOST"); $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated); $rootScope.ShowLoader = false; return null; } $rootScope.ShowLoader = false; return $q.reject(response); }, 'response': function (response) { if (requestCount > 0) { requestCount--; } //console.log("requestCount: " + requestCount); if (requestCount < 1) { $rootScope.ShowLoader = false; //$("#preLoad").hide(); } return response; }, 'request': function (config) { //don't show loader for any Document Image calls (thumbs, pages, metadata, etc) as the ImageViewer Directive will handle it's own loading screen if (config.url.indexOf("api/DocumentImage/") !== -1) { return config; } if (config.url.indexOf("api/Document/") !== -1) { return config; } //don't show loader for smartforms api calls if (config.url.indexOf("api/SmartForms") !== -1) { return config; } //don't show loader for getting workflow statuses since this loads as part of spin-up (makes the page seem ugly slow) if (config.url.indexOf("api/Workflow/WorkflowNextStatuses") !== -1) { return config; } //don't show loader for Smartforms callouts since this this will happen a lot as the user goes through the forms (makes the page seem ugly slow) if (config.url.indexOf("/api/Lookup/DoLookup") !== -1) { return config; } if (config.url.indexOf("ProcessCommand") !== -1) { return config; } if (config.url.indexOf("GetStampConfig") !== -1) { return config; } //console.log(config.url); requestCount++; //show the splash screen only after 2 second of waiting. this is so quick transitions don't show the loader, but longer make the site seem more responsive //$timeout(function () { // //console.log("requestCount: " + requestCount); // if (requestCount > 0) { // $("#preLoad").fadeIn("slow"); // } //}, 2000); return config; } }; }]); //#endregion Add an interceptor for AJAX //================================================ // Routes //================================================ //#region Routes $routeProvider.when('/', { templateUrl: ViewRoot + 'Login' }); //#region Portal routes $routeProvider.when('/portal/:CustomInquiryID?', { templateUrl: ViewRoot + 'Portal', controller: 'portalController', }); $routeProvider.when('/portal/:CustomInquiryID/Results', { templateUrl: ViewRoot + 'Portal', controller: 'portalController', }); $routeProvider.when('/portal/:CustomInquiryID/viewer/:DocumentID/:Operation?/', { templateUrl: ViewRoot + 'Viewer', controller: 'documentViewerController', }); //#endregion //#region Quicksearch routes $routeProvider.when('/quicksearch/:CustomInquiryID?', { templateUrl: ViewRoot + 'QuickSearch', controller: 'quicksearchController', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] } }); $routeProvider.when('/quicksearch/:CustomInquiryID/Results', { templateUrl: ViewRoot + 'QuickSearch', controller: 'quicksearchController', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] } }); $routeProvider.when('/quicksearch/:CustomInquiryID/viewer/:DocumentID/:Operation?/', { templateUrl: ViewRoot + 'Viewer', controller: 'documentViewerController', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] } }); //#endregion //#region Advanced Search $routeProvider.when('/advancedSearch/:SavedInquiryID?', { templateUrl: ViewRoot + 'AdvancedSearch', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] }, controller: 'advancedsearchController' }); $routeProvider.when('/advancedSearch/:SavedInquiryID/Results', { templateUrl: ViewRoot + 'AdvancedSearch', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] }, controller: 'advancedsearchController' }); $routeProvider.when('/advancedSearch/:SavedInquiryID/viewer/:DocumentID/:Operation?/', { templateUrl: ViewRoot + 'Viewer', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] }, controller: 'documentViewerController' }); //#endregion //#region FullText Search $routeProvider.when('/fulltext', { templateUrl: ViewRoot + 'FulltextSearch', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] }, controller: 'fulltextController' }); $routeProvider.when('/fulltext/Results', { templateUrl: ViewRoot + 'FulltextSearch', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] }, controller: 'fulltextController' }); $routeProvider.when('/fulltext/viewer/:DocumentID/:Operation?/', { templateUrl: ViewRoot + 'Viewer', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] }, controller: 'documentViewerController' }); //#endregion //#region Workflow $routeProvider.when('/workflow/:WorkflowID?/:WorkflowStatus?/:WorkflowQueue?', { templateUrl: ViewRoot + 'Workflow', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] }, controller: 'workflowSearchController' }); $routeProvider.when('/workflow/:WorkflowID?/:WorkflowStatus?/:WorkflowQueue?/Results', { templateUrl: ViewRoot + 'Workflow', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] }, controller: 'workflowSearchController' }); $routeProvider.when('/workflow/:WorkflowID/:WorkflowStatus/:WorkflowQueue/viewer/:DocumentID/:Operation?/', { templateUrl: ViewRoot + 'WorkflowViewer', controller: 'WorkflowViewerController', access: { requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] } }); //$routeProvider.when('/workflowDashboard', { // templateUrl: ViewRoot + 'WorkflowDashBoard', // access: { // requiredRoles: [USER_ROLES.internal, USER_ROLES.administrator] // }, // controller: 'workflowDashboardController' //}); //#endregion //#region Search by Property $routeProvider.when('/searchByProperty/:SearchType/:PropertyId/:PropertyValue', { templateUrl: ViewRoot + 'SearchByProperty', controller: 'searchByPropertyController' }); $routeProvider.when('/searchByProperty/:SearchType/:PropertyId/:PropertyValue/Results', { templateUrl: ViewRoot + 'SearchByProperty', controller: 'searchByPropertyController' }); $routeProvider.when('/searchByProperty/:SearchType/:PropertyId/:PropertyValue/viewer/:DocumentID/:Operation?/', { templateUrl: ViewRoot + 'Viewer', controller: 'documentViewerController', }); //#endregion //#region Test $routeProvider.when('/test', { templateUrl: ViewRoot + 'Test', controller: 'TestController' }); $routeProvider.when('/test/viewer/:DocumentID', { templateUrl: ViewRoot + 'Test', controller: 'TestController' }); //#endregion Test //#region Standalone Viewer $routeProvider.when('/viewer/:DocumentID/:Operation?/', { templateUrl: ViewRoot + 'Viewer', controller: 'documentViewerController', }); //#endregion Standalone Viewer //#region Smartforms $routeProvider.when('/smartform/:SmartFormsTabId/', { templateUrl: ViewRoot + 'SmartformClientTab', controller: 'smartClientTabController', }); //#endregion Smartforms //#region Version Control $routeProvider.when('/versioncontrol', { templateUrl: ViewRoot + 'VersionControl', controller: 'versionControlController', }); //#endregion Version Control //#endregion Routes //================================================ // Set Default Settings for $httpProvider //================================================ $httpProvider.defaults.useXDomain = true; $httpProvider.defaults.headers.common['lang'] = 'en-US'; // jshint ignore:line delete $httpProvider.defaults.headers.common['X-Requested-With']; //make delete requests pass data as JSON $httpProvider.defaults.headers["delete"] = { 'Content-Type': 'application/json;charset=utf-8' }; //================================================ // Configure Idle settings //================================================ IdleProvider.idle(5); // in seconds IdleProvider.timeout(20); // in seconds IdleProvider.autoResume("notIdle"); IdleProvider.interrupt("keydown DOMMouseScroll mousewheel mousedown touchstart touchmove scroll"); }]); app.config(['$translateProvider', function ($translateProvider) { //$translateProvider.useMissingTranslationHandlerLog(); $translateProvider.useSanitizeValueStrategy('escape'); $translateProvider.useLoaderCache("$translationCache"); $translateProvider.useUrlLoader(BaseUrl + "Home/GetLocalizationJSON"); $translateProvider.preferredLanguage('en-US'); $translateProvider.useLocalStorage(); }]); app.config(['growlProvider', function (growlProvider) { growlProvider.globalPosition('middle-center'); }]); app.config(['tmhDynamicLocaleProvider', function (tmhDynamicLocaleProvider) { tmhDynamicLocaleProvider.localeLocationPattern("angular/i18n/angular-locale_{{locale}}.js"); }]); app.run(['$rootScope', 'LocalStorageService', '$translate', '$translationCache', '$location', '$route', '$window', 'SessionFactory', 'PropertyService', 'Idle', 'AUTH_EVENTS', 'tmhDynamicLocale', 'SecurityService', 'docLinkWebCache', 'errorLogService', '$timeout', 'modalService', '$compile', '$http', '$locale', 'growl', 'SmartFormsAPIService', '$routeParams', 'MessagingService', function ($rootScope, LocalStorageService, $translate, $translationCache, $location, $route, $window, SessionFactory, PropertyService, Idle, AUTH_EVENTS, tmhDynamicLocale, SecurityService, docLinkWebCache, errorLogService, $timeout, modalService, $compile, $http, $locale, growl, SmartFormsAPIService, $routeParams, MessagingService) { $rootScope.CurrentUser = ""; $rootScope.CurrentUserRole = ""; $rootScope.TopLevelFolderNameSingular = ""; $rootScope.TopLevelFolderNamePlural = ""; $rootScope.TopLevelFolders = []; $rootScope.IsAuthenticated = false; $rootScope.HelpersVisible = false; $rootScope.SettingsVisible = false; $rootScope.MasterProperties = []; $rootScope.CurrentSection = "QuickSearch"; $rootScope.CurrentProgId = "QuickInquiry"; $rootScope.sessionTimeoutSecondsRemaining = -1; $rootScope.SessionTimeoutInSeconds = 0; $rootScope.manualLogout = false; $rootScope.WebAPIEndpoint = ""; $rootScope.CanChangePassword = true; $rootScope.ClientSmartForms = []; $rootScope.AppVersion = window["appVersion"]; $rootScope.Copyright = window["copyright"]; $rootScope.SiteCode = ""; var headerSizeIntervalId; //send a global resize message when the browser size changes angular.element($window).bind('resize', function () { $rootScope.$broadcast("browser-resized"); }); $rootScope.logout = function () { //$("#preLoad").fadeIn("fast"); $rootScope.ShowLoader = true; // stop the watch Idle.unwatch(); //disconnect session from Session Monitor SecurityService.logout().then(function () { SessionFactory.ClearCredentials(); $rootScope.$broadcast(AUTH_EVENTS.logoutSuccess); }); }; $rootScope.ResetTimeout = function () { console.log("ResetTimeout"); // restart the watch Idle.watch(); }; $rootScope.DoNavigate = function (path) { //$("#preLoad").fadeIn("fast"); $location.path(path); //$('.multiPropPopover').popover('hide'); }; $rootScope.OpenSmartForm = function (tab) { $location.path("/smartform/" + tab.SmartFormsTabId); $rootScope.ActiveSmartFormTab = tab; }; $rootScope.ShowSupportDialog = function () { modalService.show({ templateUrl: "tpl.supportDialog.html", controller: ['$scope', '$uibModalInstance', function ($scope, $modalInstance) { $scope.CloseDialog = function (result) { $modalInstance.close(false); }; $scope.$on("$destroy", function () { }); }] }, { }); }; $rootScope.ShowChangePasswordDialog = function () { modalService.show({ templateUrl: "tpl.ChangePasswordDialog.html", controller: ['$scope', '$uibModalInstance', '$rootScope', '$translate', 'SecurityService', 'growl', function ($scope, $modalInstance, $rootScope, $translate, SecurityService, growl) { $scope.credentials = { UserName: SessionFactory.GetLoginId(), CurrentPassword: '', NewPassword: '', ConfirmPassword: '' }; $scope.changePasswordMessage = ""; $scope.currentPasswordIsValid = true; $scope.CancelChangePassword = function (result) { $modalInstance.close(false); }; $scope.DoChangePassword = function (credentials) { $scope.changePasswordMessage = ""; $scope.currentPasswordIsValid = true; if (credentials.CurrentPassword === '') { $scope.changePasswordMessage = $translate.instant("CHANGEPASSWORD_ENTEREXISTING"); //"Please enter the existing password."; } if (credentials.NewPassword !== credentials.ConfirmPassword || credentials.NewPassword === '' || credentials.ConfirmPassword === '') { $scope.changePasswordMessage = $translate.instant("CHANGEPASSWORD_PASSWORDSMUSTMATCH"); //"New Password and Confirm Password do not match or one the fields is blank."; } else { SecurityService.changePassword(credentials).then(function () { growl.success("CHANGEPASSWORD_PASSWORDSCHANGESUCCESS", { ttl: 5000, onclose: function () { $rootScope.logout(); } }); $modalInstance.close(false); }, function (errorResponse) { $scope.currentPasswordIsValid = false; $scope.changePasswordMessage = errorResponse.response.Message; growl.error(errorResponse.response.Message, { ttl: 5000, disableCountDown: false }); }); } }; $scope.$on("$destroy", function () { }); }] }, { }); }; $rootScope.IsNativeFileType = function (fileType) { if (!angular.isDefined(fileType)) { return false; } switch (fileType.toUpperCase()) { case "TIFF": case "TIF": case "PDF": case "PCL": return true; break; default: return false; break; } } //document handlers and scope properties $rootScope.DocumentsToView = []; $rootScope.serverMessage = ""; $rootScope.RolePermissions = []; $rootScope.dlPermSearchDocuments = false; $rootScope.HasWorkflowPermission = false; $rootScope.HasQuickSearchPermission = false; //#region Localization/Language setup and events $rootScope.CurrentCulture = LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.CULTURE); if (!$rootScope.CurrentCulture) { $rootScope.CurrentCulture = "en-US"; } //#region Date Control config var tokenizedFormat = $locale.DATETIME_FORMATS.shortDate.replace("MM", "1").replace("M", "1").replace("dd", "2").replace("d", "2").replace("yyyy", "3").replace("yy", "3").replace("y", "3"); $rootScope.DateFormat = tokenizedFormat.replace("1", "MM").replace("2", "dd").replace("3", "yyyy"); var shortMonthLongYear = tokenizedFormat.replace("1", "M").replace("2", "dd").replace("3", "yyyy"); var shortMonthShortYear = tokenizedFormat.replace("1", "M").replace("2", "dd").replace("3", "yy"); var shortDayLongYear = tokenizedFormat.replace("1", "MM").replace("2", "d").replace("3", "yyyy"); var shortDayShortYear = tokenizedFormat.replace("1", "MM").replace("2", "d").replace("3", "yy"); var shortMonthshortDayLongYear = tokenizedFormat.replace("1", "M").replace("2", "d").replace("3", "yyyy"); var allShort = tokenizedFormat.replace("1", "M").replace("2", "d").replace("3", "yy"); var allLong = tokenizedFormat.replace("1", "MM").replace("2", "dd").replace("3", "yyyy"); var nonFormattedShort = tokenizedFormat.replace("1", "MM").replace("2", "dd").replace("3", "yy").replace(/\//g, ""); var nonFormattedLong = tokenizedFormat.replace("1", "MM").replace("2", "dd").replace("3", "yyyy").replace(/\//g, ""); $rootScope.AltDateFormats = [$rootScope.DateFormat, $locale.DATETIME_FORMATS.shortDate, "yyyy-MM-dd", shortMonthLongYear, shortMonthShortYear, shortDayLongYear, shortDayShortYear, shortMonthshortDayLongYear, allShort, allLong, nonFormattedShort, nonFormattedLong]; $rootScope.dateOptions = { minDate: new Date(2000, 1, 1), appendToBody: true, showWeeks: false }; $rootScope.Today = moment().format("L"); var numberExample = String("1,000,000.00").replace(".", "DECIMAL_SEP").replace(/,/g, "GROUP_SEP"); numberExample = numberExample.replace(/DECIMAL_SEP/g, $locale.NUMBER_FORMATS.DECIMAL_SEP).replace(/GROUP_SEP/g, $locale.NUMBER_FORMATS.GROUP_SEP); $rootScope.NumberFormatExample = numberExample; $rootScope.$on('$translateChangeSuccess', function () { tmhDynamicLocale.set($rootScope.CurrentCulture.toLowerCase()); }); $rootScope.$on('$localeChangeSuccess', function () { //date formats var tokenizedFormat = $locale.DATETIME_FORMATS.shortDate.replace("MM", "1").replace("M", "1").replace("dd", "2").replace("d", "2").replace("yyyy", "3").replace("yy", "3").replace("y", "3"); $rootScope.DateFormat = tokenizedFormat.replace("1", "MM").replace("2", "dd").replace("3", "yyyy"); var shortMonthLongYear = tokenizedFormat.replace("1", "M").replace("2", "dd").replace("3", "yyyy"); var shortMonthShortYear = tokenizedFormat.replace("1", "M").replace("2", "dd").replace("3", "yy"); var shortDayLongYear = tokenizedFormat.replace("1", "MM").replace("2", "d").replace("3", "yyyy"); var shortDayShortYear = tokenizedFormat.replace("1", "MM").replace("2", "d").replace("3", "yy"); var shortMonthshortDayLongYear = tokenizedFormat.replace("1", "M").replace("2", "d").replace("3", "yyyy"); var allShort = tokenizedFormat.replace("1", "M").replace("2", "d").replace("3", "yy"); var allLong = tokenizedFormat.replace("1", "MM").replace("2", "dd").replace("3", "yyyy"); var nonFormattedShort = tokenizedFormat.replace("1", "MM").replace("2", "dd").replace("3", "yy").replace(/\//g, ""); var nonFormattedLong = tokenizedFormat.replace("1", "MM").replace("2", "dd").replace("3", "yyyy").replace(/\//g, ""); $rootScope.AltDateFormats = [$rootScope.DateFormat, $locale.DATETIME_FORMATS.shortDate, "yyyy-MM-dd", shortMonthLongYear, shortMonthShortYear, shortDayLongYear, shortDayShortYear, shortMonthshortDayLongYear, allShort, allLong, nonFormattedShort, nonFormattedLong]; //change moment locale moment.locale($rootScope.CurrentCulture); $rootScope.Today = moment().format("L"); numberExample = String("1,000,000.00").replace(".", "DECIMAL_SEP").replace(/,/g, "GROUP_SEP"); numberExample = numberExample.replace(/DECIMAL_SEP/g, $locale.NUMBER_FORMATS.DECIMAL_SEP).replace(/GROUP_SEP/g, $locale.NUMBER_FORMATS.GROUP_SEP); $rootScope.NumberFormatExample = numberExample; //change request header $http.defaults.headers.common['lang'] = $rootScope.CurrentCulture.toLowerCase(); // jshint ignore:line }); //moment defaults moment.locale($rootScope.CurrentCulture); //request header $http.defaults.headers.common['lang'] = $rootScope.CurrentCulture.toLowerCase(); // jshint ignore:line //user-triggered change language callback $rootScope.changeLanguage = function (key) { $rootScope.CurrentCulture = key; $translate.use(key); }; //#endregion //#region Auth events $rootScope.$on(AUTH_EVENTS.loginSuccess, function () { //console.log("AUTH_EVENTS.loginSuccess"); $window.document.title = $translate.instant("APPLICATION_TITLE"); //set up globals $rootScope.CurrentUser = SessionFactory.GetUserName(); $rootScope.CurrentUserRole = SessionFactory.GetRole(); $rootScope.TopLevelFolderNameSingular = SessionFactory.GetTopLevelFolderSingular(); $rootScope.TopLevelFolderNamePlural = SessionFactory.GetTopLevelFolderPlural(); $rootScope.TopLevelFolders = SessionFactory.GetTopLevelFolders(); $rootScope.DocumentTypes = SessionFactory.GetDocumentTypes(); $rootScope.IsAuthenticated = SessionFactory.isAuthenticated(); $rootScope.RolePermissions = SessionFactory.GetRolePermissions(); $rootScope.HasWorkflowPermission = SessionFactory.GetWorkflowPermission(); $rootScope.HasQuickSearchPermission = SessionFactory.GetQuickSearchPermission(); $rootScope.WebAPIEndpoint = SessionFactory.GetServiceUrl(); $rootScope.CanChangePassword = (SessionFactory.GetIsLDAPUser() === false); $rootScope.RemoteShellComponents = SessionFactory.GetRemoteShellComponents(); $rootScope.SiteCode = SessionFactory.GetSiteCode(); $.each($rootScope.RolePermissions, function (idx, permission) { if (permission.PermissionName === "dlPermSearchDocuments") { $rootScope.dlPermSearchDocuments = permission.PermissionValue; } }); PropertyService.GetAllProperties().then(function (properties) { $rootScope.MasterProperties = properties; }); SmartFormsAPIService.GetDynamicUIClientTabs().then(function (tabs) { $rootScope.ClientSmartForms = _.sortBy(tabs, 'Caption'); if (angular.isDefined($routeParams.SmartFormsTabId)) { $rootScope.ActiveSmartFormTab = _.find($rootScope.ClientSmartForms, function (f) { return f.SmartFormsTabId == $routeParams.SmartFormsTabId; }); } }); // start watching when the app runs. also starts the Keepalive service by default. Idle.setIdle($rootScope.SessionTimeoutInSeconds); Idle.watch(); //start the messaging service MessagingService.Subscribe(SessionFactory.GetSmartFormsServiceURL().replace("/api/", "/signalr/"), "smartFormsMessaging"); //is there a search param? var returnUrl = $location.search().returnUrl || null; //check that the return url isn't for a path that this user is denied access for if (returnUrl !== "" && returnUrl !== null && returnUrl !== "/?returnUrl") { if ($rootScope.CurrentUserRole === 'EXTERNAL' && returnUrl.indexOf("/portal") === -1 && returnUrl.indexOf("/viewer") === -1) { returnUrl = null; } else if ($rootScope.HasQuickSearchPermission === false && returnUrl.indexOf("/quicksearch") > -1) { returnUrl = null; } else if ($rootScope.dlPermSearchDocuments === false && returnUrl.indexOf("/advancedSearch") > -1) { returnUrl = null; } else if ($rootScope.dlPermSearchDocuments === false && returnUrl.indexOf("/fulltext") > -1) { returnUrl = null; } else if ($rootScope.HasWorkflowPermission === false && returnUrl.indexOf("/workflow") > -1) { returnUrl = null; } } //check that the return url isn't for a path that is disabled in the components table if (returnUrl !== "" && returnUrl !== null && returnUrl !== "/?returnUrl") { if (returnUrl.indexOf("/quicksearch") > -1 && angular.isDefined(_.find($rootScope.RemoteShellComponents, function (c) { return c.ProgId === "QuickInquiry"; })) === false) { returnUrl = null; } else if (returnUrl.indexOf("/advancedSearch") > -1 && angular.isDefined(_.find($rootScope.RemoteShellComponents, function (c) { return c.ProgId === "AdvancedInquiry"; })) === false) { returnUrl = null; } else if (returnUrl.indexOf("/fulltext") > -1 && angular.isDefined(_.find($rootScope.RemoteShellComponents, function (c) { return c.ProgId === "FullTextSearch"; })) === false) { returnUrl = null; } else if (returnUrl.indexOf("/workflow") > -1 && angular.isDefined(_.find($rootScope.RemoteShellComponents, function (c) { return c.ProgId === "WorkflowInquiry"; })) === false) { returnUrl = null; } } //if the link is for the portal, but we're logging in with an INTERNAL user, clear the redirect path if ($rootScope.CurrentUserRole !== 'EXTERNAL' && returnUrl && returnUrl !== null && returnUrl.indexOf("/portal") > -1) { returnUrl = null; } if (returnUrl === null || returnUrl === "/?returnUrl") { //navigate to first tab if ($rootScope.CurrentUserRole === 'EXTERNAL') { $location.path('/portal').search(''); } else { var noAccess = true; //user has no access to any pages $.each($rootScope.RemoteShellComponents, function(i, shellComponent) { if (shellComponent.ProgId === "QuickInquiry" && (($rootScope.CurrentUserRole == 'INTERNAL' && $rootScope.HasQuickSearchPermission === true) || $rootScope.CurrentUserRole == 'ADMINISTRATOR')) { noAccess = false; $location.path('/quicksearch').search(''); return false; //break } else if (shellComponent.ProgId === "AdvancedInquiry" && (($rootScope.dlPermSearchDocuments === true && $rootScope.CurrentUserRole == 'INTERNAL') || $rootScope.CurrentUserRole == 'ADMINISTRATOR')) { noAccess = false; $location.path('/advancedSearch').search(''); return false; //break } else if (shellComponent.ProgId === "FullTextSearch" && (($rootScope.dlPermSearchDocuments === true && $rootScope.CurrentUserRole == 'INTERNAL') || $rootScope.CurrentUserRole == 'ADMINISTRATOR')) { noAccess = false; $location.path('/fulltext').search(''); return false; //break } else if (shellComponent.ProgId === "WorkflowInquiry" && (($rootScope.CurrentUserRole == 'INTERNAL' && $rootScope.HasWorkflowPermission === true) || $rootScope.CurrentUserRole == 'ADMINISTRATOR')) { noAccess = false; $location.path('/workflow').search(''); return false; //break } }); if (noAccess === true) { growl.error("NOACCESS_MESSAGE", { ttl: 5000, disableCountDown: false, onclose: function () { $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated); } }); } } } else { //redirect back to url in search param and remove the existing search param $location.path(returnUrl).search(''); } //reset the wrapper top margin to fit the header $(".wrapper").css("margin-top", "5px"); $("#ngViewWrapper").css("min-height", "calc(100vh - 5px)"); headerSizeIntervalId = setInterval(function () { var headerHeight = $("#TopNavBar").css("height"); if (headerHeight != "0px") { $(".wrapper").css("margin-top", "calc(" + headerHeight + " - 47px"); $("#ngViewWrapper").css("min-height", "calc(100vh - " + headerHeight + ")"); } }, 10000); }); $rootScope.$on(AUTH_EVENTS.logoutSuccess, function () { //clear cache docLinkWebCache.removeAll(); $rootScope.IsAuthenticated = false; //stop the messaging service MessagingService.Unsubscribe(); //redirect to the Logout View so that the Angular app will completely unload and autologin will be halted var currentLocation = $window.location.href.split("#"); var newLocation = currentLocation[0].replace("/Home/IndexAnon", "").replace("/Home/Index", ""); newLocation += "/Home/Logout"; $window.location.href = newLocation; //stop watching the header size clearInterval(headerSizeIntervalId); }); $rootScope.$on(AUTH_EVENTS.notAuthenticated, function () { console.log("AUTH_EVENTS.notAuthenticated"); //no cached login info, so go to login page $rootScope.IsAuthenticated = false; // stop the watch Idle.unwatch(); var returnUrl = $location.url(); //console.log("returnUrl = " + returnUrl); if (returnUrl && returnUrl !== "/" && returnUrl.indexOf("/?returnUrl") === -1) { $location.path('/').search('returnUrl=' + returnUrl); } else { $location.path('/').search(''); } }); $rootScope.$on(AUTH_EVENTS.sessionTimeout, function () { console.log("AUTH_EVENTS.sessionTimeout"); $rootScope.serverMessage = $translate.instant("SESSIONTIMEDOUT_MESSAGE"); //"Session Timed out due to inactivity"; //get the current page and redirect to log with this page as the return url $rootScope.manualLogout = false; $rootScope.IsAuthenticated = false; //stop the messaging service MessagingService.Unsubscribe(); SecurityService.logout(); //disconnect session from Session Monitor $timeout(function () { var returnUrl = $location.url(); if (returnUrl && returnUrl !== "/" && returnUrl.indexOf("/?returnUrl") === -1) { $location.path('/').search('returnUrl=' + returnUrl); } else { $location.path('/').search(''); } }); //stop watching the header size clearInterval(headerSizeIntervalId); }); $rootScope.$on(AUTH_EVENTS.notAuthorized, function () { console.log("AUTH_EVENTS.notAuthorized"); var url = $location.url(); $rootScope.serverMessage = $translate.instant("NOTAUTHORIZED_MESSAGE", { page: url }); //log this security exception var error = new Error("Security Exception: User tried to access [" + url + "], but does not have access"); errorLogService(error); $timeout(function () { //get the current page and redirect to log with this page as the return url $rootScope.manualLogout = true; //this ensures that the user isn't automatically logged in again without ever seeing the message $rootScope.IsAuthenticated = false; SecurityService.logout(); //disconnect session from Session Monitor $location.path('/').search(''); //no return page because that page would be the one that caused this exception in the first place }, 1000); }); $rootScope.$on(AUTH_EVENTS.serviceNotAvailable, function () { //console.log("AUTH_EVENTS.serviceNotAvailable"); $rootScope.serverMessage = $translate.instant("SERVICESNOTAVAILABLE_MESSAGE"); var url = $location.url(); $location.path('/').search('returnUrl=' + url); }); //#endregion //#region $route and $location events $rootScope.$on('$routeChangeStart', function (event, next, current) { //console.log("$routeChangeStart from " + ((current && current.templateUrl) ? current.templateUrl : "") + " to " + next.templateUrl); if ((!SessionFactory.GetAuthcode() || SessionFactory.GetAuthcode() === "") && $location.path() !== '/') { $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated); } else if (next && next.access) { if (next.access.requiredRoles !== undefined && $.inArray($rootScope.CurrentUserRole, next.access.requiredRoles) === -1) { $rootScope.$broadcast(AUTH_EVENTS.notAuthorized); } } }); var lastSection = $rootScope.CurrentSection; $rootScope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl, newState, oldState) { $rootScope.CurrentSection = ""; $rootScope.CurrentProgId = ""; $rootScope.PreviousLocation = oldUrl; //find current section if (newUrl.indexOf("/quicksearch") > -1) { $rootScope.CurrentSection = "QuickSearch"; if (newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "QuickSearchViewer"; } $rootScope.CurrentProgId = "QuickInquiry"; } if (newUrl.indexOf("/advancedSearch") > -1) { $rootScope.CurrentSection = "AdvancedSearch"; if (newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "AdvancedSearchViewer"; } $rootScope.CurrentProgId = "AdvancedInquiry"; } if (newUrl.indexOf("/fulltext") > -1) { $rootScope.CurrentSection = "FullTextSearch"; if (newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "FullTextSearchViewer"; } $rootScope.CurrentProgId = "FullTextSearch"; } if (newUrl.indexOf("/workflow") > -1) { $rootScope.CurrentSection = "Workflow"; if (newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "WorkflowViewer"; } $rootScope.CurrentProgId = "WorkflowInquiry"; } if (newUrl.indexOf("/searchByProperty/ID") > -1) { $rootScope.CurrentSection = "SearchByID"; if (newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "SearchByIDViewer"; } } if (newUrl.indexOf("/searchByProperty/Properties") > -1) { $rootScope.CurrentSection = "SearchByProperty"; if (newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "SearchByPropertyViewer"; } } if (newUrl.indexOf("/searchByProperty/Annotations") > -1) { $rootScope.CurrentSection = "SearchByAnnotation"; if (newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "SearchByAnnotationViewer"; } } if (newUrl.indexOf("/portal") > -1) { $rootScope.CurrentSection = "Portal"; if (newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "PortalViewer"; } $rootScope.CurrentProgId = "QuickInquiry"; } if (newUrl.indexOf("/smartform") > -1) { $rootScope.CurrentSection = "SmartFormClientTab"; } if ($rootScope.CurrentSection === "" && newUrl.indexOf("/viewer") > -1) { $rootScope.CurrentSection = "StandaloneViewer"; } if (newUrl.indexOf("/versioncontrol") > -1) { $rootScope.CurrentSection = "VersionControl"; } lastSection = $rootScope.CurrentSection; //scroll window back to top $window.scrollTo(0, 0); }); //#endregion $route and $location events //#region "Idle" $rootScope.$on('IdleStart', function () { // the user appears to have gone idle console.log("user has gone idle: " + new Date()); modalService.showModal({ templateUrl: "tpl.SessionTimeoutDialog.html" }, { closeButtonText: $translate.instant("NOSIGNOUT"), actionButtonText: $translate.instant("YESSTAYSIGNEDIN"), headerText: $translate.instant("SESSIONEXPIRING") }).then(function (result) { //console.log(JSON.stringify(result)); //if (result) { // $rootScope.ResetTimeout(); //} else { // $rootScope.logout(); //} }, function (response) { console.log(response); }); }); $rootScope.$on('IdleWarn', function (e, countdown) { // follows after the IdleStart event, but includes a countdown until the user is considered timed out // the countdown arg is the number of seconds remaining until then. // you can change the title or display a warning dialog from here. // you can let them resume their session by calling Idle.watch() console.log("logging user out in " + countdown + ": " + new Date()); $timeout(function () { $rootScope.sessionTimeoutSecondsRemaining = countdown; }); }); $rootScope.$on('IdleTimeout', function () { // the user has timed out (meaning idleDuration + timeout has passed without any activity) // this is where you'd log them console.log("logging user out: " + new Date()); //$('#sessionTimeoutDialog').modal('hide'); modalService.hide(); $rootScope.serverMessage = $translate.instant("SESSIONTIMEDOUT_MESSAGE"); //get the current page and redirect to log with this page as the return url $rootScope.manualLogout = false; $rootScope.IsAuthenticated = false; //stop the messaging service MessagingService.Unsubscribe(); //disconnect session from Session Monitor SecurityService.logout().then(function () { SessionFactory.ClearCredentials(); $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated); }, function () { //reload window and reset everything if the logout failed $window.location.reload(); }); }); $rootScope.$on('IdleEnd', function () { // the user has come back from AFK and is doing stuff. if you are warning them, you can use this to hide the dialog console.log("session recovered"); //$('#sessionTimeoutDialog').modal('hide'); modalService.hide(); }); //#endregion "Idle" }]); (function (window, $) { $(function () { //mega dropdown links don't close the menu, unless they're decorated with the dropdown-toggle class $(document).on('click', '.mega-dropdown a', function (event) { if (!$(this).hasClass("dropdown-toggle")) { event.stopPropagation(); } }); window.addEventListener("beforeunload", endSession, false); if ("onpagehide" in window) { window.addEventListener("pagehide", endSession, false); } function endSession() { var authcode = $("#AuthCode").val(); var serviceUrl = $("#WebServiceUrl").val(); localStorage.removeItem('authCode'); $.ajax({ type: "POST", url: serviceUrl + "Security/Logout", headers: { 'authCode': authcode }, async: false }); //disable this feature because it can't be fully supported in a tablet, yet //var keepSessionAfterClosingBrowser = $("#KeepSessionAfterClosingBrowser").val(); //if (authcode !== "" && keepSessionAfterClosingBrowser == "false") { // localStorage.removeItem('authCode'); // $.ajax({ // type: "POST", // url: serviceUrl + "Security/Logout", // headers: { 'authCode': authcode }, // async: false // }); //} else if (authcode !== "" && keepSessionAfterClosingBrowser == "true") { // $.ajax({ // type: "POST", // url: serviceUrl + "Security/TurnInLicenses", // headers: { 'authCode': authcode }, // async: false // }); //} } }); })(window, jQuery); (function () { 'use strict'; angular.module('Document').service('DocumentService', ['$rootScope', '$http', '$q', 'SessionFactory', 'PropertyService', '$uibModal', 'LocalStorageService', 'LibraryFunctions', 'growl', 'AnnotationService', 'modalService', '$translate', 'StateService', documentService]); function documentService($rootScope, $http, $q, SessionFactory, PropertyService, $uibModal, LocalStorageService, LibraryFunctions, growl, AnnotationService, modalService, $translate, StateService) { //return public API return ({ DocumentInfo: DocumentInfo, GetThumb: GetThumb, GetPage: GetPage, GetDocumentNotes: GetDocumentNotes, DeleteDocuments: DeleteDocuments, DocumentMetaData: DocumentMetaData, GetIndexProperties: GetIndexProperties, SaveDirtyProperties: SaveDirtyProperties, AddNote: AddNote, EmailDocuments: EmailDocuments, SetPriority: SetPriority, CheckOutDocument: CheckOutDocument, CheckInDocument: CheckInDocument, UndoCheckOutDocument: UndoCheckOutDocument, ShowDocumentVersions: ShowDocumentVersions, DownloadVersion: DownloadVersion, GetCheckedOutDocuments: GetCheckedOutDocuments, GetDocumentTypesForTopLevelFolder: GetDocumentTypesForTopLevelFolder, GetPropertiesListForDocumentType: GetPropertiesListForDocumentType, GetDocumentTypesByTLFANDPermission: GetDocumentTypesByTLFANDPermission, GetDirtyProperties: getDirtyProperties, GetDirtyAnnotations: getDirtyAnnotations, IsDirty: documentIsDirty, SaveChanges: saveChanges }); function getDirtyProperties(document) { if (!document || !document.PageModels) { return false; } //no changes for readonly documents if (document.DocumentStatus === 5) { return false; } var dirtyProperties = []; if (document.IndexPropertyInfo && document.IndexPropertyInfo.length > 0) { dirtyProperties = $.grep(document.IndexPropertyInfo, function (property) { return property.IsDirty === true; }); } return dirtyProperties; } function getDirtyAnnotations(document) { if (!document || !document.PageModels || !_.isArray(document.PageModels)) { return false; } //no changes for readonly documents if (document.DocumentStatus === 5) { return false; } var dirtyAnnotations = []; //save current page info $.each(document.PageModels, function (index, page) { if (page.Annotations && page.Annotations !== null) { $.each(page.Annotations, function (index, annotation) { if (annotation.IsDirty) { annotation.Page = page.Number; annotation.PageDPI = page.PageDPI; dirtyAnnotations.push(annotation); } }); } }); return dirtyAnnotations; } function documentIsDirty(document) { if (!document || !document.PageModels) { return false; } //no changes for readonly documents if (document.DocumentStatus === 5) { return false; } if (document.PagesAreDirty === true || this.GetDirtyProperties(document).length > 0 || this.GetDirtyAnnotations(document).length > 0) { return true; } return false; } function saveDirtyProperties(documentID, dirtyProperties) { var defer = $q.defer(); $http({ method: "put", url: SessionFactory.GetServiceUrl() + "Document/SaveDirtyProperties", data: { "DocumentId": documentID, "DirtyProperties": dirtyProperties } }).success(function (response) { //add position to the properties for proper sort order var masterProperty = null; $.each(response, function (propIndex) { masterProperty = _.find($rootScope.MasterProperties, function (p) { return p.propertyID === response[propIndex].propertyId; }); response[propIndex].position = parseInt(masterProperty.position, 10); }); defer.resolve(response); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); }); return defer.promise; } // --- // PUBLIC METHODS. // --- function beforeSaveChanges(document, saveWithoutPrompt) { var defer = $q.defer(); saveWithoutPrompt = saveWithoutPrompt || false; var saveMessages = []; if (getDirtyAnnotations(document).length > 0) { saveMessages.push($translate.instant("VIEWER_UNSAVEDANNOTATIONS_MESSAGE")); console.log("Save the changes to the annotation(s) to this document?"); } if (document.PagesAreDirty === true) { console.log("Save changes to the document image?"); saveMessages.push($translate.instant("VIEWER_UNSAVEDDOCUMENTCHANGES_MESSAGE")); } if (getDirtyProperties(document).length > 0) { console.log("Save the changes to the data associated with this document?"); saveMessages.push($translate.instant("VIEWER_UNSAVEDPROPERTIES_MESSAGE")); } if (StateService.HasUnsavedChanges()) { console.log("Save changes to the smart form?"); saveMessages.push($translate.instant("UNSAVED_SMARTFORMS_MESSAGE")); } if (saveMessages.length === 0) { console.log("There is nothing to save for document " + document.DocumentID); defer.resolve(false); // no need to continue the same } else { if (saveWithoutPrompt === true) { defer.resolve(true); } else { modalService.showModal({}, { closeButtonText: $translate.instant("GLOBAL_NO"), actionButtonText: $translate.instant("GLOBAL_YES"), headerText: $translate.instant("VIEWER_UNSAVEDCHANGES_HEADER"), bodyText: $translate.instant("SYSTEMPROPERTY_DOCUMENTID") + ": " + document.DocumentID + "
" + saveMessages.join("
") }).then(function (result) { defer.resolve(result); }, function (response) { console.log(response); defer.reject(response); }); } } return defer.promise; } function saveChanges(document, saveWithoutPrompt) { var defer = $q.defer(); saveWithoutPrompt = saveWithoutPrompt || false; console.log("saveChanges", document); if ($rootScope.IsAuthenticated === false) { defer.reject(); } else { beforeSaveChanges(document, saveWithoutPrompt).then(function (continueSaving) { if (continueSaving === false) { //reset state StateService.ClearState(); defer.resolve(true); } else { //here because beforeSaveChanges returned a true that we should continue the save var savePagesRequest = function () { var defer = $q.defer(); if (document.PagesAreDirty === true) { var documentChanges = {}; documentChanges.DocumentID = document.DocumentID; documentChanges.Pages = []; $.each(document.PageModels, function (index, page) { var pageModel = {}; pageModel.pageNumber = page.Number; pageModel.oldPageNumber = page.OriginalNumber; if (page.Rotation && page.Rotation !== 0) { pageModel.rotation = page.Rotation; } documentChanges.Pages.push(pageModel); }); //add the document changes promise $http({ method: "post", url: SessionFactory.GetServiceUrl() + "Document/SaveChanges", data: documentChanges }).then(function () { growl.success("VIEWER_DOCUMENTCHANGES_SAVED_SUCCESSMESSAGE", { ttl: 5000, disableCountDown: true }); document.PagesAreDirty = false; defer.resolve(); }); } else { defer.resolve(); } return defer.promise; }; var saveAnnotationsRequest = function () { var defer = $q.defer(); //check for dirty annotations var dirtyAnnotations = getDirtyAnnotations(document); if (dirtyAnnotations.length > 0) { //bump the Standard Stamp over to the left 4 pixels and up 2.5 pixels //because fabric automaticlaly pads the text area whereas TiffHelper does not //(found these numbers by comparing the results in the DocumentAnnotations table) $.each(dirtyAnnotations, function (idx) { if (dirtyAnnotations[idx].Type === "StandardStamp") { dirtyAnnotations[idx].x1 -= (4 / dirtyAnnotations[idx].PageDPI); dirtyAnnotations[idx].x2 += (4 / dirtyAnnotations[idx].PageDPI); dirtyAnnotations[idx].y1 -= (2.5 / dirtyAnnotations[idx].PageDPI); dirtyAnnotations[idx].y2 += (2.5 / dirtyAnnotations[idx].PageDPI); } }); AnnotationService.SaveAnnotations(document.DocumentID, dirtyAnnotations).then(function () { return $http({ method: "get", url: SessionFactory.GetServiceUrl() + "Document/DocumentMetaData?documentId=" + document.DocumentID + "&metaDataToLoad=128" }); }).then(function (metadata) { //update the annotations collection $.each(document.PageModels, function (index, page) { document.PageModels[index].Annotations = metadata.data.AnnotationSummary.filter(function (a) { return a.Page === page.Number; }); }); growl.success("VIEWER_ANNOTATIONCHANGES_SAVED_SUCCESSMESSAGE", { ttl: 5000, disableCountDown: true }); defer.resolve(); }); } else { defer.resolve(); } return defer.promise; }; var savePropertiesRequest = function () { var defer = $q.defer(); //check for dirty properties var dirtyProperties = getDirtyProperties(document); if (dirtyProperties.length > 0) { saveDirtyProperties(document.DocumentID, dirtyProperties).then(function (properties) { growl.success("VIEWER_PROPERTYYCHANGES_SAVED_SUCCESSMESSAGE", { ttl: 5000, disableCountDown: true }); document.IndexPropertyInfo = properties; document.PropertiesAreDirty = false; defer.resolve(); }); } else { defer.resolve(); } return defer.promise; }; var saveSmartformsRequest = function () { var defer = $q.defer(); //check for dirty properties console.log("StateService.HasUnsavedChanges() in beforeSaveChanges", StateService.HasUnsavedChanges()); if (StateService.HasUnsavedChanges()) { StateService.SaveState().then(function () { growl.success("VIEWER_SMARTFORMS_SAVED_SUCCESSMESSAGE", { ttl: 5000, disableCountDown: true }); //reset state StateService.ClearState(); defer.resolve(); }); } else { //reset state StateService.ClearState(); defer.resolve(); } return defer.promise; }; //run the requests in serial so any image manipulation from one request doesn't get ovcerwritten by another savePagesRequest().then(function () { return saveAnnotationsRequest(); }).then(function () { return savePropertiesRequest(); }).then(function () { return saveSmartformsRequest(); }).then(function () { $rootScope.$broadcast("DocumentImageChanged", { "documentid": document.DocumentID, "showLastPage": LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.DISPLAYLASTPAGEOFMULTIPAGEDOCUMENTS) }); //we won't get responses because they're already being resolved, but we will know when they're all complete defer.resolve(true); }, function (failResponses) { //not catch errors above, so they'll all come here defer.reject(failResponses); }); } }, function (promptError) { defer.reject(promptError); }); } return defer.promise; } function GetDocumentTypesByTLFANDPermission(DLFolderID, permissionName) { var defer = $q.defer(); $http({ method: "post", url: SessionFactory.GetServiceUrl() + "DocumentType/GetDocTypesByFolderAndPermission", data: { "TopLevelFolderId": DLFolderID, "PermissionName": permissionName } }).success(function (response) { defer.resolve(response); }).error(function () { defer.reject({ message: "Error Loading Document Types" }); }); return defer.promise; } function GetPropertiesListForDocumentType(documentTypeId) { var defer = $q.defer(); //find the property type var documentTypeProperties = []; var documentType = null; $.each($rootScope.DocumentTypes, function (index, docType) { if (docType.documentTypeID === parseInt(documentTypeId, 10)) { documentType = docType; } }); if (documentType === null) { defer.reject("Invalid Document Type Id: " + documentTypeId); } else { //if the property type already has cached properties if (angular.isDefined(documentType.properties) && documentType.properties !== null && documentType.properties.length > 0) { documentTypeProperties = $.extend([], documentType.properties); defer.resolve(_.sortBy(documentTypeProperties, 'position')); } else { $http({ method: "get", url: SessionFactory.GetServiceUrl() + "Property/PropertiesForDocumentType?documentTypeId=" + documentTypeId }).success(function (response) { //add position to the properties for proper sort order var masterProperty = null; $.each(response, function (propIndex) { masterProperty = _.find($rootScope.MasterProperties, function (p) { return p.propertyID === response[propIndex].propertyID; }); response[propIndex].position = parseInt(masterProperty.position, 10); }); documentType.properties = _.sortBy(response, 'position'); defer.resolve(response); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); }); } } return defer.promise; } function GetDocumentTypesForTopLevelFolder(topLevelFolderId) { var defer = $q.defer(); $http({ method: "put", url: SessionFactory.GetServiceUrl() + "DocumentType/DocumentTypes", data: { "topLevelFolders": [{ "folderID": topLevelFolderId }], "selectedDocTypes": [] } }).success(function (response) { defer.resolve(response); }).error(function () { defer.reject({ message: "Error Loading Document Types" }); }); return defer.promise; } function GetCheckedOutDocuments() { var defer = $q.defer(); $http({ method: "post", url: SessionFactory.GetServiceUrl() + "Document/Checkouts" }).success(function (response) { defer.resolve(response); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); }); return defer.promise; } function DownloadVersion(document, versionid) { $http({ method: "get", url: SessionFactory.GetServiceUrl() + "Document/DownloadFileVersion/" + document.DocumentID + "?version=" + versionid + "&authcode=" + window.escape(LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.AUTHCODE)), responseType: "blob" }).success(function (blob, status, headers) { //defer.resolve(response); let contentType = headers("Content-Type"); let contentDisposition = headers("Content-Disposition"); let imageFileName = contentDisposition.replace("attachment; filename=", "").replace(/"/g, ''); if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, imageFileName); } else { const data = window.URL.createObjectURL(blob); var link = window.document.createElement('a'); link.href = data link.download = imageFileName; window.document.body.appendChild(link); link.click(); // For Firefox it is necessary to delay revoking the ObjectURL setTimeout(function () { window.URL.revokeObjectURL(data); }, 100); } }).error(function (error) { //defer.reject({ message: "Error Loading Page Source" }); console.log("error"); }); } function CheckOutDocument(document) { var defer = $q.defer(); $http({ method: "post", url: SessionFactory.GetServiceUrl() + "Document/Checkout", data: { "DocumentId": document.DocumentID } }).success(function (response) { defer.resolve(response); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); }); return defer.promise; } function CheckInDocument(document) { var defer = $q.defer(); var modalInstance = $uibModal.open({ animation: true, templateUrl: "tpl.DocumentVersions_Checkin_template.html", size: "md", controller: ['$scope', '$uibModalInstance', function ($scope, $modalInstance) { $scope.CheckinComment = ""; //$scope.FileData = null; $scope.FileName = ""; $scope.acceptedfiletypes = "." + (document.NativeFileType)? document.NativeFileType : "*"; $scope.CheckIn = function () { //FILL FormData WITH FILE DETAILS. var fd = new FormData(); fd.append("uploadedFile", $scope.FileData); fd.append("DocumentId", document.DocumentID); fd.append("Comment", $scope.CheckinComment); $http({ method: "POST", url: SessionFactory.GetServiceUrl() + "Document/Checkin", data: fd, transformRequest: angular.identity, headers: { 'Content-Type': undefined } }).success(function (response) { defer.resolve(true); $modalInstance.close(); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); $modalInstance.close(); }); }; $scope.SetVersionFileData = function (e) { $scope.FileData = e.files[0]; $scope.FileName = e.files[0].name; $scope.$apply(); }; $scope.CloseModal = function () { defer.resolve(false); $modalInstance.close(); }; }] }); return defer.promise; } function UndoCheckOutDocument(document) { var defer = $q.defer(); $http({ method: "post", url: SessionFactory.GetServiceUrl() + "Document/UndoCheckout", data: { "DocumentId": document.DocumentID } }).success(function (response) { defer.resolve(response); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); }); return defer.promise; } function ShowDocumentVersions(document) { var modalInstance = $uibModal.open({ animation: true, templateUrl: "tpl.DocumentVersions_template.html", size: "md", //scope: $scope, controller: ['$scope', '$uibModalInstance', function ($scope, $modalInstance) { $scope.Versions = []; $scope.SelectedVersion = null; $http({ method: "post", url: SessionFactory.GetServiceUrl() + "Document/Versions", data: { "DocumentId": document.DocumentID } }).success(function (response) { $.each(response, function (i) { response[i].CheckedInDate = LibraryFunctions.parseDate(response[i].CheckedInDate, "L LT") }); $scope.Versions = response; }).error(function (response, status) { //defer.reject({ "response": response, "status": status }); }); $scope.DownloadVersion = function (version) { DownloadVersion(document, version.VersionId); }; $scope.SetSelectedVersion = function (version) { $scope.SelectedVersion = version; }; $scope.CloseModal = function () { $modalInstance.close(); }; }] }); } function AddNote(documentID, type, text) { var defer = $q.defer(); $http({ method: "post", url: SessionFactory.GetServiceUrl() + "Document/Note", data: { "DocumentId": documentID, "NoteType": type, "Text": text } }).success(function (response) { defer.resolve(response); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); }); return defer.promise; } function SaveDirtyProperties(documentID, dirtyProperties) { var defer = $q.defer(); $http({ method: "put", url: SessionFactory.GetServiceUrl() + "Document/SaveDirtyProperties", data: { "DocumentId": documentID, "DirtyProperties": dirtyProperties } }).success(function (response) { //add dataTypes to the Index Property collection for formatting in the tree displays $.each(response, function (idx, property) { PropertyService.GetPropertyById(property.propertyId).then(function (masterProperty) { property.dataType = masterProperty.dataType; property.position = parseInt(masterProperty.position, 10); property.IsDirty = false; }); }); defer.resolve(response); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); }); return defer.promise; } function GetDocumentNotes(documentId) { var defer = $q.defer(); $http({ method: "get", url: SessionFactory.GetServiceUrl() + "Document/Notes?id=" + documentId }).success(function (response) { defer.resolve(response); }).error(function () { defer.reject({ message: "Error Loading document notes" }); }); return defer.promise; } //get thumbnail as base64 image function GetThumb(documentId, pageNum) { var request = $http({ method: "get", url: SessionFactory.GetServiceUrl() + "DocumentImage/Thumb?id=" + documentId + "&page=" + pageNum + "&maxHeight=200&maxWidth=200" }); return (request.then(function (base64image) { //console.log(base64image); return base64image.data; }, handleError)); } //get page as base64 image function GetPage(documentId, pageNum) { var defer = $q.defer(); $http({ method: "get", url: SessionFactory.GetServiceUrl() + "DocumentImage/Page?id=" + documentId + "&page=" + pageNum }).success(function (response) { defer.resolve(response); }).error(function () { defer.reject({ message: "Error Loading Page Source" }); }); return defer.promise; } function DocumentInfo(DocumentId, MaxThumbHeight, MaxThumbWidth, MetaDataToLoad, displayLastPageOfMultiPageDocuments, fullrefresh) { var defer = $q.defer(); $http({ method: "get", url: SessionFactory.GetServiceUrl() + "DocumentImage/GetDocumentData?documentId=" + DocumentId + "&maxThumbHeight=" + MaxThumbHeight + "&maxThumbWidth=" + MaxThumbWidth + "&metaDataToLoad=" + MetaDataToLoad + "&displayLastPageOfMultiPageDocuments=" + displayLastPageOfMultiPageDocuments + "&forceRefresh=" + fullrefresh }).success(function (response) { //response.DocumentImageWasLoadedSuccessfully = true; //add dataTypes to the Index Property collection for formatting in the tree displays if (response.IndexPropertyInfo) { $.each(response.IndexPropertyInfo, function (idx, property) { PropertyService.GetPropertyById(property.propertyId).then(function (masterProperty) { property.dataType = masterProperty.dataType; property.IsDirty = false; }); }); } //set some things to not null, so the document refresh doesn't cause the displays directives to the attempt to load "missing" data if (!response.AnnotationSummary) { response.AnnotationSummary = []; } if (!response.Notes) { response.Notes = []; } response.PropertiesAreDirty = false; response.PagesAreDirty = false; response.CurrentPageNumber = 1; defer.resolve(response); }).error(function (response, status) { defer.reject({ "response": response, "status": status }); }); return defer.promise; } function DocumentMetaData(DocumentId, metaDataFlags) { var defer = $q.defer(); $http({ method: "get", url: SessionFactory.GetServiceUrl() + "Document/DocumentMetaData?documentId=" + DocumentId + "&metaDataToLoad=" + metaDataFlags }).success(function (response) { if (response.IndexPropertyInfo && response.IndexPropertyInfo !== null) { var masterProperty = null; //_.find($rootScope.MasterProperties, function (p) { return p.propertyID == property.propertyId; }); $.each(response.IndexPropertyInfo, function (propIndex) { masterProperty = _.find($rootScope.MasterProperties, function (p) { return p.propertyID === response.IndexPropertyInfo[propIndex].propertyId; }); if (masterProperty) { response.IndexPropertyInfo[propIndex].position = parseInt(masterProperty.position, 10); } else { response.IndexPropertyInfo[propIndex].position = 9999; //push to the end. Unlikely to have more than 10000 properties, but then again Bill Gates thought 640K was an upper limit, too. } }); response.IndexPropertyInfo = _.sortBy(response.IndexPropertyInfo, 'position'); } defer.resolve(response); }).error(function (response, status) { //alert("rejecting response from Document Inquiry: \nStatus: " + status); defer.reject({ "response": response, "status": status }); }); return defer.promise; } function GetIndexProperties(DocumentId) { var defer = $q.defer(); $http({ method: "get", url: SessionFactory.GetServiceUrl() + "Document/IndexProperties?id=" + DocumentId }).success(function (response) { defer.resolve(response); }).error(function (response, status) { //alert("rejecting response from Document Inquiry: \nStatus: " + status); defer.reject({ "response": response, "status": status }); }); return defer.promise; } function DeleteDocuments(documentIds) { var defer = $q.defer(); $http({ method: "delete", url: SessionFactory.GetServiceUrl() + "Document/DeleteDocuments", data: { DocumentIDs: documentIds } }).success(function (response) { defer.resolve(response); }).error(function (response, status) { //alert("rejecting response from Document Inquiry: \nStatus: " + status); defer.reject({ "response": response, "status": status }); }); return defer.promise; } function EmailDocuments(to, from, subject, body, appendNotes, documents, emailTiffFormat) { var defer = $q.defer(); var SendImageEmailModel = {}; SendImageEmailModel.emailDocFrom = from; SendImageEmailModel.emailDocTo = to; SendImageEmailModel.emailDocSubject = subject; SendImageEmailModel.emailDocBody = body; SendImageEmailModel.documentIDs = $.map(documents, function (document) { return document.DocumentID; }); SendImageEmailModel.appendNotes = appendNotes; SendImageEmailModel.emailTiffFormat = emailTiffFormat; $http({ method: "post", url: SessionFactory.GetServiceUrl() + "DocumentImage/Email", data: SendImageEmailModel }).success(function (response) { defer.resolve(response); }).error(function (response, status) { //alert("rejecting response from Document Inquiry: \nStatus: " + status); defer.reject({ "response": response, "status": status }); }); return defer.promise; } function SetPriority(documentId, isPriority) { var defer = $q.defer(); $http({ method: "put", url: SessionFactory.GetServiceUrl() + "Workflow/WorkflowDocumentPriority", data: { "DocumentID": documentId, "Priority": isPriority } }).success(function (response) { //console.log("success response in WorkflowService: " + JSON.stringify(response)); defer.resolve(response); }).error(function (response) { //console.log("error response in WorkflowService: " + JSON.stringify(response)); defer.reject({ message: response.Message }); }); return defer.promise; } // I transform the error response, unwrapping the application dta from // the API response payload. function handleError(response) { //alert(JSON.stringify(response)); // The API response from the server should be returned in a // nomralized format. However, if the request was not handled by the // server (or what not handles properly - ex. server error), then we // may have to normalize it on our end, as best we can. if ( !angular.isObject(response.data) || !response.data.message ) { return ($q.reject("An unknown error occurred.")); } // Otherwise, use expected error message. return ($q.reject(response.data.message)); } } })(); (function () { 'use strict'; var app = angular.module('docLinkWeb'); // The "stacktrace" library that we included in the Scripts // is now in the Global scope; but, we don't want to reference // global objects inside the AngularJS components - that's // not how AngularJS rolls; as such, we want to wrap the // stacktrace feature in a proper AngularJS service that // formally exposes the print method. app.factory( "stacktraceService", function () { var callback = function (frames) { console.log(frames); }; var errback = function (err) { console.log(err.message); }; return ({ print: function (exception) { var deferred = $.Deferred(); StackTrace.fromError(exception.e).then(function (trace) { deferred.resolve(trace); }).catch(errback); return deferred.promise(); } }); } ); // The error log service is our wrapper around the core error // handling ability of AngularJS. Notice that we pass off to // the native "$log" method and then handle our additional // server-side logging. app.factory( "errorLogService", ["$log", "$window", "stacktraceService", "LocalStorageService", "$rootScope", function ($log, $window, stacktraceService, LocalStorageService, $rootScope) { // I log the given error to the remote server. function log(exception, cause) { // Pass off the error to the default error handler // on the AngualrJS logger. This will output the // error to the console (and let the application // keep running normally for the user). $log.error.apply($log, arguments); // Now, we need to try and log the error the server. try { var errorMessage = exception.toString(); stacktraceService.print({ e: exception }).then(function (stackTrace) { $.ajax({ type: "POST", url: $rootScope.WebAPIEndpoint + "./ErrorLog/LogException", contentType: "application/json", data: angular.toJson({ errorUrl: $window.location.href, errorMessage: errorMessage, stackTrace: "\n\tat " + stackTrace.join("\n\tat "), cause: (cause || ""), currentUser: $rootScope.CurrentUser }) }); }); } catch (loggingError) { // For Developers - log the log-failure. $log.warn("Error logging failed"); $log.log(loggingError); } } // Return the logging function. return (log); }] ); // By default, AngularJS will catch errors and log them to // the Console. We want to keep that behavior; however, we // want to intercept it so that we can also log the errors // to the server for later analysis. app.provider( "$exceptionhandler", { $get: ["errorLogService", function (errorlogservice) { return (errorlogservice); }] } ); })(); (function () { 'use strict'; var app = angular.module('docLinkWeb'); app.service('FileUploadService', ['$http', '$q', 'SessionFactory', 'LocalStorageService', fileUploadService]); function fileUploadService($http, $q, SessionFactory, LocalStorageService) { return ({ UploadFiles: uploadFiles, GetUploadFilePage: getUploadFilePage }); function uploadFiles(filesArray) { var defer = $q.defer(); //FILL FormData WITH FILE DETAILS. var fd = new FormData(); for (var i in filesArray) { fd.append("uploadedFile", filesArray[i]); } $http({ method: "POST", url: SessionFactory.GetServiceUrl() + "Files/Upload", data: fd, transformRequest: angular.identity, headers: { 'Content-Type': undefined } }).then(function (response) { defer.resolve(response); }, function (response) { defer.reject(response); }); return defer.promise; } function getUploadFilePage(fileId, pageIndex) { var defer = $q.defer(); $http({ method: "GET", url: SessionFactory.GetServiceUrl() + "Files/GetFilePage?FileId=" + fileId + "&pageIndex=" + pageIndex, data: {}, }).then(function (response) { defer.resolve(response); }, function (response) { defer.reject(response); }); return defer.promise; } } })(); (function () { 'use strict'; angular.module('LocalStorage').service('LocalStorageService', [LocalStorageService]); function LocalStorageService() { //var LocalStorageService = {}; var PropertyDefaults = { //lang: "en", culture: "en-US", traceErrors: false, quickSearchRunFirst: "none", restrictPropertiesToCommon: false, systemPropertiesVisibleArray: "", wfResultsPropertiesVisibleArray: "", displaygroupbybox: false, combinedPrinting: false, maxDocSearch: 1000, savedProfiles: [], serviceUrl: "", smartFormsServiceUrl: "", userName: "", loginId: "", email: "", userDescription: "", role: "", authCode: "", topLevelFolderSingular: "", topLevelFolderPlural: "", topLevelFolders: [], documentTypes: [], //topLevelFoldersDocumentTypeCrosswalk: [], UserDefinedPropertyColumnOrder: [], ThumbnailSize: "none", ResultsViewStyle: "grid", ItemsPerPage: 20, //OrderBy: "DocumentID;asc", EmailTiffFormat: "pdf", TextMatching: "wildcards", DateMatching: "individual", EnableSearchByPropertyPopup: true, RememberViewSettings: false, DisplayNewestPropertyForMultiValueProperties: false, authCode_lastAccessed: new Date(0, 0, 0, 0, 0, 0, 0), visible_viewer_sections: "details,notes", ResetSendStatusAfterSend: false, WFDisplayGroupbyBox: false, WFDisplayNewestPropertyForMultiValueProperties: false, AutomaticallyOpenSupportingDocuments: true, AutomaticallyOpenFirstWorkflowDocument: true, maxSuppDocs: 5, WFMaxResults: 100, CacheQuickSearches: false, CacheSavedSearches: false, CacheTopLevelFolders: false, CacheDocumentTypes: false, CacheWorkflows: false, savedsearches: [], workflows: [], quicksearches: [], rolePermissions: [], hasWorkflowPermission: false, hasQuickSearchflowPermissions: false, Viewer_ShowAnnotations: false, Viewer_ShowThumbnails: false, AllowSearchResultsFiltering: false, WFAllowSearchResultsFiltering: false, SmartFormsSettings: JSON.stringify({ "CustomSettings": { "showBurnWarning": true } }), SearchTypeColumnDisplay: 'text', DisplayLastPageOfMultiPageDocuments: false, LastViewedDistributionStampDefinition: "", ViewerSectionSizes: null, ViewerWindowLayout: 'maximized', ViewerDefaultZoom: 'FitToWidth', //fit to width by default. Different than Smart Client per Merri jo. WFDefaultSort: JSON.stringify([{ "Level": 0, "ColumnName": "Received", "SortOrder": 0 }]), InquiryDefaultSort: JSON.stringify([{ "Level": 0, "ColumnName": "DocumentID", "SortOrder": 0 }]), }; //return public API return ({ GetProperty: GetProperty, SetProperty: SetProperty, ResetProperty: resetProperty, ClearSettings: ClearSettings, //setLocalStorageProperty: setLocalStorageProperty, //getLocalStorageProperty: getLocalStorageProperty, //setSessionStorageProperty: setSessionStorageProperty, //getSessionStorageProperty: getSessionStorageProperty, DeletePropertyFromLocalStorage: DeletePropertyFromLocalStorage, WipeSessionStorage: WipeSessionStorage, PropertyKeyEnum: { //LANGUAGE: "lang", CULTURE: "NG_TRANSLATE_LANG_KEY", TRACEERRORS: "traceErrors", QUICKSEARCHRUNFIRST: "quickSearchRunFirst", RESTRICTPROPERTIESTOCOMMON: "restrictPropertiesToCommon", SYSTEMPROPERTIESVISIBLEARRAY: "systemPropertiesVisibleArray", WFSYSTEMPROPERTIESVISIBLEARRAY: "wfResultsPropertiesVisibleArray", //DISPLAYGROUPBYBOX: "displaygroupbybox", COMBINEDPRINTING: "combinedPrinting", MAXDOCSEARCH: "maxDocSearch", SAVEDPROFILES: "savedProfiles", SERVICEURL: "serviceUrl", SMARTFORMSSERVICEURL: "smartFormsServiceUrl", USERNAME: "userName", LOGINID: "loginId", USEREMAIL: "email", USERDESCRIPTION: "userDescription", ROLE: "role", AUTHCODE: "authCode", TOPLEVELFOLDERSINGULAR: "topLevelFolderSingular", TOPLEVELFOLDERPLURAL: "topLevelFolderPlural", TOPLEVELFOLDERS: "topLevelFolders", DOCUMENTTYPES: "documentTypes", USERDEFINEDPROPERTYCOLUMNORDER: "UserDefinedPropertyColumnOrder", THUMBNAILSIZE: "ThumbnailSize", RESULTSVIEWSTYLE: "ResultsViewStyle", ITEMSPERPAGE: "ItemsPerPage", //ORDERBY: "OrderBy", EMAILTIFFFORMAT: "EmailTiffFormat", TEXTMATCHING: "TextMatching", DATEMATCHING: "DateMatching", ENABLESEARCHBYPROPERTYPOPUP: "EnableSearchByPropertyPopup", REMEMBERVIEWSETTINGS: "RememberViewSettings", DISPLAYNEWESTPROPERTYFORMULTIVALUEPROPERTIES: "DisplayNewestPropertyForMultiValueProperties", AUTHCODE_LASTACCESSED: "authCode_lastAccessed", VISIBLE_VIEWER_SECTIONS: "visible_viewer_sections", RESETSENDSTATUSAFTERSEND: "ResetSendStatusAfterSend", //WFDISPLAYGROUPBYBOX: "WFDisplayGroupbyBox", WFDISPLAYNEWESTPROPERTYFORMULTIVALUEPROPERTIES: "WFDisplayNewestPropertyForMultiValueProperties", AUTOMATICALLYOPENSUPPORTINGDOCUMENTS: "AutomaticallyOpenSupportingDocuments", AUTOMATICALLYOPENFIRSTWORKFLOWDOCUMENT: "AutomaticallyOpenFirstWorkflowDocument", MAXSUPPDOCS: "maxSuppDocs", WFMAXRESULTS: "WFMaxResults", CACHEQUICKSEARCHES: "CacheQuickSearches", CACHESAVEDSEARCHES: "CacheSavedSearches", CACHETOPLEVELFOLDERS: "CacheTopLevelFolders", CACHEDOCUMENTTYPES: "CacheDocumentTypes", CACHEWORKFLOWS: "CacheWorkflows", QUICKSEARCHES: "quicksearches", SAVEDSEARCHES: "savedsearches", WORKFLOWS: "workflows", ROLEPERMISSIONS: "rolePermissions", HASWORKFLOWPERMISSIONS: "hasWorkflowPermission", HASQUICKSEARCHFLOWPERMISSIONS: "hasQuickSearchflowPermissions", SHOWANNOTATIONS: "Viewer_ShowAnnotations", SHOWTHUMBNAILS: "Viewer_ShowThumbnails", ALLOWSEARCHRESULTSFILTERING: "AllowSearchResultsFiltering", WFALLOWSEARCHRESULTSFILTERING: "WFAllowSearchResultsFiltering", SMARTFORMSSETTINGS: "SmartFormsSettings", SEARCHTYPECOLUMNDISPLAY: "SearchTypeColumnDisplay", DISPLAYLASTPAGEOFMULTIPAGEDOCUMENTS: "DisplayLastPageOfMultiPageDocuments", LASTVIEWEDDISTRIBUTIONSTAMPDEFINITION: "LastViewedDistributionStampDefinition", VIEWERSECTIONSIZES: "ViewerSectionSizes", VIEWERWINDOWLAYOUT: "ViewerWindowLayout", VIEWERDEFAULTZOOM: "ViewerDefaultZoom", WFDEFAULTSORT: "WFDefaultSort", INQUIRYDEFAULTSORT: "InquiryDefaultSort", } }); // --- // PRIVATE PROPERTIES // --- // --- // PUBLIC PROPERTIES. // --- // --- // PUBLIC METHODS. // --- function GetProperty(key, ignoreSessionValue) { var userSpecificSuffix = "|" + getSessionStorageProperty(this.PropertyKeyEnum.LOGINID) + "|" + getSessionStorageProperty(this.PropertyKeyEnum.SERVICEURL); var daysSinceUpdated; switch (key) { case this.PropertyKeyEnum.CACHEQUICKSEARCHES: case this.PropertyKeyEnum.CACHETOPLEVELFOLDERS: case this.PropertyKeyEnum.CACHEDOCUMENTTYPES: case this.PropertyKeyEnum.CACHESAVEDSEARCHES: case this.PropertyKeyEnum.CACHEWORKFLOWS: case this.PropertyKeyEnum.RESTRICTPROPERTIESTOCOMMON: case this.PropertyKeyEnum.COMBINEDPRINTING: case this.PropertyKeyEnum.REMEMBERVIEWSETTINGS: case this.PropertyKeyEnum.ENABLESEARCHBYPROPERTYPOPUP: case this.PropertyKeyEnum.DISPLAYNEWESTPROPERTYFORMULTIVALUEPROPERTIES: case this.PropertyKeyEnum.RESETSENDSTATUSAFTERSEND: case this.PropertyKeyEnum.WFDISPLAYNEWESTPROPERTYFORMULTIVALUEPROPERTIES: case this.PropertyKeyEnum.AUTOMATICALLYOPENSUPPORTINGDOCUMENTS: case this.PropertyKeyEnum.AUTOMATICALLYOPENFIRSTWORKFLOWDOCUMENT: case this.PropertyKeyEnum.ALLOWSEARCHRESULTSFILTERING: case this.PropertyKeyEnum.WFALLOWSEARCHRESULTSFILTERING: case this.PropertyKeyEnum.DISPLAYLASTPAGEOFMULTIPAGEDOCUMENTS: return (String(getLocalStorageProperty(key)) === 'true'); case this.PropertyKeyEnum.QUICKSEARCHES: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHEQUICKSEARCHES)) === 'true') { daysSinceUpdated = Math.floor((new Date() - new Date(getLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix))) / (1000 * 60 * 60 * 24)); if (daysSinceUpdated >= 7) { return []; } return String(getLocalStorageProperty(key + userSpecificSuffix)); } return String(getSessionStorageProperty(key)); case this.PropertyKeyEnum.TOPLEVELFOLDERS: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHETOPLEVELFOLDERS)) === 'true') { daysSinceUpdated = Math.floor((new Date() - new Date(getLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix))) / (1000 * 60 * 60 * 24)); if (daysSinceUpdated >= 7) { return []; } return String(getLocalStorageProperty(key + userSpecificSuffix)); } return String(getSessionStorageProperty(key)); case this.PropertyKeyEnum.DOCUMENTTYPES: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHEDOCUMENTTYPES)) === 'true') { daysSinceUpdated = Math.floor((new Date() - new Date(getLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix))) / (1000 * 60 * 60 * 24)); if (daysSinceUpdated >= 7) { return []; } return String(getLocalStorageProperty(key + userSpecificSuffix)); } return String(getSessionStorageProperty(key)); case this.PropertyKeyEnum.SAVEDSEARCHES: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHESAVEDSEARCHES)) === 'true') { daysSinceUpdated = Math.floor((new Date() - new Date(getLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix))) / (1000 * 60 * 60 * 24)); if (daysSinceUpdated >= 7) { return []; } return String(getLocalStorageProperty(key + userSpecificSuffix)); } return String(getSessionStorageProperty(key)); case this.PropertyKeyEnum.WORKFLOWS: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHEWORKFLOWS)) === 'true') { daysSinceUpdated = Math.floor((new Date() - new Date(getLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix))) / (1000 * 60 * 60 * 24)); if (daysSinceUpdated >= 7) { return []; } return String(getLocalStorageProperty(key + userSpecificSuffix)); } return String(getSessionStorageProperty(key)); //view settings //case this.PropertyKeyEnum.ORDERBY: case this.PropertyKeyEnum.THUMBNAILSIZE: case this.PropertyKeyEnum.RESULTSVIEWSTYLE: case this.PropertyKeyEnum.ITEMSPERPAGE: if (ignoreSessionValue) { return getLocalStorageProperty(key + userSpecificSuffix); } else { return getSessionStorageProperty(key); } //these are specific to the user/system case this.PropertyKeyEnum.QUICKSEARCHRUNFIRST: case this.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER: case this.PropertyKeyEnum.VISIBLE_VIEWER_SECTIONS: return getLocalStorageProperty(key + userSpecificSuffix); case this.PropertyKeyEnum.WFDEFAULTSORT: case this.PropertyKeyEnum.INQUIRYDEFAULTSORT: var setting = getLocalStorageProperty(key + userSpecificSuffix); try { if (_.isArray(JSON.parse(setting))) { return JSON.parse(setting); } } catch (e) { if (_.isString(setting)) { return [{ "Level": 0, "ColumnName": setting, "SortOrder": 0 }]; } else { alert("Unable to parse " + key + " setting"); } } //if (!_.isArray(JSON.parse(setting))) { // return [{ "Level": 0, "ColumnName": setting, "SortOrder": 0 }]; //} else { // return JSON.parse(setting); //} break; case this.PropertyKeyEnum.SHOWANNOTATIONS: case this.PropertyKeyEnum.SHOWTHUMBNAILS: return (String(getLocalStorageProperty(key + userSpecificSuffix)) === 'true'); case this.PropertyKeyEnum.SYSTEMPROPERTIESVISIBLEARRAY: case this.PropertyKeyEnum.WFSYSTEMPROPERTIESVISIBLEARRAY: return getLocalStorageProperty(key + userSpecificSuffix).split(","); //these are login specific case this.PropertyKeyEnum.SMARTFORMSSERVICEURL: case this.PropertyKeyEnum.USERNAME: case this.PropertyKeyEnum.LOGINID: case this.PropertyKeyEnum.USEREMAIL: case this.PropertyKeyEnum.USERDESCRIPTION: case this.PropertyKeyEnum.ROLE: case this.PropertyKeyEnum.TOPLEVELFOLDERSINGULAR: case this.PropertyKeyEnum.TOPLEVELFOLDERPLURAL: case this.PropertyKeyEnum.ROLEPERMISSIONS: return getSessionStorageProperty(key); case this.PropertyKeyEnum.HASWORKFLOWPERMISSIONS: case this.PropertyKeyEnum.HASQUICKSEARCHPERMISSIONS: return (String(getSessionStorageProperty(key)) == "true"); //parse and return as INT case this.PropertyKeyEnum.MAXDOCSEARCH: case this.PropertyKeyEnum.MAXSUPPDOCS: case this.PropertyKeyEnum.WFMAXRESULTS: return parseInt(getLocalStorageProperty(key), 10); case this.PropertyKeyEnum.SMARTFORMSSETTINGS: return JSON.parse(getLocalStorageProperty(key + userSpecificSuffix)); //these should be cached in locale storage for session recovery case this.PropertyKeyEnum.AUTHCODE: case this.PropertyKeyEnum.AUTHCODE_LASTACCESSED: case this.PropertyKeyEnum.SERVICEURL: return getLocalStorageProperty(key); //ensure language and culture are valid case this.PropertyKeyEnum.CULTURE: var value = getLocalStorageProperty(this.PropertyKeyEnum.CULTURE); if (!value || (value !== "en-US" && value !== "en-GB" && value !== "es-ES")) { console.warn("Caught invalid culture value. Setting to en-US."); setLocalStorageProperty(this.PropertyKeyEnum.CULTURE, "en-US"); return "en-US"; } return value; default: return getLocalStorageProperty(key); } } function SetProperty(key, value, enforcePersist) { var userSpecificSuffix = "|" + getSessionStorageProperty(this.PropertyKeyEnum.LOGINID) + "|" + getSessionStorageProperty(this.PropertyKeyEnum.SERVICEURL); if (!enforcePersist || enforcePersist == null) { enforcePersist = false; } switch (key) { case this.PropertyKeyEnum.CACHEQUICKSEARCHES: setLocalStorageProperty(this.PropertyKeyEnum.CACHEQUICKSEARCHES, value); if (!value) { //if turning off this setting, copy values to session setSessionStorageProperty(this.PropertyKeyEnum.QUICKSEARCHES, getLocalStorageProperty(this.PropertyKeyEnum.QUICKSEARCHES + userSpecificSuffix)); //then delete from local storage DeletePropertyFromLocalStorage(this.PropertyKeyEnum.QUICKSEARCHES + userSpecificSuffix); } else { //populate from session or default setLocalStorageProperty(this.PropertyKeyEnum.QUICKSEARCHES + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.QUICKSEARCHES)); } break; case this.PropertyKeyEnum.CACHETOPLEVELFOLDERS: setLocalStorageProperty(this.PropertyKeyEnum.CACHETOPLEVELFOLDERS, value); if (!value) { //if turning off this setting, copy values to session setSessionStorageProperty(this.PropertyKeyEnum.TOPLEVELFOLDERS, getLocalStorageProperty(this.PropertyKeyEnum.TOPLEVELFOLDERS + userSpecificSuffix)); //then delete from local storage DeletePropertyFromLocalStorage(this.PropertyKeyEnum.TOPLEVELFOLDERS + userSpecificSuffix); } else { //populate from session or default setLocalStorageProperty(this.PropertyKeyEnum.TOPLEVELFOLDERS + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.TOPLEVELFOLDERS)); } break; case this.PropertyKeyEnum.CACHEDOCUMENTTYPES: setLocalStorageProperty(this.PropertyKeyEnum.CACHEDOCUMENTTYPES, value); if (!value) { //if turning off this setting, copy values to session setSessionStorageProperty(this.PropertyKeyEnum.DOCUMENTTYPES, getLocalStorageProperty(this.PropertyKeyEnum.DOCUMENTTYPES + userSpecificSuffix)); //then delete from local storage DeletePropertyFromLocalStorage(this.PropertyKeyEnum.DOCUMENTTYPES + userSpecificSuffix); } else { //populate from session or default setLocalStorageProperty(this.PropertyKeyEnum.DOCUMENTTYPES + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.DOCUMENTTYPES)); } break; case this.PropertyKeyEnum.CACHESAVEDSEARCHES: setLocalStorageProperty(this.PropertyKeyEnum.CACHESAVEDSEARCHES, value); if (!value) { //if turning off this setting, copy values to session setSessionStorageProperty(this.PropertyKeyEnum.SAVEDSEARCHES, getLocalStorageProperty(this.PropertyKeyEnum.SAVEDSEARCHES + userSpecificSuffix)); //then delete from local storage DeletePropertyFromLocalStorage(this.PropertyKeyEnum.SAVEDSEARCHES + userSpecificSuffix); } else { //populate from session or default setLocalStorageProperty(this.PropertyKeyEnum.SAVEDSEARCHES + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.SAVEDSEARCHES)); } break; case this.PropertyKeyEnum.CACHEWORKFLOWS: setLocalStorageProperty(this.PropertyKeyEnum.CACHEWORKFLOWS, value); if (!value) { //if turning off this setting, copy values to session setSessionStorageProperty(this.PropertyKeyEnum.WORKFLOWS, getLocalStorageProperty(this.PropertyKeyEnum.WORKFLOWS + userSpecificSuffix)); //then delete from local storage DeletePropertyFromLocalStorage(this.PropertyKeyEnum.WORKFLOWS + userSpecificSuffix); } else { //populate from session or default setLocalStorageProperty(this.PropertyKeyEnum.WORKFLOWS + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.WORKFLOWS)); } break; case this.PropertyKeyEnum.QUICKSEARCHES: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHEQUICKSEARCHES)) === 'true') { setLocalStorageProperty(key + userSpecificSuffix, value); setLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix, new Date()); } else { setSessionStorageProperty(key, value); } break; case this.PropertyKeyEnum.TOPLEVELFOLDERS: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHETOPLEVELFOLDERS)) === 'true') { setLocalStorageProperty(key + userSpecificSuffix, value); setLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix, new Date()); } else { setSessionStorageProperty(key, value); } break; case this.PropertyKeyEnum.DOCUMENTTYPES: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHEDOCUMENTTYPES)) === 'true') { setLocalStorageProperty(key + userSpecificSuffix, value); setLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix, new Date()); } else { setSessionStorageProperty(key, value); } break; case this.PropertyKeyEnum.SAVEDSEARCHES: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHESAVEDSEARCHES)) === 'true') { setLocalStorageProperty(key + userSpecificSuffix, value); setLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix, new Date()); } else { setSessionStorageProperty(key, value); } break; case this.PropertyKeyEnum.WORKFLOWS: if (String(getLocalStorageProperty(this.PropertyKeyEnum.CACHEWORKFLOWS)) === 'true') { setLocalStorageProperty(key + userSpecificSuffix, value); setLocalStorageProperty(key + "_LastAccessed" + userSpecificSuffix, new Date()); } else { setSessionStorageProperty(key, value); } break; //view settings //case this.PropertyKeyEnum.ORDERBY: case this.PropertyKeyEnum.THUMBNAILSIZE: case this.PropertyKeyEnum.RESULTSVIEWSTYLE: case this.PropertyKeyEnum.ITEMSPERPAGE: //console.log("enforcePersist: " + enforcePersist); if (String(getLocalStorageProperty(this.PropertyKeyEnum.REMEMBERVIEWSETTINGS)) === 'true' || enforcePersist) { setLocalStorageProperty(key + userSpecificSuffix, value); } setSessionStorageProperty(key, value); break; case this.PropertyKeyEnum.REMEMBERVIEWSETTINGS: setLocalStorageProperty(key, value); if (!value) { //if turning off this setting, copy values to session //setSessionStorageProperty(this.PropertyKeyEnum.ORDERBY, getLocalStorageProperty(this.PropertyKeyEnum.ORDERBY + userSpecificSuffix)); setSessionStorageProperty(this.PropertyKeyEnum.THUMBNAILSIZE, getLocalStorageProperty(this.PropertyKeyEnum.THUMBNAILSIZE + userSpecificSuffix)); setSessionStorageProperty(this.PropertyKeyEnum.RESULTSVIEWSTYLE, getLocalStorageProperty(this.PropertyKeyEnum.RESULTSVIEWSTYLE + userSpecificSuffix)); setSessionStorageProperty(this.PropertyKeyEnum.ITEMSPERPAGE, getLocalStorageProperty(this.PropertyKeyEnum.ITEMSPERPAGE + userSpecificSuffix)); //then delete from local storage //DeletePropertyFromLocalStorage(this.PropertyKeyEnum.ORDERBY + userSpecificSuffix); DeletePropertyFromLocalStorage(this.PropertyKeyEnum.THUMBNAILSIZE + userSpecificSuffix); DeletePropertyFromLocalStorage(this.PropertyKeyEnum.RESULTSVIEWSTYLE + userSpecificSuffix); DeletePropertyFromLocalStorage(this.PropertyKeyEnum.ITEMSPERPAGE + userSpecificSuffix); } else { //populate from session or default //setLocalStorageProperty(this.PropertyKeyEnum.ORDERBY + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.ORDERBY)); setLocalStorageProperty(this.PropertyKeyEnum.THUMBNAILSIZE + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.THUMBNAILSIZE)); setLocalStorageProperty(this.PropertyKeyEnum.RESULTSVIEWSTYLE + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.RESULTSVIEWSTYLE)); setLocalStorageProperty(this.PropertyKeyEnum.ITEMSPERPAGE + userSpecificSuffix, getSessionStorageProperty(this.PropertyKeyEnum.ITEMSPERPAGE)); } break; //these are specific to the user/system case this.PropertyKeyEnum.QUICKSEARCHRUNFIRST: case this.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER: case this.PropertyKeyEnum.VISIBLE_VIEWER_SECTIONS: case this.PropertyKeyEnum.SHOWANNOTATIONS: case this.PropertyKeyEnum.SHOWTHUMBNAILS: case this.PropertyKeyEnum.WFDEFAULTSORT: case this.PropertyKeyEnum.INQUIRYDEFAULTSORT: setLocalStorageProperty(key + userSpecificSuffix, value); break; case this.PropertyKeyEnum.SYSTEMPROPERTIESVISIBLEARRAY: case this.PropertyKeyEnum.WFSYSTEMPROPERTIESVISIBLEARRAY: //ensure the value is an array if ($.isArray(value)) { setLocalStorageProperty(key + userSpecificSuffix, value); } else { setLocalStorageProperty(key, value.join(",")); } break; case this.PropertyKeyEnum.SMARTFORMSSETTINGS: setLocalStorageProperty(key + userSpecificSuffix, JSON.stringify(value)); break; //these are login specific case this.PropertyKeyEnum.SMARTFORMSSERVICEURL: case this.PropertyKeyEnum.USERNAME: case this.PropertyKeyEnum.LOGINID: case this.PropertyKeyEnum.USEREMAIL: case this.PropertyKeyEnum.USERDESCRIPTION: case this.PropertyKeyEnum.ROLE: case this.PropertyKeyEnum.TOPLEVELFOLDERSINGULAR: case this.PropertyKeyEnum.TOPLEVELFOLDERPLURAL: case this.PropertyKeyEnum.ROLEPERMISSIONS: case this.PropertyKeyEnum.HASWORKFLOWPERMISSIONS: case this.PropertyKeyEnum.HASQUICKSEARCHFLOWPERMISSIONS: setSessionStorageProperty(key, value); break; //these require value validation case this.PropertyKeyEnum.MAXDOCSEARCH: case this.PropertyKeyEnum.MAXSUPPDOCS: case this.PropertyKeyEnum.WFMAXRESULTS: if (parseInt(value, 10) < 0) { value = 0; } setLocalStorageProperty(key, value); break; //these should be cached in locale storage for session recovery case this.PropertyKeyEnum.AUTHCODE: case this.PropertyKeyEnum.AUTHCODE_LASTACCESSED: case this.PropertyKeyEnum.SERVICEURL: setLocalStorageProperty(key, value); break; //set language and culture together case this.PropertyKeyEnum.CULTURE: setLocalStorageProperty(this.PropertyKeyEnum.CULTURE, value); //setLocalStorageProperty(this.PropertyKeyEnum.LANGUAGE, value); break; default: setLocalStorageProperty(key, value); } } function setLocalStorageProperty(key, value) { try { if (typeof (Storage) !== "undefined") { localStorage.setItem(key, value); } else { amplify.store(key, value); } return true; } catch (ex) { return false; } } function setSessionStorageProperty(key, value) { try { //console.log("saving " + value + " into " + key + " sessionStorage"); if (typeof (Storage) !== "undefined") { sessionStorage.setItem(key, value); } else { amplify.store(key, value); } return true; } catch (ex) { console.log(JSON.stringify(ex)); return false; } } function getLocalStorageProperty(key) { var value = null; if (typeof (Storage) !== "undefined") { value = localStorage.getItem(key); } else { value = amplify.store(key); } //if not defined, get the default and save if (!angular.isDefined(value) || value === null) { try { value = PropertyDefaults[key]; if ((!angular.isDefined(value) || value === null) && key.indexOf("|") > -1) { var baseKey = key.split("|")[0]; value = PropertyDefaults[baseKey]; } //console.log("default value for " + key + ": " + value); setLocalStorageProperty(key, value); } catch (e) { //eat the error. a missing stored key is better handled in the calling code console.error(e); } } return value; } function getSessionStorageProperty(key) { var value = null; if (typeof (Storage) !== "undefined") { value = sessionStorage.getItem(key); } else { value = amplify.store(key); } //if not defined, get the default and save if (!value || value === null) { if (key !== "loginId" && key !== "serviceUrl") { //check to see if there's a persisted value (if there isn't one, it'll return the default, which is what we need anyway) var userSpecificSuffix = "|" + getSessionStorageProperty("loginId") + "|" + getSessionStorageProperty("serviceUrl"); value = getLocalStorageProperty(key + userSpecificSuffix); } if (!value || value === null) { try { //console.log("getting default value for " + key); value = PropertyDefaults[key]; // eval("LocalStorageService.PropertyDefaults." + key); if ((!value || value === null) && key.indexOf("|") > -1) { var baseKey = key.split("|")[0]; value = PropertyDefaults[baseKey]; } //console.log("default value for " + key + ": " + value); setSessionStorageProperty(key, value); } catch (e) { //eat the error. a missing stored key is better handled in the calling code console.error(e); } } else { setSessionStorageProperty(key, value); } } return value; } function resetProperty(key) { if (typeof (Storage) !== "undefined") { localStorage.removeItem(key); var sessionKey = key.split("|")[0]; sessionStorage.removeItem(sessionKey); } else { amplify.store(key, null); } } function DeletePropertyFromLocalStorage(key) { if (typeof (Storage) !== "undefined") { localStorage.removeItem(key); } else { amplify.store(key, null); } } function WipeSessionStorage() { if (typeof (Storage) !== "undefined") { sessionStorage.clear(); } else { $.each(this.PropertyKeyEnum, function (index, key) { amplify.store(key, null); }); } } function ClearSettings() { var userSpecificSuffix = "|" + getSessionStorageProperty(this.PropertyKeyEnum.LOGINID) + "|" + getSessionStorageProperty(this.PropertyKeyEnum.SERVICEURL); $.each(this.PropertyKeyEnum, function (index, key) { switch (key) { case "quicksearches": case "topLevelFolders": case "documentTypes": case "savedsearches": case "workflows": resetProperty(key + userSpecificSuffix); resetProperty(key + "_LastAccessed" + userSpecificSuffix); break; //case "OrderBy": case "ThumbnailSize": case "ResultsViewStyle": case "ItemsPerPage": case "quickSearchRunFirst": case "systemPropertiesVisibleArray": case "wfResultsPropertiesVisibleArray": case "UserDefinedPropertyColumnOrder": case "visible_viewer_sections": case "Viewer_ShowAnnotations": case "Viewer_ShowThumbnails": resetProperty(key + userSpecificSuffix); break; //case "lang": case "NG_TRANSLATE_LANG_KEY": case "restrictPropertiesToCommon": case "combinedPrinting": case "maxDocSearch": case "EmailTiffFormat": case "SearchTypeColumnDisplay": case "TextMatching": case "DateMatching": case "EnableSearchByPropertyPopup": case "RememberViewSettings": case "DisplayNewestPropertyForMultiValueProperties": case "WFDisplayNewestPropertyForMultiValueProperties": case "ResetSendStatusAfterSend": case "AutomaticallyOpenSupportingDocuments": case "AutomaticallyOpenFirstWorkflowDocument": case "maxSuppDocs": case "WFMaxResults": case "AllowSearchResultsFiltering": case "WFAllowSearchResultsFiltering": case "DisplayLastPageOfMultiPageDocuments": case "LastViewedDistributionStampDefinition": resetProperty(key); break; } }); } // --- // PRIVATE FUNCTIONS. // --- //return LocalStorageService; } })(); (function () { 'use strict'; // Original: https://github.com/angular/angular.js/issues/1699#issuecomment-22511464 // // Usage: // // (interception is needed for Back/Forward buttons to work) // // location.intercept($scope._url_pattern, function(matched) { // // can return false to abort interception // var type = matched[1] // if (!type) { // return; // } // $scope.safeApply(function() { // $scope.data_type = type; // $scope.params.page = 1; // $scope.get_data(); // }); // }); // // anywhere in your controller: // location.skipReload().path(url); // // to replace in history stack: // location.skipReload().path(url).replace(); angular.module('docLinkWeb').factory('locationFactory', [ '$location', '$route', '$rootScope', locationFactory]); function locationFactory($location, $route, $rootScope) { var page_route = $route.current; $location.skipReload = function () { //var lastRoute = $route.current; var unbind = $rootScope.$on('$locationChangeSuccess', function () { $route.current = page_route; unbind(); }); return $location; }; if ($location.intercept) { throw '$location.intercept is already defined'; } $location.intercept = function (url_pattern, load_url) { function parse_path() { var match = $location.path().match(url_pattern); if (match) { match.shift(); return match; } } var unbind = $rootScope.$on("$locationChangeSuccess", function () { var matched = parse_path(); if (!matched || load_url(matched) === false) { return unbind(); } $route.current = page_route; }); }; var locationChangeSuccess_teardownHandler = null; $location.update_path = function (path, keep_previous_path_in_history) { if ($location.path() == path) return; var routeToKeep = $route.current; var unbind_locationFactory_locationChangeSuccess = $rootScope.$on('$locationChangeSuccess', function () { if (routeToKeep) { $route.current = routeToKeep; routeToKeep = null; unbind_locationFactory_locationChangeSuccess(); } }); $location.path(path); if (!keep_previous_path_in_history) $location.replace(); }; return $location; } })(); (function () { 'use strict'; var app = angular.module('docLinkWeb'); app.service("MessagingService", ['Hub', 'SessionFactory', '$rootScope', 'growl', function (Hub, SessionFactory, $rootScope, growl) { var hub = null; this.hubName = ""; var that = this; var messagingEvents = { OpenDocumentsRequested: "OpenDocumentsRequested", SelectedDocumentsChanged: "SelectedDocumentsChanged", ResultsReloadRequested: "ResultsReloadRequested", SearchByPropertyRequested: "SearchByPropertyRequested", ResultsViewSettingsChanged: "ResultsViewSettingsChanged", ResultsUpdated: "ResultsUpdated", DocumentUpdated: "DocumentUpdated", DocumentImageChanged: "DocumentImageChanged", DocumentsDeleted: "DocumentsDeleted", DocumentsRemovedFromWorkflow: "DocumentsRemovedFromWorkflow", DocumentPropertyUpdated: "DocumentPropertyUpdated", } that.connectedState = "disconnected"; //#region init/teardown events var subscribe = function (serverPath, hubName) { that.serverPath = serverPath; that.hubName = hubName; //signal-R Hub for SmartForms messaging that.hub = new Hub(that.hubName, { //client side methods listeners: { 'ServerToClientMessage': function (jsonMessage) { var message = JSON.parse(jsonMessage); console.log(message); if (message.MessageId === "RefreshImage") { var documentId = message.Items["documentId"]; var gotoLast = message.Items["displayLastPage"]; $rootScope.$broadcast(messagingEvents.DocumentImageChanged, { "documentid": documentId, "showLastPage": gotoLast }); } else if (message.MessageId === "DocumentUpdated") { var documentId = message.Items["Document"]; $rootScope.$broadcast(messagingEvents.DocumentUpdated, { "documentid": documentId }); } else if (message.MessageId === "DownloadFileContentAvailable") { var fileName = message.Items["fileName"]; var content = message.Items["content"]; // Try using msSaveBlob if supported var blob = new Blob([content], { type: 'application/octet-stream' }); if (navigator.msSaveBlob) navigator.msSaveBlob(blob, fileName); else { // Try using other saveBlob implementations, if available var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob; if (saveBlob !== undefined) { saveBlob(blob, fileName); } else { var anchor = angular.element(''); anchor.css({ display: 'none' }); // Make sure it's not visible angular.element(document.body).append(anchor); // Attach to document for FireFox anchor.attr({ href: 'data:' + message.Items["dataType"] + ';charset=utf-8,' + encodeURI(content), target: '_blank', download: fileName })[0].click(); anchor.remove(); } } } else if (message.MessageId === "DocumentCreated") { var documentId = message.Items["Document"]; if (documentId && documentId != null) { growl.success("DOCUMENT_CREATED", { ttl: 5000, disableCountDown: false, variables: { "documentid": documentId } }); } } else { //generic message without a declared event, so just broadcast the message id $rootScope.$broadcast(message.MessageId, message.Items); } }, 'newConnection': function (connectionId) { $rootScope.$broadcast("MessagingFactoryConnectionMade", { ConnectionId: connectionId }); } }, //server side methods methods: ['clientToServerMessage'], 'stateChanged': function (state) { var stateNames = { 0: 'connecting', 1: 'connected', 2: 'reconnecting', 4: 'disconnected' }; //console.log("New Signal-R Connection State: " + stateNames[state.newState]) that.connectedState = stateNames[state.newState]; if (stateNames[state.newState] == 'disconnected') { //Hub Disconnect logic here... } $rootScope.$broadcast("MessagingFactoryStateChanged", { NewState: stateNames[state.newState] }); }, //handle connection error errorHandler: function (error) { console.error(error); }, rootPath: that.serverPath, //query params sent on initial connection queryParams: { 'authCode': SessionFactory.GetAuthcode() }, logging: true, useSharedConnection: true, transport: (isSafari())? ["longPolling"] : "auto" }); }; var unsubscribe = function () { that.hub.disconnect(); }; function isSafari() { var ua = window.navigator.userAgent; var iOS = !!ua.match(/iP(ad|od|hone)/i); var hasSafariInUa = !!ua.match(/Safari/i); var noOtherBrowsersInUa = !ua.match(/Chrome|CriOS|OPiOS|mercury|FxiOS|Firefox/i) var result = false; if (iOS) { //detecting Safari in IOS mobile browsers var webkit = !!ua.match(/WebKit/i); result = webkit && hasSafariInUa && noOtherBrowsersInUa } else if (window.safari !== undefined) { //detecting Safari in Desktop Browsers result = true; } else { // detecting Safari in other platforms result = hasSafariInUa && noOtherBrowsersInUa } return result; } //#endregion init/teardown events //#region Public Methods /// /// Send a Message to SignalR Service and optionally send it to other listeners /// /// Message Types found in Altec.SmartForms.ApplicationMessage /// JSON representation of a dictionary with message items /// broadcast this message to other listeners? function sendMessage(messageType, payload, loopBack) { if (that.connectedState === "connected") { try { that.hub.clientToServerMessage(messageType, JSON.stringify(payload)); //Calling a server method } catch (e) { console.error(e); } } //broadcast this message to other listeners if (angular.isDefined(loopBack) && loopBack === true) { $rootScope.$broadcast(messageType, payload); } } var documentUpdated = function (documentid, showLastPage) { if (angular.isDefined(showLastPage) === false) { showLastPage = false; } sendMessage(messagingEvents.DocumentUpdated, { "documentid": documentid, "showLastPage": showLastPage }, true); }; var documentPropertyUpdated = function (documentid, propertyName, propertyValue) { var payload = { "documentid": documentid, "propertyName": propertyName, "propertyValue": propertyValue }; sendMessage(messagingEvents.DocumentPropertyUpdated, payload, true); }; var updateResults = function (gridName, columns, data, totalDocumentCount) { var payload = { "gridName": gridName, "columns": columns, "data": data, "totalDocumentCount": totalDocumentCount }; sendMessage(messagingEvents.ResultsUpdated, payload, true); }; var clearResults = function (gridName) { var payload = { "gridName": gridName, "columns": [], "data": [], "totalDocumentCount": 0 }; sendMessage(messagingEvents.ResultsUpdated, payload, true); }; var updateViewSettings = function (gridName, columns, thumbnailSize, resultsViewStyle, itemsPerPage, orderBy, pageNum) { var payload = { "gridName": gridName, "columns": columns, "thumbnailSize": thumbnailSize, "resultsViewStyle": resultsViewStyle, "itemsPerPage": itemsPerPage, "orderBy": orderBy, "pageNum": pageNum } sendMessage(messagingEvents.ResultsViewSettingsChanged, payload, true); } var searchByProperty = function (propertyId, propertyValue) { var payload = { "PropertyId": propertyId, "PropertyValue": propertyValue } sendMessage(messagingEvents.SearchByPropertyRequested, payload, true); } var reloadGrid = function (gridName, pageNum, pageCount, orderBy, clearSelected) { if (angular.isDefined(clearSelected) === false) { clearSelected = false; } var payload = { "pageNum": pageNum, "pageCount": pageCount, "OrderBy": orderBy, "gridName": gridName, "ClearSelectedDocuments": clearSelected } sendMessage(messagingEvents.ResultsReloadRequested, payload, true); }; var updateGridSelections = function (gridName, selecteddocuments, focusedDocument, focusedDocumentIndex) { var payload = { "selecteddocuments": $.extend(true, [], selecteddocuments), "focusedDocument": (focusedDocument == null) ? null : $.extend(true, {}, focusedDocument), "focusedDocumentIndex": focusedDocumentIndex, "gridName": gridName } sendMessage(messagingEvents.SelectedDocumentsChanged, payload, true); }; var openDocuments = function (gridName, documents, currentPage) { var payload = { "documents": documents, "currentpage": currentPage, "gridName": gridName } sendMessage(messagingEvents.OpenDocumentsRequested, payload, true); }; var documentsDeleted = function (documentids) { sendMessage(messagingEvents.DocumentsDeleted, { "documentids": documentids }, true); } var documentsRemovedFromWorkflow = function (documentids) { sendMessage(messagingEvents.DocumentsRemovedFromWorkflow, { "documentids": documentids }, true); } var documentsWorkflowDetailsChanged = function (documentids) { sendMessage(messagingEvents.DocumentsWorkflowDetailsChanged, { "documentids": documentids }, true); } //#endregion Public Methods //#region Event Listeners var onConnection = function ($scope, handler) { $scope.$on("MessagingFactoryConnectionMade", function (event, payload) { // note that the handler is passed the domain parameters handler(that.hubName, payload.ConnectionId); }); }; var onConnectionStateChange = function ($scope, handler) { $scope.$on("MessagingFactoryStateChanged", function (event, payload) { // note that the handler is passed the domain parameters handler(that.hubName, payload.NewState); }); }; var onDocumentUpdated = function ($scope, documentid, handler) { return $scope.$on(messagingEvents.DocumentUpdated, function (event, payload) { // note that the handler is passed the domain parameters if (payload.documentid === documentid || documentid === "ALL") { handler(payload.documentid, payload.showLastPage); } }); }; var onResultsUpdated = function ($scope, gridName, handler) { return $scope.$on(messagingEvents.ResultsUpdated, function (event, payload) { // note that the handler is passed the domain parameters if (payload.gridName === gridName) { handler(payload); } }); }; var onViewSettingsChanged = function ($scope, gridName, handler) { return $scope.$on(messagingEvents.ResultsViewSettingsChanged, function (event, payload) { // note that the handler is passed the domain parameters if (payload.gridName === gridName) { handler(payload); } }); }; var onSearchByProperty = function ($scope, handler) { $scope.$on(messagingEvents.SearchByPropertyRequested, function (event, payload) { // note that the handler is passed the domain parameters handler(payload); }); }; var onReloadRequested = function ($scope, gridName, handler) { $scope.$on(messagingEvents.ResultsReloadRequested, function (event, payload) { // note that the handler is passed the domain parameters if (payload.gridName === gridName) { handler(payload); } }); }; var onSelectionChanged = function ($scope, gridName, handler) { $scope.$on(messagingEvents.SelectedDocumentsChanged, function (event, payload) { // note that the handler is passed the domain parameters if (payload.gridName === gridName || gridName === "ALL" || gridName === null) { handler(payload); } }); }; var onDocumentSelectedToOpen = function ($scope, gridName, handler) { $scope.$on(messagingEvents.OpenDocumentsRequested, function (event, payload) { // note that the handler is passed the domain parameters if (payload.gridName === gridName || gridName === "ALL" || gridName === null) { handler(payload); } }); }; var onDocumentsDeleted = function ($scope, handler) { return $scope.$on(messagingEvents.DocumentsDeleted, function (event, payload) { // note that the handler is passed the domain parameters handler(payload); }); }; var onDocumentsRemovedFromWorkflow = function ($scope, handler) { return $scope.$on(messagingEvents.DocumentsRemovedFromWorkflow, function (event, payload) { // note that the handler is passed the domain parameters handler(payload); }); }; var onDocumentsWorkflowDetailsChanged = function ($scope, handler) { return $scope.$on(messagingEvents.DocumentsWorkflowDetailsChanged, function (event, payload) { // note that the handler is passed the domain parameters handler(payload); }); }; var onDocumentPropertyUpdated = function ($scope, documentid, propertyName, handler) { return $scope.$on(messagingEvents.DocumentPropertyUpdated, function (event, payload) { // note that the handler is passed the domain parameters if ((payload.documentid === documentid || documentid === "ALL") && (payload.propertyName === propertyName || propertyName === "ALL")) { handler(payload.documentid, payload.propertyName, payload.propertyValue); } }); }; //#endregion return { Subscribe: subscribe, Unsubscribe: unsubscribe, onConnection: onConnection, onConnectionStateChange: onConnectionStateChange, DocumentUpdated: documentUpdated, onDocumentUpdated: onDocumentUpdated, onResultsUpdated: onResultsUpdated, UpdateResults: updateResults, ClearResults: clearResults, onViewSettingsChanged: onViewSettingsChanged, UpdateViewSettings: updateViewSettings, onSearchByProperty: onSearchByProperty, SearchByProperty: searchByProperty, onReloadRequested: onReloadRequested, ReloadGrid: reloadGrid, onSelectionChanged: onSelectionChanged, UpdateGridSelections: updateGridSelections, onDocumentSelectedToOpen: onDocumentSelectedToOpen, OpenDocuments: openDocuments, DocumentsDeleted: documentsDeleted, onDocumentsDeleted: onDocumentsDeleted, DocumentsRemovedFromWorkflow: documentsRemovedFromWorkflow, onDocumentsRemovedFromWorkflow: onDocumentsRemovedFromWorkflow, DocumentsWorkflowDetailsChanged: documentsWorkflowDetailsChanged, onDocumentsWorkflowDetailsChanged: onDocumentsWorkflowDetailsChanged, DocumentPropertyUpdated: documentPropertyUpdated, onDocumentPropertyUpdated: onDocumentPropertyUpdated } }]); })(); angular.module('docLinkWeb').service('modalService', ['$rootScope', '$uibModal', '$uibModalStack', function ($rootScope, $modal, $uibModalStack) { var that = this; var modalDefaults = { backdrop: true, keyboard: true, modalFade: true, templateUrl: "tpl.modalServiceYesNoTemplate.html", animation: false, backdropClass: 'modalBackDrop' }; var modalOptions = { closeButtonText: 'Close', actionButtonText: 'OK', headerText: 'Proceed?', bodyText: 'Perform this action?' }; this.modalInstance = null; this.hide = function () { if (this.modalInstance && this.modalInstance !== null) { this.modalInstance.close(); } }; this.showModal = function (customModalDefaults, customModalOptions) { if (!customModalDefaults) customModalDefaults = {}; customModalDefaults.backdrop = 'static'; return this.show(customModalDefaults, customModalOptions); }; this.show = function (customModalDefaults, customModalOptions) { //Create temp objects to work with since we're in a singleton service var tempModalDefaults = {}; var tempModalOptions = {}; //Map angular-ui modal custom defaults to modal defaults defined in service angular.extend(tempModalDefaults, modalDefaults, customModalDefaults); //Map modal.html $scope custom properties to defaults defined in service angular.extend(tempModalOptions, modalOptions, customModalOptions); if (!tempModalDefaults.controller) { tempModalDefaults.controller = ['$scope', '$uibModalInstance', '$rootScope', function ($scope, $modalInstance, $rootScope) { that.modalInstance = $modalInstance; $scope.modalOptions = tempModalOptions; $scope.modalOptions.ok = function (result) { $modalInstance.close(true); }; $scope.modalOptions.close = function (result) { $modalInstance.close(false); }; $scope.$on("$destroy", function () { $scope.modalOptions = null; that.modalInstance = null; }); }]; } return $modal.open(tempModalDefaults).result; }; // this will listen for route changes and call the callback $rootScope.$on('$routeChangeStart', function () { $uibModalStack.dismissAll(); // automatically dismiss modals on state change }); }]); (function () { 'use strict'; angular.module('Properties').service('PropertyService', ['$http', '$q', 'SessionFactory', 'LocalStorageService', propertyService]); function propertyService($http, $q, SessionFactory, LocalStorageService) { //return public API return ({ GetMasterPropertiesList: getMasterPropertiesList, GetAllProperties: getAllProperties, GetPropertyById: GetPropertyById, UpdatePropertyPositions: UpdatePropertyPositions, SaveOptionsChanges: SaveOptionsChanges, GetPropertiesByPosition: GetPropertiesByPosition, PropertiesForDocumentTypes: PropertiesForDocumentTypes, GetLookupOptions: GetLookupOptions }); // --- // PRIVATE PROPERTIES // --- var __masterProperties = []; // --- // PUBLIC PROPERTIES. // --- // --- // PUBLIC METHODS. // --- function getMasterPropertiesList(refresh) { var defer = $q.defer(); if (!angular.isDefined(refresh)) { refresh = false; } var request = $http({ method: "get", url: SessionFactory.GetServiceUrl() + "Property/MasterProperties?refresh=" + refresh }).success(function (response) { defer.resolve(response); }).error(function (response, status) { defer.reject({ message: "Error Loading Master Properties" }); }) return defer.promise; } function getAllProperties() { var defer = $q.defer(); __masterProperties = []; var masterPropertyString = LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER); if (masterPropertyString && masterPropertyString.length && masterPropertyString.length > 0) { __masterProperties = JSON.parse(masterPropertyString); } if (__masterProperties.length > 0) { //ensure property types (backwards compatibility) $.each(__masterProperties, function (propIndex, property) { switch (property.dataType) { case 0: property.dataType = "String"; break; case 1: property.dataType = "Double"; break; case 2: property.dataType = "Date"; break; case 3: property.dataType = "Boolean"; break; case 4: property.dataType = "Currency"; break; } }); defer.resolve(__masterProperties); } else { if (SessionFactory.GetServiceUrl() === "") { defer.resolve([]); } else { $http({ method: "get", url: SessionFactory.GetServiceUrl() + "Property/MasterProperties" }).success(function (response) { __masterProperties = response; //save to local storage LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER, JSON.stringify(__masterProperties)); defer.resolve(__masterProperties); }).error(function () { defer.reject({ message: "Error Loading Master Properties" }); }); } } return defer.promise; } function GetPropertyById(propertyID) { var deferred = $.Deferred(); getAllProperties().then(function (properties) { var matches = $.grep(properties, function (prop) { return parseInt(prop.propertyID, 10) === parseInt(propertyID, 10); }); if (matches.length > 0) { deferred.resolve(matches[0]); } else { deferred.reject({ message: "Property " + propertyID + " Not Found" }); } }); return deferred.promise(); } function GetPropertiesByPosition() { var deferred = $.Deferred(); getAllProperties().then(function (properties) { var sortedProperties = properties.sort(function (a, b) { var aPos = parseInt(a.position, 10); var bPos = parseInt(b.position, 10); return ((aPos < bPos) ? -1 : ((aPos > bPos) ? 1 : 0)); }); deferred.resolve(sortedProperties); }); return deferred.promise(); } function UpdatePropertyPositions(sortedArrayOfPropertyIds) { var defer = $q.defer(); getAllProperties().then(function (properties) { var iPos, masterPropertyArrayIndex, matches; for (iPos = 0; iPos < sortedArrayOfPropertyIds.length; iPos++) { //find the property in the master properties array masterPropertyArrayIndex = -1; matches = $.grep(properties, function (prop, propIndex) { if (prop.propertyID === parseInt(sortedArrayOfPropertyIds[iPos], 10)) { masterPropertyArrayIndex = propIndex; } return prop.propertyID === parseInt(sortedArrayOfPropertyIds[iPos], 10); }); //update the position if (masterPropertyArrayIndex > -1) { properties[masterPropertyArrayIndex].position = iPos; } } //re-sort __masterProperties = properties.sort(function (a, b) { var aPos = parseInt(a.position, 10); var bPos = parseInt(b.position, 10); return ((aPos < bPos) ? -1 : ((aPos > bPos) ? 1 : 0)); }); //save the new array to local storage LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER, JSON.stringify(__masterProperties)); defer.resolve(__masterProperties); }); return defer.promise; } function SaveOptionsChanges(propertiesFromOptions) { var defer = $q.defer(); __masterProperties = propertiesFromOptions; LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.USERDEFINEDPROPERTYCOLUMNORDER, JSON.stringify(__masterProperties)); defer.resolve(__masterProperties); return defer.promise; } //retrieve properties based upon document type selection function PropertiesForDocumentTypes(docTypeIds, restrictPropertiesToCommon) { var defer = $q.defer(); $http({ method: "post", url: SessionFactory.GetServiceUrl() + "Property/PropertiesTable", data: { "documentTypes": docTypeIds, "restrictPropertiesToCommon": restrictPropertiesToCommon } }).success(function (response) { $.each(response, function (propertyIndex) { var masterProperty = _.find(__masterProperties, function (p) { return p.propertyID == response[propertyIndex].propertyID; }); if (masterProperty) { response[propertyIndex].decimalPlaces = masterProperty.decimalPlaces; } }); defer.resolve(response); }).error(function () { defer.reject({ message: "Error Loading Properties For Document Types" }); }); return defer.promise; } function GetLookupOptions(lookupControl, otherControlsInGroup) { var defer = $q.defer(); var LookupRequestModel = {}; LookupRequestModel.PropertyId = lookupControl.propertyID; LookupRequestModel.Text = lookupControl.value; LookupRequestModel.GroupKey = lookupControl.groupValue; LookupRequestModel.GroupValues = []; $.each(otherControlsInGroup, function (idx) { LookupRequestModel.GroupValues.push({ DynamicUIFieldId: otherControlsInGroup[idx].propertyId, Text: otherControlsInGroup[idx].value, }); }); var request = $http({ method: "post", url: SessionFactory.GetServiceUrl() + "Property/GetPropertyLookupData", data: LookupRequestModel }).success(function (response) { defer.resolve(response); }).error(function (response, status) { defer.reject(response); }); return defer.promise; } } })(); (function () { 'use strict'; angular.module('Session').factory('SessionFactory', ['LocalStorageService', '$rootScope', '$http', SessionFactory]); function SessionFactory(LocalStorageService, $rootScope, $http) { //return public API return ({ SetAuthCode: SetAuthCode, GetAuthcode: GetAuthcode, GetAuthcodeLastAccessed: GetAuthcodeLastAccessed, SetRole: SetRole, GetRole: GetRole, SetUserName: SetUserName, GetUserName: GetUserName, SetLoginId: SetLoginId, GetLoginId: GetLoginId, SetUserDescription:SetUserDescription, GetUserDescription: GetUserDescription, SetUserEmail:SetUserEmail, GetUserEmail: GetUserEmail, SetServiceUrl: SetServiceUrl, GetServiceUrl: GetServiceUrl, SetSmartFormsServiceURL: SetSmartFormsServiceURL, GetSmartFormsServiceURL: GetSmartFormsServiceURL, SetTopLevelFolderSingular: SetTopLevelFolderSingular, GetTopLevelFolderSingular: GetTopLevelFolderSingular, SetTopLevelFolderPlural: SetTopLevelFolderPlural, GetTopLevelFolderPlural: GetTopLevelFolderPlural, SetTopLevelFolders: SetTopLevelFolders, GetTopLevelFolders: GetTopLevelFolders, SetDocumentTypes: SetDocumentTypes, GetDocumentTypes: GetDocumentTypes, ClearCredentials: ClearCredentials, isAuthenticated: isAuthenticated, isAuthorized: isAuthorized, SetRolePermissions: SetRolePermissions, GetRolePermissions: GetRolePermissions, SetWorkflowPermission: SetWorkflowPermission, GetWorkflowPermission: GetWorkflowPermission, SetQuickSearchPermission: SetQuickSearchPermission, GetQuickSearchPermission: GetQuickSearchPermission, SetIsLDAPUser: SetIsLDAPUser, GetIsLDAPUser: GetIsLDAPUser, SetRemoteShellComponents: SetRemoteShellComponents, GetRemoteShellComponents: GetRemoteShellComponents, SetSiteCode: SetSiteCode, GetSiteCode: GetSiteCode, }); // --- // PRIVATE PROPERTIES // --- var __authCode = ""; var __role = ""; var __loginId = ""; var __name = ""; var __userDescription = ""; var __userEmail = ""; var __serviceURL = ""; var __smartFormsServiceURL = ""; var __topLevelFolderSingular = ""; var __topLevelFolderPlural = ""; var __topLevelFolders = []; var __documentTypes = []; var __permissions = []; var __hasWorkflowPermission = false; var __hasQuickSearchPermission = false; var __isLDAPUser = false; var __remoteShellComponents = []; var __siteCode = ""; // --- // PUBLIC PROPERTIES. // --- function SetAuthCode(authCode, keepSessionAfterClosingBrowser) { __authCode = String(authCode); //add auth code to all requests from this point forward $http.defaults.headers.common['authCode'] = __authCode; // jshint ignore:line //update global scope $("#AuthCode").val(__authCode); $("#KeepSessionAfterClosingBrowser").val(keepSessionAfterClosingBrowser); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.AUTHCODE, __authCode); LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.AUTHCODE_LASTACCESSED, new Date().toISOString()); localStorage.setItem("authcode", __authCode); } function GetAuthcode() { return __authCode; } function GetAuthcodeLastAccessed() { try { return Date.parse(LocalStorageService.GetProperty(LocalStorageService.PropertyKeyEnum.AUTHCODE_LASTACCESSED)); } catch (e) { console.log("error caught parsing AUTHCODE_LASTACCESSED"); return new Date(0, 0, 0, 0, 0, 0, 0); } } function SetRole(role) { __role = String(role); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.ROLE, __role); } function GetRole() { return __role; } function SetLoginId(loginId) { __loginId = String(loginId); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.LOGINID, __loginId); } function GetLoginId() { return __loginId; } function SetUserName(name) { __name = String(name); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.USERNAME, __name); } function GetUserName() { return __name; } function SetUserDescription(description) { __userDescription = String(description); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.USERDESCRIPTION, __userDescription); } function GetUserDescription() { return __userDescription; } function SetUserEmail(email) { __userEmail = String(email); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.USEREMAIL, __userEmail); } function GetUserEmail() { return __userEmail; } function SetServiceUrl(ServiceURL) { //save the service url __serviceURL = String(ServiceURL); //save service url into gloabl scope //DefaultWebServiceUrl = __serviceURL; $("#WebServiceUrl").val(__serviceURL); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.SERVICEURL, __serviceURL); } function GetServiceUrl() { return __serviceURL; } function SetSmartFormsServiceURL(ServiceURL) { //save the service url __smartFormsServiceURL = String(ServiceURL); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.SMARTFORMSSERVICEURL, __smartFormsServiceURL); } function GetSmartFormsServiceURL() { return __smartFormsServiceURL; } function SetTopLevelFolderSingular(TopLevelFolderSingular) { //save the service url __topLevelFolderSingular = String(TopLevelFolderSingular); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.TOPLEVELFOLDERSINGULAR, __topLevelFolderSingular); } function GetTopLevelFolderSingular() { return __topLevelFolderSingular; } function SetTopLevelFolderPlural(TopLevelFolderPlural) { //save the service url __topLevelFolderPlural = String(TopLevelFolderPlural); //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.TOPLEVELFOLDERPLURAL, __topLevelFolderPlural); } function GetTopLevelFolderPlural() { return __topLevelFolderPlural; } function SetTopLevelFolders(TopLevelFolders) { //save the top level folders __topLevelFolders = TopLevelFolders; //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.TOPLEVELFOLDERS, JSON.stringify(TopLevelFolders)); } function GetTopLevelFolders() { return __topLevelFolders; } function SetDocumentTypes(docTypes) { //save the document types __documentTypes = docTypes; //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.DOCUMENTTYPES, JSON.stringify(docTypes)); } function GetDocumentTypes() { return __documentTypes; } function SetRolePermissions(permissions) { __permissions = permissions; //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.ROLEPERMISSIONS, JSON.stringify(permissions)); } function GetRolePermissions() { return __permissions; } function SetWorkflowPermission(hasWorkflowPermission) { __hasWorkflowPermission = hasWorkflowPermission; //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.HASWORKFLOWPERMISSIONS, __hasWorkflowPermission); } function GetWorkflowPermission() { return __hasWorkflowPermission; } function SetQuickSearchPermission(hasQuickSearchPermission) { __hasQuickSearchPermission = hasQuickSearchPermission; //store in local storage for retrieval on refresh LocalStorageService.SetProperty(LocalStorageService.PropertyKeyEnum.HASQUICKSEARCHFLOWPERMISSIONS, __hasQuickSearchPermission); } function GetQuickSearchPermission() { return __hasQuickSearchPermission; } function SetIsLDAPUser(setting) { __isLDAPUser = setting; } function GetIsLDAPUser() { return __isLDAPUser; } function SetRemoteShellComponents(remoteShellComponents) { //save the service url __remoteShellComponents = remoteShellComponents; } function GetRemoteShellComponents() { return __remoteShellComponents; } function SetSiteCode(value) { __siteCode = value || ""; } function GetSiteCode() { return __siteCode; } // --- // PUBLIC METHODS. // --- function ClearCredentials() { //console.log("ClearCredentials called"); __authCode = ""; __loginId = ""; __name = ""; __userDescription = ""; __serviceURL = ""; __smartFormsServiceURL = ""; __topLevelFolderSingular = ""; __topLevelFolderPlural = ""; __topLevelFolders = []; __remoteShellComponents = []; __siteCode = ""; delete $rootScope.isAuthenticated; LocalStorageService.WipeSessionStorage(); //localStorage.removeItem(LocalStorageService.PropertyKeyEnum.AUTHCODE); delete $http.defaults.headers.common['authCode']; } function isAuthenticated() { //console.log("isAuthenticated: " + !!$rootScope.authCode); return !!__authCode; } function isAuthorized(authorizedRoles) { if (!angular.isArray(authorizedRoles)) { authorizedRoles = [authorizedRoles]; } //console.log("isAuthorized: " + (authService.isAuthenticated() && authorizedRoles.indexOf(__role) !== -1)); return (isAuthenticated() && authorizedRoles.indexOf(__role) !== -1); } } })(); (function () { 'use strict'; angular.module('CommonDirectives').directive('annotationSummaryTab', ['ngTableParams', '$filter', 'DocumentService', annotationSummaryTab]); function annotationSummaryTab(ngTableParams, $filter, DocumentService) { return { restrict: 'E', templateUrl: "tpl.AnnotationSummaryTab.html", scope: true, link: function (scope, element, attrs) { element.on('$destroy', function () { //console.log("annotationSummaryTab element destroyed"); scope.AnnotationSummaryTable = null; scope.CurrentAnnotationSummary = null; }); }, controller: ['$scope', '$element', function ($scope, $element) { $scope.CurrentAnnotationSummary = null; //used to display the annotation text in the annotation summary section $scope.SetCurrentAnnotationSummary = function (annotationSummary) { $scope.CurrentAnnotationSummary = annotationSummary; }; function buildTable() { if ($scope.AnnotationSummaryTable) { $scope.AnnotationSummaryTable.reload(); } else { //initialize the annotation summary table $scope.AnnotationSummaryTable = new ngTableParams({ page: 1, // show first page count: 10, // count per page sorting: { Created: 'asc' // initial sorting } }, { counts: [], // hides page sizes total: ($scope.document.AnnotationSummary) ? $scope.document.AnnotationSummary.length : 0, // length of data getData: function ($defer, params) { if (!$scope.document.AnnotationSummary || $scope.document.AnnotationSummary.length === 0) { $defer.resolve([]); } else { var orderedData = []; switch (params.orderBy()[0]) { case "-Created": //descending Created can't be handled by angular since it used a text comparator orderedData = $scope.document.AnnotationSummary.sort(function (a, b) { a = new Date(a.Created); b = new Date(b.Created); return a > b ? -1 : a < b ? 1 : 0; }); break; case "+Created": //ascending Created can't be handled by angular since it used a text comparator orderedData = $scope.document.AnnotationSummary.sort(function (a, b) { a = new Date(a.Created); b = new Date(b.Created); return a > b ? 1 : a < b ? -1 : 0; }); break; default: // use build-in angular filter orderedData = $filter('orderBy')($scope.document.AnnotationSummary, params.orderBy()); break; } params.total($scope.document.AnnotationSummary.length); $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } } }); //$scope.AnnotationSummaryTable.settings().$scope = $scope; } } $scope.$watch("document.AnnotationSummary", function () { if ($scope.document && $scope.document !== null) { buildTable(); } }); $scope.$on("$destroy", function () { //console.log("destroy in annotationSummaryTab"); $scope.AnnotationSummaryTable = null; }); }] }; } })(); (function () { 'use strict'; angular.module('CommonDirectives').directive('auditHistoryTab', ['ngTableParams', '$filter', 'DocumentService', auditHistoryTab]); function auditHistoryTab(ngTableParams, $filter, DocumentService) { return { restrict: 'E', templateUrl: "tpl.AuditHistoryTab.html", scope: true, link: function (scope, element, attrs) { element.on('$destroy', function () { //console.log("auditHistoryTab element destroyed"); scope.AuditHistTable = null; }); }, controller: ['$scope', '$element', function ($scope, $element) { function buildTable() { if ($scope.AuditHistTable) { $scope.AuditHistTable.reload(); } else { //initialize the audit history table $scope.AuditHistTable = new ngTableParams({ page: 1, // show first page count: 20, // count per page sorting: { ActionDateTime: 'asc' // initial sorting } }, { counts: [], // hides page sizes total: ($scope.document.AuditHistory) ? $scope.document.AuditHistory.length : 0, // length of data getData: function ($defer, params) { if (!$scope.document.AuditHistory || $scope.document.AuditHistory.length === 0) { $defer.resolve([]); } else { var orderedData = []; switch (params.orderBy()[0]) { case "-ActionDateTime": //descending ActionDateTime can't be handled by angular since it used a text comparator orderedData = $scope.document.AuditHistory.sort(function (a, b) { let a1 = new Date(a.ActionDateTime); let b1 = new Date(b.ActionDateTime); return b1 - a1 || b["AuditDocActionId"] - a["AuditDocActionId"]; }); break; case "+ActionDateTime": //ascending ActionDateTime can't be handled by angular since it used a text comparator orderedData = $scope.document.AuditHistory.sort(function (a, b) { let a1 = new Date(a.ActionDateTime); let b1 = new Date(b.ActionDateTime); return a1 - b1 || a["AuditDocActionId"] - b["AuditDocActionId"]; }); break; default: let sortOrder = "asc"; let field = params.orderBy()[0].substring(1); if (params.orderBy()[0].substring(0, 1) == "-") { sortOrder = "desc"; } if (sortOrder === "desc") { orderedData = $scope.document.AuditHistory.sort(function (a, b) { let a1 = a[field]; let b1 = b[field]; return b1 - a1 || b["AuditDocActionId"] - a["AuditDocActionId"]; }); } else { orderedData = $scope.document.AuditHistory.sort(function (a, b) { let a1 = a[field]; let b1 = b[field]; return a1 - b1 || a["AuditDocActionId"] - b["AuditDocActionId"]; }); } break; } params.total($scope.document.AuditHistory.length); $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } } }); $scope.AuditHistTable.settings().$scope = $scope; } } $scope.$watch("document.AuditHistory", function () { if ($scope.document && $scope.document !== null) { buildTable(); } }); $scope.ToggleDetails = function (parent) { console.log("ToggleDetails: " + parent.AuditDocActionId); if (!angular.isDefined(parent.IsOpen)) { parent.IsOpen = true; } else { if (parent.IsOpen === true) { parent.IsOpen = false; } else { parent.IsOpen = true; } } console.log("IsOpen: " + parent.IsOpen); }; $scope.$on("$destroy", function () { //console.log("destroy in auditHistoryTab"); $scope.AuditHistTable = null; }); }] }; } })(); (function () { 'use strict'; angular.module('CommonDirectives').directive('detailsTab', ['$rootScope', 'DocumentService', 'PropertyService', 'LibraryFunctions', 'ngTableParams', detailsTab]); function detailsTab($rootScope, DocumentService, PropertyService, LibraryFunctions, ngTableParams) { return { restrict: 'E', templateUrl: "tpl.DetailsTab.html", scope: true, link: function (scope, element, attrs) { //element.on('$destroy', function () { // //console.log("detailsTab element destroyed"); //}); }, controller: ['$scope', '$element', function ($scope, $element) { $scope.uniqueid = LibraryFunctions.generateUUID(); $scope.TopLevelFolderNameSingular = $rootScope.TopLevelFolderNameSingular; $scope.InfoSectionCollapsed = false; $scope.OriginationSectionCollapsed = true; $scope.PropertiesSectionCollapsed = false; //language changes $scope.$on('$localeChangeSuccess', function () { buildIndexTable(); }); var unregisterReloadDocument_eventHandler = $rootScope.$on("DocumentUpdated", function (event, args) { //reload the index values if (args.documentid === parseInt($scope.document.DocumentID, 10)) { DocumentService.GetIndexProperties($scope.document.DocumentID).then(function (indexPropertyInfo) { $scope.document.IndexPropertyInfo = indexPropertyInfo; }); } }); $scope.$watchCollection("document.IndexPropertyInfo", function () { if (!$scope.document || $scope.document === null || !$scope.document.DocumentID) { return; } $scope.IndexTable = null; //add dataTypes to the Index Property collection for formatting in the tree displays if ($scope.document.IndexPropertyInfo && $scope.document.IndexPropertyInfo !== null) { $.each($scope.document.IndexPropertyInfo, function (idx, property) { //PropertyService.GetPropertyById(property.propertyId).then(function (masterProperty) { // $scope.document.IndexPropertyInfo[idx].dataType = masterProperty.dataType; // $scope.document.IndexPropertyInfo[idx].IsDirty = false; //}); if (property.dataType === "Date") { $scope.document.IndexPropertyInfo[idx].value = LibraryFunctions.parseDate(property.value, "L"); } $.each(property.Children, function (childidx, childproperty) { if (childproperty.dataType === "Date") { property.Children[childidx].value = LibraryFunctions.parseDate(childproperty.value, "L"); } }); }); buildIndexTable(); } }); $scope.$watchCollection("document.OriginationInfo", function () { if (!$scope.document || $scope.document === null || !$scope.document.DocumentID) { return; } if ($scope.document.OriginationInfo && $scope.document.OriginationInfo !== null) { $.each($scope.document.OriginationInfo, function (index) { var page = $scope.document.OriginationInfo[index].DocumentInfo_Page; var elements = String(page).split(" of "); $scope.document.OriginationInfo[index].sortIndex = parseInt(elements[0], 10); elements = null; page = null; }); } }); //$scope.$watchGroup(["document.DocumentInfo", "document.IndexPropertyInfo", "document.OriginationInfo"], function () { // if (!$scope.document || $scope.document === null || !$scope.document.DocumentID) { // return; // } // if ($scope.document.OriginationInfo && $scope.document.OriginationInfo !== null) { // $.each($scope.document.OriginationInfo, function (index) { // var page = $scope.document.OriginationInfo[index].DocumentInfo_Page; // var elements = String(page).split(" of "); // $scope.document.OriginationInfo[index].sortIndex = parseInt(elements[0], 10); // elements = null; // page = null; // }); // } // //add dataTypes to the Index Property collection for formatting in the tree displays // if ($scope.document.IndexPropertyInfo && $scope.document.IndexPropertyInfo !== null) { // $.each($scope.document.IndexPropertyInfo, function (idx, property) { // //PropertyService.GetPropertyById(property.propertyId).then(function (masterProperty) { // // $scope.document.IndexPropertyInfo[idx].dataType = masterProperty.dataType; // // $scope.document.IndexPropertyInfo[idx].IsDirty = false; // //}); // if (property.dataType == "Date") { // $scope.document.IndexPropertyInfo[idx].value = LibraryFunctions.parseDate(property.value, "L"); // } // $.each(property.Children, function (childidx, childproperty) { // if (childproperty.dataType == "Date") { // property.Children[childidx].value = LibraryFunctions.parseDate(childproperty.value, "L"); // } // }); // }); // buildIndexTable(); // } //}); //function SortBySequence(a, b) { // var aName = a.sequenceNumber; // var bName = b.sequenceNumber; // return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0)); //} function buildIndexTable() { if ($scope.IndexTable) { $scope.IndexTable.reload(); } else { //initialize the audit history table $scope.IndexTable = new ngTableParams({ page: 1, // show first page count: 20, // count per page sorting: { sequenceNumber: 'asc' // initial sorting } }, { counts: [], // hides page sizes total: ($scope.document.IndexPropertyInfo) ? $scope.document.IndexPropertyInfo.length : 0, // length of data getData: function ($defer, params) { if (!$scope.document.IndexPropertyInfo || $scope.document.IndexPropertyInfo.length === 0) { $defer.resolve([]); } else { //var orderedData = $scope.document.IndexPropertyInfo.sort(SortBySequence); //var orderedData = _.orderBy($scope.document.IndexPropertyInfo, ['sequenceNumber', 'groupValue']); $defer.resolve($scope.document.IndexPropertyInfo.slice((params.page() - 1) * params.count(), params.page() * params.count())); } } }); $scope.IndexTable.settings().$scope = $scope; } } $scope.ToggleDetails = function (parent) { if (!angular.isDefined(parent.IsOpen)) { parent.IsOpen = false; } else { if (parent.IsOpen === true) { parent.IsOpen = false; } else { parent.IsOpen = true; } } }; $scope.$on("$destroy", function () { //console.log("destroy in detailsTab"); $scope.IndexTable = null; unregisterReloadDocument_eventHandler(); }); }] }; } })(); (function () { 'use strict'; angular.module('CommonDirectives').directive('documentDelete', ['$rootScope', 'SessionFactory', 'DocumentService', 'LibraryFunctions', '$translate', 'growl', 'modalService', documentDelete]); function documentDelete($rootScope, SessionFactory, DocumentService, LibraryFunctions, $translate, growl, modalService) { return { scope: { SelectedDocuments: "=selectedDocuments", HostGridId: "=?hostId" }, compile: function (el) { el.attr('title', $translate.instant("RESULTSTOOLBAR_DELETEBUTTON_TITLE")); }, controller: ['$scope', '$element', function ($scope, $element) { //language changes $scope.$on('$localeChangeSuccess', function () { $element.attr('title', $translate.instant("RESULTSTOOLBAR_DELETEBUTTON_TITLE")); }); var documentIdsToDelete = []; var confirmListHtml = ""; $scope.clickingCallback = function () { documentIdsToDelete = []; confirmListHtml = ""; //rebuild id arrays if ($.isArray($scope.SelectedDocuments)) { documentIdsToDelete = $.map($scope.SelectedDocuments, function (document) { return document.DocumentID; }); $.each($scope.SelectedDocuments, function (index, document) { var date = LibraryFunctions.parseDate(document.EntryDate, "L LT"); //confirmList.push($translate.instant("DOCUMENTDELETECONFIRM_LISTITEM", { documentType: document.DocumentType, docid: document.DocumentID, entrydate: date })); // {{documentType}} ({{docid}}) Entered {{entrydate}} confirmListHtml += ""; }); } else { documentIdsToDelete.push($scope.SelectedDocuments.DocumentID); var date = LibraryFunctions.parseDate($scope.SelectedDocuments.EntryDate, "L LT"); //confirmList.push($translate.instant("DOCUMENTDELETECONFIRM_LISTITEM", { documentType: $scope.SelectedDocuments.DocumentType, docid: $scope.SelectedDocuments.DocumentID, entrydate: date })); // {{documentType}} ({{docid}}) Entered {{entrydate}} confirmListHtml += ""; } confirmListHtml += "
" + $translate.instant("SYSTEMPROPERTY_DOCUMENTID_SHORT") + "" + $translate.instant("SYSTEMPROPERTY_DOCUMENTTYPE") + "" + $translate.instant("SYSTEMPROPERTY_ENTRYDATE") + "
" + document.DocumentID + "" + document.DocumentType + "" + date + "
" + $scope.SelectedDocuments.DocumentID + "" + $scope.SelectedDocuments.DocumentType + "" + date + "
"; modalService.showModal({}, { closeButtonText: $translate.instant("GLOBAL_NO"), actionButtonText: $translate.instant("GLOBAL_YES"), headerText: $translate.instant("DOCUMENTDELETECONFIRM_LABEL"), bodyText: confirmListHtml }).then(function (result) { if (result) { DocumentService.DeleteDocuments(documentIdsToDelete).then(function () { $rootScope.$broadcast("documents_deleted", { "DeletedDocumentIDs": documentIdsToDelete, "gridID": $scope.HostGridId }); }, function (errorResponse) { growl.error(JSON.stringify(errorResponse), { ttl: 5000, disableCountDown: true }); }); } }, function (response) { console.log(response); }); }; $element.bind('click', $scope.clickingCallback); $scope.$on("$destroy", function () { //console.log("$destroy in documentDelete") $element.unbind(); }); }] }; } })(); (function () { 'use strict'; angular.module('CommonDirectives').directive('documentEmail', ['SessionFactory', 'LocalStorageService', '$uibModal', 'DocumentService', '$translate', documentEmail]); function documentEmail(SessionFactory, LocalStorageService, $uibModal, DocumentService, $translate) { return { scope: { SelectedDocuments: "=selectedDocuments" }, compile: function (el) { el.attr('title', $translate.instant("VIEWER_EMAIL_BUTTON_TITLE")); }, controller: ['$scope', '$element', function ($scope, $element) { //language changes $scope.$on('$localeChangeSuccess', function () { $element.attr('title', $translate.instant("VIEWER_EMAIL_BUTTON_TITLE")); }); var documentIdsToEmail = []; //email scope $scope.DialogModel = {}; $scope.DialogModel.To = ""; $scope.DialogModel.From = SessionFactory.GetUserEmail(); $scope.DialogModel.FromExists = SessionFactory.GetUserEmail().length > 0; $scope.DialogModel.Subject = ""; $scope.DialogModel.Body = ""; $scope.DialogModel.AppendNotes = false; $scope.DialogModel.Attachments = []; $scope.DialogModel.ErrorMessage = ""; $scope.clickingCallback = function () { documentIdsToEmail = []; $scope.DialogModel = {}; $scope.DialogModel.To = ""; $scope.DialogModel.From = SessionFactory.GetUserEmail(); $scope.DialogModel.FromExists = String(SessionFactory.GetUserEmail()) !== null && String(SessionFactory.GetUserEmail()) !== ""; $scope.DialogModel.Subject = ""; $scope.DialogModel.Body = ""; $scope.DialogModel.AppendNotes = false; $scope.DialogModel.Attachments = []; $scope.DialogModel.ErrorMessage = ""; $scope.DialogModel.TopLevelFolderNameSingular = SessionFactory.GetTopLevelFolderSingular(); $scope.CanAppendNotes = true; //rebuild id arrays if ($.isArray($scope.SelectedDocuments)) { documentIdsToEmail = $.map($scope.SelectedDocuments, function (document) { return document.DocumentID; }); $scope.DialogModel.Attachments = $scope.SelectedDocuments; $.each($scope.SelectedDocuments, function (index) { if (!$scope.SelectedDocuments[index]['dlPermViewNotes']) { $scope.CanAppendNotes = false; } }); } else { documentIdsToEmail.push($scope.SelectedDocuments.DocumentID); $scope.DialogModel.Attachments = []; $scope.DialogModel.Attachments.push($scope.SelectedDocuments); $scope.CanAppendNotes = $scope.SelectedDocuments['dlPermViewNotes']; } $scope.EmailModalHeader = $translate.instant("EMAIL_MODAL_HEADER"); $scope.EmailModalToLabel = $translate.instant("EMAIL_MODAL_TO"); $scope.EmailModalFromLabel = $translate.instant("EMAIL_MODAL_FROM"); $scope.EmailModalSubjectLabel = $translate.instant("EMAIL_MODAL_SUBJECT"); $scope.EmailModalBodyLabel = $translate.instant("EMAIL_MODAL_BODY"); $scope.AppendNotesLabel = $translate.instant("EMAIL_MODAL_APPENDNOTES"); $scope.InvalidEmailMessage = $translate.instant("EMAIL_MODAL_INVALIDEMAIL"); $scope.RequiredFieldMessage = $translate.instant("GLOBAL_REQUIREDFIELD"); var emailDialogHTML = '' + '' + '