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