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