adminApp.js 17.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
//
// app module for online DPMS
//
var app = angular.module('adminApp', ['ui.tree', 'ui.bootstrap', 'ui.bootstrap.tpls', 'ui.event', 'pascalprecht.translate', 'ngMessages', 'ui.utils',
        'ngRoute', 'ngCookies', 'ngSanitize', 'ct.ui.router.extras', 'chieffancypants.loadingBar', 'ngDraggable', 'ngFileUpload', 'LocalStorageModule', 'exceptionless',
        'app.config', 'app.common', 'app.webservices', 'app.framework', 'app.infrastructure', 'app.basicData', 'app.adminHomePage', 'app.noPermissionPage', 'pasvaz.bindonce', 'vs-repeat', 'ivh.treeview', 'angular-cache',
        'app.systemConfiguration', 'app.cache', 'angularBootstrapNavTree', 'ngAnimate', 'cgNotify', 'angularInlineEdit'
])
    //run blocks are executed after the injector is created and are the first
    //methods that are executed in any Angular app.
    .run(['$log', '$http', 'CacheFactory', '$rootScope', 'userService', 'loginContext', '$q', function ($log, $http, CacheFactory, $rootScope, userService, loginContext, $q) {
        $log.debug('adminApp.run()...');

        $rootScope.adminPermission = constant.adminPermission;

        // 控制用户admin操作权限
        $rootScope.checkUserPermission = function (permissionCode) {
            var deferred = $q.defer();
            var promise = deferred.promise;
            var ret = false;
            userService.getUserPermissionNew(loginContext.userName, function (data) {
                var ret = window.PWC.isHavePermission(permissionCode, data);
                deferred.resolve(ret);
            });

            var successFunction = function (fn) {
                promise.then(function (ret) {
                    fn(ret);
                });
                return this;
            }

            return {
                success: successFunction,
            };
        };

        // 控制用户admin操作权限
        $rootScope.checkUserPermissionList = function (permissionCodeList) {
            var deferred = $q.defer();
            var promise = deferred.promise;
            var model = {};
            userService.getUserPermissionNew(loginContext.userName, function (data) {


                permissionCodeList.forEach(function (permissionCode) {
                    var ret = window.PWC.isHavePermission(permissionCode, data);
                    model[permissionCode] = ret;
                });

                deferred.resolve(model);
            });

            var successFunction = function (fn) {
                promise.then(function (model) {
                    fn(model);
                });
                return this;
            }

            return {
                success: successFunction,
            };
        };

        $http.defaults.headers.common['X-XSRF-Token'] =
            angular.element('input[name="__RequestVerificationToken"]').attr('value');
    }])
    // We always place constant at the beginning of all configuration blocks.
    .constant('application', {
        // the current logged on user
        currentUser: {},
        // convert date to display time based on current user
        toDisplayTimeString: function (dateTime) {
            if (!_.isDate(dateTime)) {
                throw new TypeError('"dateTime" should be "Date" type!');
            }
            return dateTime.toString('h:mmtt').toLowerCase();
        },
        // define angular events for $broadcast/$emit and $on
        events: {
            beforeUnload: 'event:beforeUnload',
            navigateToTab: 'event:navigateToTab',
            showNotificationBar: 'event:showNotificationBar'
        }
    })
    .config(['$urlRouterProvider', function ($urlRouterProvider) {
        //$urlRouterProvider.otherwise('/basicDataInfrastructure/regionManage'); 
    }])
    // only providers and constants should be injected in config block
    .config(['$logProvider', '$translateProvider', '$translatePartialLoaderProvider', 'region', '$compileProvider',
        function ($logProvider, $translateProvider, $translatePartialLoaderProvider, region, $compileProvider) {
            'use strict';
            region = 'zh-CN';
            // to disable various debug runtime information in the compiler to DOM elements.
            $compileProvider.debugInfoEnabled(false);
            // enable output $log.debug by default
            $logProvider.debugEnabled(true);

            // angular-translate configuration
            var configurateTranslation = function () {

                $translateProvider.useLoader('$translatePartialLoader', {
                    // the translation table are organized by language and module under folder 'app/i18n/'
                    urlTemplate: '/app-resources/i18n/{lang}/{part}.json'
                });

                $translateProvider
                    .preferredLanguage(region)
                    .fallbackLanguage(region);

                //https://github.com/Contactis/translations-manager/issues/7
                //https://angular-translate.github.io/docs/#/guide/19_security
                $translateProvider.useSanitizeValueStrategy('escape');
            };

            configurateTranslation();
        }
    ])
    // IE10 fires input event when a placeholder is defined so that form element is in dirty instead of pristine state 
    // refer to: https://github.com/angular/angular.js/issues/2614
    .config(['$provide', function ($provide) {
        $provide.decorator('$sniffer', ['$delegate', function ($sniffer) {
            var msieVersion = parseInt((/msie (\d+)/.exec(angular.lowercase(navigator.userAgent)) || [])[1], 10);
            var hasEvent = $sniffer.hasEvent;
            $sniffer.hasEvent = function (event) {
                if (event === 'input' && msieVersion === 10) {
                    return false;
                }
                hasEvent.call(this, event);
            };
            return $sniffer;
        }]);
    }])
    .config(['$ExceptionlessClient', 'exceptionlessServerURL', function ($ExceptionlessClient, exceptionlessServerURL) {
        if (!PWC.isNullOrEmpty(exceptionlessServerURL)) {
            $ExceptionlessClient.config.apiKey = 'HK0XK49LbufV6E4q8HLW7CGncwSBJvdBrJQwUnzw';
            $ExceptionlessClient.config.serverUrl = exceptionlessServerURL;
            $ExceptionlessClient.config.setUserIdentity('0', 'Anonymous');
            $ExceptionlessClient.config.useSessions();
            $ExceptionlessClient.config.defaultTags.push('JavaScript', 'Angular');
        }
    }])
    .config(['CacheFactoryProvider', function (CacheFactoryProvider) {
        var options = {
            storageMode: 'localStorage', // This cache will use `localStorage`.
            storagePrefix: 'atms.'
        };
        if (!window.localStorage) {
            options.storageImpl = localStoragePolyfill;
        }
        angular.extend(CacheFactoryProvider.defaults, options);
    }])
    .config(['ivhTreeviewOptionsProvider', function (ivhTreeviewOptionsProvider) {
        ivhTreeviewOptionsProvider.set({
            defaultSelectedState: false,
            validate: true,
            // Twisties can be images, custom html, or plain text
            twistieCollapsedTpl: '<i class="fa fa-plus" aria-hidden="true"></i>',
            twistieExpandedTpl: '<i class="fa fa-minus" aria-hidden="true"></i>',
            twistieLeafTpl: '<span style="color:white">&#9679;</span>'
        });
    }])
    // refer to: https://github.com/oitozero/ngSweetAlert
    .factory('SweetAlert', ['$rootScope', '$log', '$translate', function ($rootScope, $log, $translate) {
        $log.debug('SweetAlert.run()...');
        var swal = window.swal;
        //public methods
        var self = {

            swal: function (arg1, arg2, arg3) {
                $rootScope.$evalAsync(function () {
                    if (typeof (arg2) === 'function') {
                        swal(arg1, function (isConfirm) {
                            $rootScope.$evalAsync(function () {
                                arg2(isConfirm);
                            });
                        }, arg3);
                    } else {
                        swal(arg1, arg2, arg3);
                    }
                });
            },
            success: function (title, message) {
                $rootScope.$evalAsync(function () {
                    //swal(title, message, 'success');

                    swal({
                        title: title,
                        text: message,
                        type: "success",
                        confirmButtonText: $translate.instant('Confirm'),
                    });
                });
            },
            error: function (title, message) {
                $rootScope.$evalAsync(function () {
                    //swal(title, message, 'error');
                    swal({
                        title: title,
                        text: message,
                        type: "error",
                        confirmButtonText: $translate.instant('Confirm'),
                    });

                });
            },
            warning: function (title, message) {
                $rootScope.$evalAsync(function () {
                    //swal(title, message, 'warning');
                    swal({
                        title: title,
                        text: message,
                        type: "warning",
                        confirmButtonText: $translate.instant('Confirm'),
                    });
                });
            },
            info: function (title, message) {
                $rootScope.$evalAsync(function () {
                    //swal(title, message, 'info');
                    swal({
                        title: title,
                        text: message,
                        type: "info",
                        confirmButtonText: $translate.instant('Confirm'),
                    });
                });
            }
        };

        return self;
    }])
    //turn off angular-loading-bar spinner
    //refer to https://github.com/chieffancypants/angular-loading-bar
    .config(['cfpLoadingBarProvider', function (cfpLoadingBarProvider) {
        cfpLoadingBarProvider.includeSpinner = false;
    }])
    //initialize localStorage
    //refer to https://github.com/grevory/angular-local-storage#get-started
    .config(['localStorageServiceProvider', function (localStorageServiceProvider) {
        localStorageServiceProvider.setPrefix('pwcdashboard').setStorageType('sessionStorage');
    }])
    // Provide the localization function for application and support async load translation table by parts on demand.
    // Note: When trying to adding new translation resource into .json file, please check if the same KEY is existing 
    // in .json files under i18n folder. Because if two parts have the same property, the property value will be overwrited 
    // by the loaded last part.
    // for example,
    // We load app.json first and then load patient.json. "app.json" file contains a property {"Text" : "Test"} 
    // and "patient.json" file contains property {"Text" : "Overwrite Test"} the "Text" on view will be translated to 
    // be "Overwrite Test".
    .factory('appTranslation', ['$log', '$translatePartialLoader', '$translate',
        function ($log, $translatePartialLoader, $translate) {
            'use strict';
            $log.debug('appTranslation.ctor()...');

            var translation = {
                // part names for modules
                // AppPart is for the translation of application level, not for a module for a business logic.
                appPart: 'app',
                vat:'vat',

                // other parts for business logic
                //worklist: 'worklist',
                //registration: 'registration',
                //report: 'report',
                //clientSetting: 'clientSetting',
                //selfServiceSetting: 'selfServiceSetting',
                cit: 'cit',
                //menu: 'menu',
                role: 'role',
                infrastructure: 'infrastructure',
                //materiallist: 'materiallist',
                basicData: 'basicData',
                systemConfiguration: 'systemConfiguration',
                adminHomePage: 'adminHomePage',
                taxDocumentList: 'taxDocumentList',
                noPermissionPage: 'noPermissionPage',
                //declarationFormConfiguration: 'declarationFormConfiguration',

                /// <summary>
                /// async load translation tables into application for specified part names that required for the view.
                /// </summary>
                /// <param name="partNames">part names of array type</param>
                load: function (partNames) {
                    if (!angular.isArray(partNames)) {
                        throw new TypeError('"partNames" should be an array!');
                    }

                    partNames.forEach(function (name) {
                        $translatePartialLoader.addPart(name);
                    });

                    $translate.refresh();
                },
                loadAll: function () {
                    _.map(_.values(translation), function (part) {
                        if (_.isString(part)) {
                            $translatePartialLoader.addPart(part);
                        }
                    });
                    $translate.refresh();
                }
            };
            return translation;
        }
    ])
    .controller('AdminAppController', ['$rootScope', '$scope', '$log', '$location', '$translate', '$translatePartialLoader',
        '$window', 'appRoute', 'application', 'appTranslation', '$timeout', '$uibModal', 'loginContext', '$ExceptionlessClient', 'signalRSvc', 'userService', '$state', '$q',
       'exceptionlessServerURL', function ($rootScope, $scope, $log, $location, $translate, $translatePartialLoader, $window, appRoute,
            application, appTranslation, $timeout, $uibModal, loginContext, $ExceptionlessClient, signalRSvc, userService, $state, $q, exceptionlessServerURL) {
           'use strict';
           $log.debug('AdminAppController.ctor()...');

           $scope.localName = loginContext.localName;

           if (!PWC.isNullOrEmpty(exceptionlessServerURL)) {
               $ExceptionlessClient.config.setUserIdentity(loginContext.userId, loginContext.localName);
               $ExceptionlessClient.config.useSessions();
           }

           $scope.$on('$locationChangeSuccess', function () {
               $scope.actualLocation = $location.path();
           });

           $scope.$watch(function () {
               return $location.path()
           }, function (newLocation) {
               if ($scope.actualLocation === newLocation) {
                   // back or forward
                   $log.debug('Go back or go forward to view browser history. Url: ' + newLocation);
               }
           });

           $scope.$on('$stateChangeSuccess',
               function () {
                   $log.debug('$stateChangeSuccess: ');
               });

           $scope.$on("$locationChangeStart", function (e, currentLocation, previousLocation) {
               // Do whatever you need to do.
               $rootScope.previousLocation = previousLocation;

           });

           $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {

               // permission control
               var url = toState.url;
               // url: /organizationBusinessUnitView

               if (toState.name) {

                   // 特殊处理有name中有.,也就是那种tab的情况
                   if (toState.name.indexOf('organizationView') > -1) {
                       url = '#/organizationViewInfrastructure' + url;
                   } else if (toState.name.indexOf('masterData.') > -1) {
                       url = '#/masterData' + url;
                   } else if (toState.name.indexOf('financialData.') > -1) {
                       url = '#/financialData' + url;
                   }

                   else {
                       url = '#' + url;
                   }

               } else {
                   url = '#' + url;
               }

               $log.debug('url:' + url + 'toState:' + JSON.stringify(toState));
               if (url.indexOf('noPermissionPage') > -1) {
                   return;
               }

               userService.getUserPermission(loginContext.userName).success(function (data) {
                   var find = null;
                   if (data.navigationUrlList) {
                       find = _.find(data.navigationUrlList, function (num) {

                           // 完全匹配
                           if (url === num) {
                               return true;
                           }

                           // 匹配查询单个机构这种
                           if (url.indexOf(num) > -1) {
                               return true;
                           }

                           return false;
                       });
                   }
                   if (data && (data.isAdmin || find)) {
                       return;
                   } else {
                       $log.debug(url + ':noPermissionPage');
                       event.preventDefault();
                       $state.go('noPermissionPage');
                   }
               });

           });


           // publish unbeforeunload event to child scopes
           $scope.onbeforeunload = function () {
               $scope.$broadcast(application.events.beforeUnload);
           };

           $scope.main = function () {
               $location.path('/main');
               $location.url('main');
           };

           $scope.createDemo = function () {
               $location.path('/accountDemo');
               $location.url($location.path());
           };

           appTranslation.loadAll();

           signalRSvc.initialize();
       }
    ]);