Catalog alignment
[sdc.git] / catalog-ui / src / app / app.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 'use strict';
22
23 import * as _ from "lodash";
24 import "reflect-metadata";
25 import 'ng-infinite-scroll';
26 import './modules/filters.ts';
27 import './modules/utils.ts';
28 import './modules/directive-module.ts';
29 import './modules/service-module';
30 import './modules/view-model-module.ts';
31 import {SdcUiCommon, SdcUiComponents, SdcUiServices} from 'onap-ui-angular';
32 import {
33     AngularJSBridge,
34     CookieService,
35     DataTypesService,
36     EcompHeaderService,
37     LeftPaletteLoaderService
38 } from "./services";
39 import {CacheService, CatalogService, HomeService} from "./services-ng2";
40 import {AuthenticationService} from "app/ng2/services/authentication.service";
41 import {CHANGE_COMPONENT_CSAR_VERSION_FLAG, PREVIOUS_CSAR_COMPONENT, States} from "./utils";
42 import {IAppConfigurtaion, IAppMenu, IHostedApplication, Resource} from "./models";
43 import {ComponentFactory} from "./utils/component-factory";
44 import {Component} from "./models/components/component";
45 import {IUserProperties} from "./models/user";
46 import {WorkspaceService} from "./ng2/pages/workspace/workspace.service";
47
48 let moduleName:string = 'sdcApp';
49 let viewModelsModuleName:string = 'Sdc.ViewModels';
50 let directivesModuleName:string = 'Sdc.Directives';
51 let servicesModuleName:string = 'Sdc.Services';
52 let filtersModuleName:string = 'Sdc.Filters';
53 let utilsModuleName:string = 'Sdc.Utils';
54
55 // Load configuration according to environment.
56 declare var __ENV__:string;
57 let sdcConfig:IAppConfigurtaion;
58 let sdcMenu:IAppMenu;
59 let pathPrefix:string = '';
60 if (__ENV__ === 'dev') {
61     sdcConfig = require('./../../configurations/dev.js');
62 } else if (__ENV__ === 'prod') {
63     sdcConfig = require('./../../configurations/prod.js');
64     pathPrefix = 'sdc1/';
65 } else {
66     console.log("ERROR: Environment configuration not found!");
67 }
68 sdcMenu = require('./../../configurations/menu.js');
69
70 let dependentModules:Array<string> = [
71     'ui.router',
72     'ui.bootstrap',
73     'ui.bootstrap.tpls',
74     'ngDragDrop',
75     'ui-notification',
76     'ngResource',
77     'ngSanitize',
78     'naif.base64',
79     'base64',
80     'uuid4',
81     'checklist-model',
82     'angular.filter',
83     'pascalprecht.translate',
84     '720kb.tooltips',
85     'restangular',
86     'angular-clipboard',
87     'angularResizable',
88     'infinite-scroll',
89     viewModelsModuleName,
90     directivesModuleName,
91     servicesModuleName,
92     filtersModuleName,
93     utilsModuleName
94 ];
95
96 // ===================== Hosted applications section ====================
97 // Define here new hosted apps
98 let hostedApplications:Array<IHostedApplication> = [
99     {
100         "moduleName": "dcaeApp",
101         "navTitle": "DCAE",
102         "defaultState": 'dcae.app.home',
103         "state": {
104             "name": "dcae",
105             "url": "/dcae",
106             "relativeHtmlPath": 'dcae-app/dcae-app-view.html',
107             "controllerName": '.DcaeAppViewModel'
108         }
109     }
110 ];
111
112 // Check if module exists (in case the javascript was not loaded).
113 let isModuleExists = (moduleName:string):boolean => {
114     try {
115         angular.module(moduleName);
116         dependentModules.push(moduleName);
117         return true;
118     } catch (e) {
119         console.log('Module ' + moduleName + ' does not exists');
120         return false;
121     }
122 };
123
124 // Check which hosted applications exists
125 _.each(hostedApplications, (hostedApp)=> {
126     if (isModuleExists(hostedApp.moduleName)) {
127         hostedApp['exists'] = true;
128     }
129 });
130 // ===================== Hosted applications section ====================
131
132 export const ng1appModule:ng.IModule = angular.module(moduleName, dependentModules);
133
134 ng1appModule.config([
135     '$stateProvider',
136     '$translateProvider',
137     '$urlRouterProvider',
138     '$httpProvider',
139     'tooltipsConfigProvider',
140     'NotificationProvider',
141     ($stateProvider:any,
142      $translateProvider:any,
143      $urlRouterProvider:ng.ui.IUrlRouterProvider,
144      $httpProvider:ng.IHttpProvider,
145      tooltipsConfigProvider:any,
146      NotificationProvider:any):void => {
147
148         NotificationProvider.setOptions({
149             delay: 5000,
150             startTop: 10,
151             startRight: 10,
152             closeOnClick: true,
153             verticalSpacing: 20,
154             horizontalSpacing: 20,
155             positionX: 'right',
156             positionY: 'top'
157         });
158         NotificationProvider.options.templateUrl = 'notification-custom-template.html';
159
160         $translateProvider.useStaticFilesLoader({
161             prefix: pathPrefix + 'assets/languages/',
162             langKey: '',
163             suffix: '.json?d=' + (new Date()).getTime()
164         });
165         $translateProvider.useSanitizeValueStrategy('escaped');
166         $translateProvider.preferredLanguage('en_US');
167
168         $httpProvider.interceptors.push('Sdc.Services.HeaderInterceptor');
169         $urlRouterProvider.otherwise('dashboard');
170
171         $stateProvider.state(
172             'dashboard', {
173                 url: '/dashboard?show&folder&filter.term&filter.status&filter.distributed',
174                 template: '<home-page></home-page>',
175                 permissions: ['DESIGNER']
176             },
177
178         );
179
180
181         let componentsParam:Array<any> = ['$stateParams', 'HomeService', 'CatalogService', 'Sdc.Services.CacheService', ($stateParams:any, HomeService:HomeService, CatalogService:CatalogService, cacheService:CacheService) => {
182             if (cacheService.get('breadcrumbsComponentsState') === $stateParams.previousState) {
183                 const breadcrumbsComponents = cacheService.get('breadcrumbsComponents');
184                 if (breadcrumbsComponents) {
185                     return breadcrumbsComponents;
186                 }
187             } else {
188                 let breadcrumbsComponentsObservable;
189                 if ($stateParams.previousState === 'dashboard') {
190                     breadcrumbsComponentsObservable = HomeService.getAllComponents(true);
191                 } else if ($stateParams.previousState === 'catalog') {
192                     breadcrumbsComponentsObservable = CatalogService.getCatalog();
193                 } else {
194                     cacheService.remove('breadcrumbsComponentsState');
195                     cacheService.remove('breadcrumbsComponents');
196                     return [];
197                 }
198                 breadcrumbsComponentsObservable.subscribe((components) => {
199                     cacheService.set('breadcrumbsComponentsState', $stateParams.previousState);
200                     cacheService.set('breadcrumbsComponents', components);
201                 });
202                 return breadcrumbsComponentsObservable;
203             }
204         }];
205
206         const oldWorkspaceController:Array<any> = ['$location', ($location:ng.ILocationService) => {
207             // redirect old /workspace/* urls to /catalog/workspace/* url
208             const newUrl = '/catalog' + $location.url();
209             console.log('old workspace path - redirecting to:', newUrl);
210             $location.url(newUrl);
211         }];
212
213         $stateProvider.state(
214             'workspace-old', {
215                 url: '/workspace/:id/:type/*workspaceInnerPath',
216                 controller: oldWorkspaceController
217             }
218         );
219
220         $stateProvider.state(
221             'workspace', {
222                 url: '/:previousState/workspace/:id/:type/',
223                 params: {'importedFile': null, 'componentCsar': null, 'resourceType': null, 'disableButtons': null},
224                 templateUrl: './view-models/workspace/workspace-view.html',
225                 controller: viewModelsModuleName + '.WorkspaceViewModel',
226                 resolve: {
227                     injectComponent: ['$stateParams', 'ComponentFactory', 'workspaceService', 'Sdc.Services.CacheService', function ($stateParams, ComponentFactory:ComponentFactory, workspaceService:WorkspaceService, cacheService: CacheService) {
228
229                         if ($stateParams.id && $stateParams.id.length) { //need to check length in case ID is an empty string
230                             return ComponentFactory.getComponentWithMetadataFromServer($stateParams.type.toUpperCase(), $stateParams.id).then(
231                                 (component:Component)=> {
232                                     if ($stateParams.componentCsar && component.isResource()){
233                                         if((<Resource>component).csarVersion != $stateParams.componentCsar.csarVersion) {
234                                             cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
235                                         }
236                                         component = ComponentFactory.updateComponentFromCsar($stateParams.componentCsar, <Resource>component);
237                                     }
238                                     workspaceService.setComponentMetadata(component.componentMetadata);
239                                     return component;
240                                 });
241                         } else if ($stateParams.componentCsar && $stateParams.componentCsar.csarUUID) {
242                             return $stateParams.componentCsar;
243                         } else {
244                             let emptyComponent = ComponentFactory.createEmptyComponent($stateParams.type.toUpperCase());
245                             if (emptyComponent.isResource() && $stateParams.resourceType) {
246                                 // Set the resource type
247                                 (<Resource>emptyComponent).resourceType = $stateParams.resourceType;
248                             }
249                             if ($stateParams.importedFile) {
250                                 (<Resource>emptyComponent).importedFile = $stateParams.importedFile;
251                             }
252                             return emptyComponent;
253                         }
254                     }],
255                     components: componentsParam
256                 }
257             }
258         );
259
260         $stateProvider.state(
261             States.WORKSPACE_GENERAL, {
262                 url: 'general',
263                 parent: 'workspace',
264                 controller: viewModelsModuleName + '.GeneralViewModel',
265                 templateUrl: './view-models/workspace/tabs/general/general-view.html',
266                 data: {unsavedChanges: false, bodyClass: 'general'}
267             }
268         );
269
270
271         $stateProvider.state(
272             States.WORKSPACE_INFORMATION_ARTIFACTS, {
273                 url: 'information_artifacts',
274                 parent: 'workspace',
275                 template:'<information-artifact-page></information-artifact-page>'
276             }
277         );
278
279         $stateProvider.state(
280             States.WORKSPACE_TOSCA_ARTIFACTS, {
281                 url: 'tosca_artifacts',
282                 parent: 'workspace',
283                 template:'<tosca-artifact-page></tosca-artifact-page>'
284             }
285         );
286
287
288         $stateProvider.state(
289             States.WORKSPACE_DEPLOYMENT_ARTIFACTS, {
290                 url: 'deployment_artifacts',
291                 parent: 'workspace',
292                 template:'<deployment-artifact-page></deployment-artifact-page>'
293             }
294         );
295
296         $stateProvider.state(
297             States.WORKSPACE_PROPERTIES, {
298                 url: 'properties',
299                 parent: 'workspace',
300                 controller: viewModelsModuleName + '.PropertiesViewModel',
301                 templateUrl: './view-models/workspace/tabs/properties/properties-view.html',
302                 data: {
303                     bodyClass: 'properties'
304                 }
305             }
306         );
307
308         $stateProvider.state(
309             States.WORKSPACE_PROPERTIES_ASSIGNMENT, {
310                 url: 'properties_assignment',
311                 params: {'component': null},
312                 template: '<properties-assignment></properties-assignment>',
313                 parent: 'workspace',
314                 resolve: {
315                     componentData: ['injectComponent', '$stateParams', function (injectComponent:Component, $stateParams) {
316                         //injectComponent.componentService = null; // this is for not passing the service so no one will use old api and start using new api
317                         $stateParams.component = injectComponent;
318                         return injectComponent;
319                     }],
320                 },
321                 data: {
322                     bodyClass: 'properties-assignment'
323                 }
324             }
325         );
326
327         $stateProvider.state(
328             States.WORKSPACE_ATTRIBUTES, {
329                 url: 'attributes',
330                 parent: 'workspace',
331                 template: '<attributes></attributes>',
332             }
333         );
334
335         $stateProvider.state(
336             States.WORKSPACE_REQUIREMENTS_AND_CAPABILITIES, {
337                 url: 'req_and_capabilities',
338                 parent: 'workspace',
339                 template: '<req-and-capabilities></req-and-capabilities>',
340                 data: {
341                     bodyClass: 'attributes'
342                 }
343             }
344         );
345         $stateProvider.state(
346             States.WORKSPACE_REQUIREMENTS_AND_CAPABILITIES_EDITABLE, {
347                 url: 'req_and_capabilities_editable',
348                 parent: 'workspace',
349                 template: '<req-and-capabilities></req-and-capabilities>',
350                 data: {
351                     bodyClass: 'attributes'
352                 }
353             }
354         );
355
356
357         $stateProvider.state(
358             States.WORKSPACE_MANAGEMENT_WORKFLOW, {
359                 parent: 'workspace',
360                 url: 'management_workflow',
361                 templateUrl: './view-models/workspace/tabs/management-workflow/management-workflow-view.html',
362                 controller: viewModelsModuleName + '.ManagementWorkflowViewModel'
363             }
364         );
365
366         $stateProvider.state(
367             States.WORKSPACE_NETWORK_CALL_FLOW, {
368                 parent: 'workspace',
369                 url: 'network_call_flow',
370                 templateUrl: './view-models/workspace/tabs/network-call-flow/network-call-flow-view.html',
371                 controller: viewModelsModuleName + '.NetworkCallFlowViewModel'
372             }
373         );
374
375
376         $stateProvider.state(
377             States.WORKSPACE_COMPOSITION, {
378                 url: 'composition/',
379                 params: {'component': null},
380                 parent: 'workspace',
381                 template: '<composition-page></composition-page>',
382                 resolve: {
383                     componentData: ['injectComponent', '$stateParams', function (injectComponent:Component, $stateParams) {
384                         //injectComponent.componentService = null; // this is for not passing the service so no one will use old api and start using new api
385                         $stateParams.component = injectComponent;
386                         return injectComponent;
387                     }],
388                 },
389                 data: {
390                     bodyClass: 'composition'
391                 }
392             }
393         );
394
395         $stateProvider.state(
396             States.WORKSPACE_ACTIVITY_LOG, {
397                 url: 'activity_log/',
398                 parent: 'workspace',
399                 template: '<activity-log></activity-log>',
400             }
401
402         );
403
404         $stateProvider.state(
405             States.WORKSPACE_DISTRIBUTION, {
406                 url: 'distribution',
407                 parent: 'workspace',
408                 template: '<distribution></distribution>',
409             }
410
411         );
412
413         $stateProvider.state(
414             States.WORKSPACE_DEPLOYMENT, {
415                 url: 'deployment/',
416                 parent: 'workspace',
417                 template: '<deployment-page></deployment-page>',
418
419             }
420         );
421
422         $stateProvider.state(
423             'workspace.composition.details', {
424                 url: 'details',
425                 parent: 'workspace.composition',
426                 resolve: {
427                     componentData: ['injectComponent', '$stateParams', function (injectComponent:Component, $stateParams) {
428                         $stateParams.component = injectComponent;
429                         return injectComponent;
430                     }],
431                 }
432
433             }
434         );
435
436         $stateProvider.state(
437             'workspace.composition.properties', {
438                 url: 'properties',
439                 parent: 'workspace.composition'
440             }
441         );
442
443         $stateProvider.state(
444             'workspace.composition.artifacts', {
445                 url: 'artifacts',
446                 parent: 'workspace.composition'
447
448             }
449         );
450
451         $stateProvider.state(
452             'workspace.composition.relations', {
453                 url: 'relations',
454                 parent: 'workspace.composition'
455             }
456         );
457
458         $stateProvider.state(
459             'workspace.composition.structure', {
460                 url: 'structure',
461                 parent: 'workspace.composition'
462             }
463         );
464         $stateProvider.state(
465             'workspace.composition.lifecycle', {
466                 url: 'lifecycle',
467                 parent: 'workspace.composition'
468             }
469         );
470
471         $stateProvider.state(
472             'workspace.composition.api', {
473                 url: 'api',
474                 parent: 'workspace.composition'
475             }
476         );
477         $stateProvider.state(
478             'workspace.composition.deployment', {
479                 url: 'deployment',
480                 parent: 'workspace.composition'
481             }
482         );
483
484         $stateProvider.state(
485             States.WORKSPACE_INTERFACE_OPERATION, {
486                 url: 'interface_operation',
487                 parent: 'workspace',
488                 controller: viewModelsModuleName + '.InterfaceOperationViewModel',
489                 templateUrl: './view-models/workspace/tabs/interface-operation/interface-operation-view.html',
490                 data: {
491                     bodyClass: 'interface_operation'
492                 }
493             }
494         );
495
496         $stateProvider.state(
497             'workspace.plugins', {
498                 url: 'plugins/*path',
499                 parent: 'workspace',
500                 template: '<plugin-context-view></plugin-context-view>',
501                 resolve: {
502                     componentData: ['injectComponent', '$stateParams', function (injectComponent:Component, $stateParams) {
503                         $stateParams.component = injectComponent;
504                         return injectComponent;
505                     }],
506                 }
507
508             }
509         );
510
511         $stateProvider.state(
512             'adminDashboard', {
513                 url: '/adminDashboard',
514                 templateUrl: './view-models/admin-dashboard/admin-dashboard-view.html',
515                 controller: viewModelsModuleName + '.AdminDashboardViewModel',
516                 permissions: ['ADMIN']
517             }
518         );
519
520         $stateProvider.state(
521             'onboardVendor', {
522                 url: '/onboardVendor',
523                 templateUrl: './view-models/onboard-vendor/onboard-vendor-view.html',
524                 controller: viewModelsModuleName + '.OnboardVendorViewModel'
525             }
526         );
527
528         $stateProvider.state(
529             'plugins', {
530                 url: '/plugins/*path',
531                 template: '<plugin-tab-view></plugin-tab-view>'
532             }
533         );
534
535         // Build the states for all hosted apps dynamically
536         _.each(hostedApplications, (hostedApp)=> {
537             if (hostedApp.exists) {
538                 $stateProvider.state(
539                     hostedApp.state.name, {
540                         url: hostedApp.state.url,
541                         templateUrl: './view-models/dcae-app/dcae-app-view.html',
542                         controller: viewModelsModuleName + hostedApp.state.controllerName
543                     }
544                 );
545             }
546         });
547
548         $stateProvider.state(
549             'catalog', {
550                 url: '/catalog?filter.components&filter.resourceSubTypes&filter.categories&filter.statuses&filter.order&filter.term&filter.active',
551                 template: '<catalog-page></catalog-page>',
552                 resolve: {
553                     auth: ["$q", "AuthenticationServiceNg2", ($q:any, authService:AuthenticationService) => {
554                         let userInfo:IUserProperties = authService.getLoggedinUser();
555                         if (userInfo) {
556                             return $q.when(userInfo);
557                         } else {
558                             return $q.reject({authenticated: false});
559                         }
560                     }]
561                 }
562             }
563         );
564
565         $stateProvider.state(
566             'error-403', {
567                 url: '/error-403',
568                 templateUrl: "./view-models/modals/error-modal/error-403-view.html",
569                 controller: viewModelsModuleName + '.ErrorViewModel'
570             }
571         );
572
573         tooltipsConfigProvider.options({
574             side: 'bottom',
575             delay: '600',
576             class: 'tooltip-custom',
577             lazy: 0,
578             try: 0
579         });
580
581     }
582 ]);
583
584 ng1appModule.value('ValidationPattern', /^[\s\w\&_.:-]{1,1024}$/);
585 ng1appModule.value('ComponentNameValidationPattern', /^(?=.*[^. ])[\s\w\&_.:-]{1,1024}$/); //DE250513 - same as ValidationPattern above, plus requirement that name not consist of dots and/or spaces alone.
586 ng1appModule.value('PropertyNameValidationPattern', /^[a-zA-Z0-9_:-]{1,50}$/);// DE210977
587 ng1appModule.value('TagValidationPattern', /^[\s\w_.-]{1,50}$/);
588 ng1appModule.value('VendorReleaseValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
589 ng1appModule.value('VendorNameValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,60}$/);
590 ng1appModule.value('VendorModelNumberValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,65}$/);
591 ng1appModule.value('ServiceTypeAndRoleValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,256}$/);
592 ng1appModule.value('ContactIdValidationPattern', /^[\s\w-]{1,50}$/);
593 ng1appModule.value('UserIdValidationPattern', /^[\s\w-]{1,50}$/);
594 ng1appModule.value('LabelValidationPattern', /^[\sa-zA-Z0-9+-]{1,25}$/);
595 ng1appModule.value('UrlValidationPattern', /^(https?|ftp):\/\/(((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([A-Za-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([A-Za-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/);
596 ng1appModule.value('IntegerValidationPattern', /^(([-+]?\d+)|([-+]?0x[0-9a-fA-F]+))$/);
597 ng1appModule.value('IntegerNoLeadingZeroValidationPattern', /^(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)$/);
598 ng1appModule.value('FloatValidationPattern', /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?$/);
599 ng1appModule.value('NumberValidationPattern', /^((([-+]?\d+)|([-+]?0x[0-9a-fA-F]+))|([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?))$/);
600 ng1appModule.value('KeyValidationPattern', /^[\s\w-]{1,50}$/);
601 ng1appModule.value('CommentValidationPattern', /^[\u0000-\u00BF]*$/);
602 ng1appModule.value('BooleanValidationPattern', /^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])$/);
603 ng1appModule.value('MapKeyValidationPattern', /^[\w]{1,50}$/);
604
605 ng1appModule.constant('sdcConfig', sdcConfig);
606 ng1appModule.constant('sdcMenu', sdcMenu);
607
608 ng1appModule.run([
609     '$http',
610     'Sdc.Services.CacheService',
611     'Sdc.Services.CookieService',
612     'AuthenticationServiceNg2',
613     '$state',
614     '$rootScope',
615     '$location',
616     'sdcMenu',
617     'Sdc.Services.EcompHeaderService',
618     'LeftPaletteLoaderService',
619     'Sdc.Services.DataTypesService',
620     'AngularJSBridge',
621     '$templateCache',
622     'ModalServiceSdcUI',
623     ($http:ng.IHttpService,
624      cacheService:CacheService,
625      cookieService:CookieService,
626      authService:AuthenticationService,
627      $state:ng.ui.IStateService,
628      $rootScope:ng.IRootScopeService,
629      $location:ng.ILocationService,
630      sdcMenu:IAppMenu,
631      ecompHeaderService:EcompHeaderService,
632      LeftPaletteLoaderService:LeftPaletteLoaderService,
633      DataTypesService:DataTypesService,
634      AngularJSBridge,
635      $templateCache:ng.ITemplateCacheService,
636      ModalServiceSdcUI:SdcUiServices.ModalService):void => {
637         $templateCache.put('notification-custom-template.html', require('./view-models/shared/notification-custom-template.html'));
638         $templateCache.put('notification-custom-template.html', require('./view-models/shared/notification-custom-template.html'));
639
640         // Add hosted applications to sdcConfig
641         sdcConfig.hostedApplications = hostedApplications;
642
643         //handle http config
644         $http.defaults.withCredentials = true;
645         // $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
646         $http.defaults.headers.common[cookieService.getUserIdSuffix()] = cookieService.getUserId();
647
648         DataTypesService.initDataTypes();
649
650         //handle stateChangeStart
651         let internalDeregisterStateChangeStartWatcher:Function = ():void => {
652             if (deregisterStateChangeStartWatcher) {
653                 deregisterStateChangeStartWatcher();
654                 deregisterStateChangeStartWatcher = null;
655             }
656             if (deregisterStateChangeSuccessWatcher) {
657                 deregisterStateChangeSuccessWatcher();
658                 deregisterStateChangeSuccessWatcher = null;
659             }
660         };
661
662         let removeLoader:Function = ():void => {
663             $(".sdc-loading-page .main-loader").addClass("animated fadeOut");
664             $(".sdc-loading-page .caption1").addClass("animated fadeOut");
665             $(".sdc-loading-page .caption2").addClass("animated fadeOut");
666             window.setTimeout(():void=> {
667                 $(".sdc-loading-page .main-loader").css("display", "none");
668                 $(".sdc-loading-page .caption1").css("display", "none");
669                 $(".sdc-loading-page .caption2").css("display", "none");
670                 $(".sdc-loading-page").addClass("animated fadeOut");
671             }, 1000);
672         };
673
674         let onNavigateOut:Function = (toState, toParams):void => {
675             let onOk:Function = ():void => {
676                 $state.current.data.unsavedChanges = false;
677                 $state.go(toState.name, toParams);
678             };
679
680             let data = sdcMenu.alertMessages.exitWithoutSaving;
681             const okButton = {
682                 testId: "OK",
683                 text: sdcMenu.alertMessages.okButton,
684                 type: SdcUiCommon.ButtonType.warning,
685                 callback: onOk,
686                 closeModal: true
687             } as SdcUiComponents.ModalButtonComponent;
688             //open notify to user if changes are not saved
689             ModalServiceSdcUI.openWarningModal(data.title,
690                 data.message,
691                 'navigate-modal',
692                 [okButton]);
693         };
694
695         let onStateChangeStart:Function = (event, toState, toParams, fromState, fromParams):void => {
696             console.info((new Date()).getTime());
697             console.info('$stateChangeStart', toState.name);
698             if (toState.name !== 'error-403' && !authService.getLoggedinUser()) {
699
700
701                 authService.authenticate().subscribe((userInfo:IUserProperties) => {
702                     if (!doesUserHasAccess(toState, userInfo)) {
703                         $state.go('error-403');
704                         console.info('User has no permissions');
705                         return;
706                     }
707                     authService.setLoggedinUser(userInfo);
708                     setTimeout(function () {
709
710                         removeLoader();
711
712                         if (authService.getLoggedinUser().role === 'ADMIN') {
713                             // toState.name = "adminDashboard";
714                             $state.go("adminDashboard", toParams);
715                             return;
716                         }
717
718                         // After user authorized init categories
719                         window.setTimeout(():void=> {
720                             if ($state.current.name === '') {
721                                 $state.go(toState.name, toParams);
722                             }
723
724                             console.log("------$state.current.name=" + $state.current.name);
725
726                         }, 1000);
727
728                     }, 0);
729
730                 }, () => {
731                     $state.go('error-403');
732                 });
733             }
734             else if (authService.getLoggedinUser()) {
735                 let user:IUserProperties =  authService.getLoggedinUser();
736                 if(!cacheService.contains('user')){
737                     cacheService.set('user', user);
738                 }
739
740                 if (!doesUserHasAccess(toState, authService.getLoggedinUser())) {
741                     event.preventDefault();
742                     $state.go('error-403');
743                     console.info('User has no permissions');
744                 }
745
746                 if (authService.getLoggedinUser().role === 'ADMIN') {
747                     // toState.name = "adminDashboard";
748                     $state.go("adminDashboard", toParams);
749                     return;
750                 }
751
752
753                 //if form is dirty and not save  - notify to user
754                 if (fromState.data && fromState.data.unsavedChanges && fromParams.id != toParams.id) {
755                     event.preventDefault();
756                     onNavigateOut(toState, toParams);
757                 }
758             }
759
760             // if enetering workspace, set the previousState param
761             if (toState.name.indexOf('workspace') !== -1) {
762                 if (!toParams.previousState) {
763                     const tmpPreviousState1 = fromParams && fromParams.previousState;
764                     const tmpPreviousState2 = (['dashboard', 'catalog'].indexOf(fromState.name) !== -1) ? fromState.name : 'catalog';
765                     toParams.previousState = tmpPreviousState1 || tmpPreviousState2;
766                 }
767             }
768
769         };
770
771         let onStateChangeSuccess:Function = (event, toState, toParams, fromState, fromParams):void => {
772             console.info('$stateChangeSuccess', toState.name);
773
774             // Workaround in case we are entering other state then workspace (user move to catalog)
775             // remove the changeComponentCsarVersion, user should open again the VSP list and select one for update.
776             if (toState.name.indexOf('workspace') === -1) {
777                 if (cacheService.contains(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
778                     cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
779                 }
780                 if (cacheService.contains(PREVIOUS_CSAR_COMPONENT)){
781                     cacheService.remove(PREVIOUS_CSAR_COMPONENT);
782                 }
783             }
784
785             //set body class
786             $rootScope['bodyClass'] = 'default-class';
787             if (toState.data && toState.data.bodyClass) {
788                 $rootScope['bodyClass'] = toState.data.bodyClass;
789             }
790         };
791
792         let doesUserHasAccess:Function = (toState, user):boolean => {
793
794             let isUserHasAccess = true;
795             if (toState.permissions && toState.permissions.length > 0) {
796                 isUserHasAccess = _.includes(toState.permissions, user.role);
797             }
798             return isUserHasAccess;
799         };
800         let deregisterStateChangeStartWatcher:Function;
801         let deregisterStateChangeSuccessWatcher:Function;
802
803         let registerStateChangeStartWatcher:Function = ():void => {
804             internalDeregisterStateChangeStartWatcher();
805             console.info('registerStateChangeStartWatcher $stateChangeStart');
806             deregisterStateChangeStartWatcher = $rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams):void => {
807                 onStateChangeStart(event, toState, toParams, fromState, fromParams);
808             });
809             deregisterStateChangeSuccessWatcher = $rootScope.$on('$stateChangeSuccess', (event, toState, toParams, fromState, fromParams):void => {
810                 onStateChangeSuccess(event, toState, toParams, fromState, fromParams);
811             });
812         };
813         registerStateChangeStartWatcher();
814     }]);
815