Final commit to master merge from
[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
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).then(
229                                 (component:Component)=> {
230                                 if ($stateParams.componentCsar){
231                                     component = ComponentFactory.updateComponentFromCsar($stateParams.componentCsar, <Resource>component);
232                                 }
233                                 return component;
234                             });
235                         } else if ($stateParams.componentCsar && $stateParams.componentCsar.csarUUID) {
236                             return $stateParams.componentCsar;
237                         } else {
238                             let emptyComponent = ComponentFactory.createEmptyComponent($stateParams.type.toUpperCase());
239                             if (emptyComponent.isResource() && $stateParams.resourceType) {
240                                 // Set the resource type
241                                 (<Resource>emptyComponent).resourceType = $stateParams.resourceType;
242                             }
243                             if ($stateParams.importedFile) {
244                                 (<Resource>emptyComponent).importedFile = $stateParams.importedFile;
245                             }
246                             return emptyComponent;
247                         }
248                     }],
249                     components: componentsParam
250                 }
251             }
252         );
253
254         $stateProvider.state(
255             States.WORKSPACE_GENERAL, {
256                 url: 'general',
257                 parent: 'workspace',
258                 controller: viewModelsModuleName + '.GeneralViewModel',
259                 templateUrl: './view-models/workspace/tabs/general/general-view.html',
260                 data: {unsavedChanges: false, bodyClass: 'general'}
261             }
262         );
263
264         $stateProvider.state(
265             States.WORKSPACE_ACTIVITY_LOG, {
266                 url: 'activity_log',
267                 parent: 'workspace',
268                 controller: viewModelsModuleName + '.ActivityLogViewModel',
269                 templateUrl: './view-models/workspace/tabs/activity-log/activity-log.html',
270                 data: {unsavedChanges: false}
271             }
272         );
273
274         $stateProvider.state(
275             States.WORKSPACE_DEPLOYMENT_ARTIFACTS, {
276                 url: 'deployment_artifacts',
277                 parent: 'workspace',
278                 controller: viewModelsModuleName + '.DeploymentArtifactsViewModel',
279                 templateUrl: './view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html',
280                 data: {
281                     bodyClass: 'deployment_artifacts'
282                 }
283             }
284         );
285
286         $stateProvider.state(
287             States.WORKSPACE_INFORMATION_ARTIFACTS, {
288                 url: 'information_artifacts',
289                 parent: 'workspace',
290                 controller: viewModelsModuleName + '.InformationArtifactsViewModel',
291                 templateUrl: './view-models/workspace/tabs/information-artifacts/information-artifacts-view.html',
292                 data: {
293                     bodyClass: 'information_artifacts'
294                 }
295             }
296         );
297
298         $stateProvider.state(
299             States.WORKSPACE_TOSCA_ARTIFACTS, {
300                 url: 'tosca_artifacts',
301                 parent: 'workspace',
302                 controller: viewModelsModuleName + '.ToscaArtifactsViewModel',
303                 templateUrl: './view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html',
304                 data: {
305                     bodyClass: 'tosca_artifacts'
306                 }
307             }
308         );
309
310         $stateProvider.state(
311             States.WORKSPACE_PROPERTIES, {
312                 url: 'properties',
313                 parent: 'workspace',
314                 controller: viewModelsModuleName + '.PropertiesViewModel',
315                 templateUrl: './view-models/workspace/tabs/properties/properties-view.html',
316                 data: {
317                     bodyClass: 'properties'
318                 }
319             }
320         );
321
322         $stateProvider.state(
323             States.WORKSPACE_SERVICE_INPUTS, {
324                 url: 'service_inputs',
325                 parent: 'workspace',
326                 controller: viewModelsModuleName + '.ServiceInputsViewModel',
327                 templateUrl: './view-models/workspace/tabs/inputs/service-input/service-inputs-view.html',
328                 data: {
329                     bodyClass: 'workspace-inputs'
330                 }
331             }
332         );
333
334         $stateProvider.state(
335             States.WORKSPACE_PROPERTIES_ASSIGNMENT, {
336                 url: 'properties_assignment',
337                 params: {'component': null},
338                 template: '<properties-assignment></properties-assignment>',
339                 parent: 'workspace',
340                 resolve: {
341                     componentData: ['injectComponent', '$stateParams', function (injectComponent:Component, $stateParams) {
342                         //injectComponent.componentService = null; // this is for not passing the service so no one will use old api and start using new api
343                         $stateParams.component = injectComponent;
344                         return injectComponent;
345                     }],
346                 },
347                 data: {
348                     bodyClass: 'properties-assignment'
349                 }
350             }
351         );
352
353         $stateProvider.state(
354             States.WORKSPACE_RESOURCE_INPUTS, {
355                 url: 'resource_inputs',
356                 parent: 'workspace',
357                 controller: viewModelsModuleName + '.ResourceInputsViewModel',
358                 templateUrl: './view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html',
359                 data: {
360                     bodyClass: 'workspace-inputs'
361                 }
362             }
363         );
364
365         $stateProvider.state(
366             States.WORKSPACE_ATTRIBUTES, {
367                 url: 'attributes',
368                 parent: 'workspace',
369                 controller: viewModelsModuleName + '.AttributesViewModel',
370                 templateUrl: './view-models/workspace/tabs/attributes/attributes-view.html',
371                 data: {
372                     bodyClass: 'attributes'
373                 }
374             }
375         );
376
377         $stateProvider.state(
378             States.WORKSPACE_REQUIREMENTS_AND_CAPABILITIES, {
379                 url: 'req_and_capabilities',
380                 parent: 'workspace',
381                 controller: viewModelsModuleName + '.ReqAndCapabilitiesViewModel',
382                 templateUrl: './view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html',
383                 data: {
384                     bodyClass: 'attributes'
385                 }
386             }
387         );
388
389
390         $stateProvider.state(
391             States.WORKSPACE_MANAGEMENT_WORKFLOW, {
392                 parent: 'workspace',
393                 url: 'management_workflow',
394                 templateUrl: './view-models/workspace/tabs/management-workflow/management-workflow-view.html',
395                 controller: viewModelsModuleName + '.ManagementWorkflowViewModel'
396             }
397         );
398
399         $stateProvider.state(
400             States.WORKSPACE_NETWORK_CALL_FLOW, {
401                 parent: 'workspace',
402                 url: 'network_call_flow',
403                 templateUrl: './view-models/workspace/tabs/network-call-flow/network-call-flow-view.html',
404                 controller: viewModelsModuleName + '.NetworkCallFlowViewModel'
405             }
406         );
407
408         $stateProvider.state(
409             States.WORKSPACE_DISTRIBUTION, {
410                 parent: 'workspace',
411                 url: 'distribution',
412                 templateUrl: './view-models/workspace/tabs/distribution/distribution-view.html',
413                 controller: viewModelsModuleName + '.DistributionViewModel'
414             }
415         );
416
417         $stateProvider.state(
418             States.WORKSPACE_COMPOSITION, {
419                 url: 'composition/',
420                 parent: 'workspace',
421                 controller: viewModelsModuleName + '.CompositionViewModel',
422                 templateUrl: './view-models/workspace/tabs/composition/composition-view.html',
423                 data: {
424                     bodyClass: 'composition'
425                 }
426             }
427         );
428
429         // $stateProvider.state(
430         //     States.WORKSPACE_NG2, {
431         //         url: 'ng2/',
432         //        component: downgradeComponent({component: NG2Example2Component}), //viewModelsModuleName + '.NG2Example',
433         //        templateUrl: './ng2/view-ng2/ng2.example2/ng2.example2.component.html'
434         //     }
435         // );
436
437         $stateProvider.state(
438             States.WORKSPACE_DEPLOYMENT, {
439                 url: 'deployment/',
440                 parent: 'workspace',
441                 templateUrl: './view-models/workspace/tabs/deployment/deployment-view.html',
442                 controller: viewModelsModuleName + '.DeploymentViewModel',
443                 data: {
444                     bodyClass: 'composition'
445                 }
446             }
447         );
448
449         $stateProvider.state(
450             'workspace.composition.details', {
451                 url: 'details',
452                 parent: 'workspace.composition',
453                 templateUrl: './view-models/workspace/tabs/composition/tabs/details/details-view.html',
454                 controller: viewModelsModuleName + '.DetailsViewModel'
455             }
456         );
457
458         $stateProvider.state(
459             'workspace.composition.properties', {
460                 url: 'properties',
461                 parent: 'workspace.composition',
462                 templateUrl: './view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html',
463                 controller: viewModelsModuleName + '.ResourcePropertiesViewModel'
464             }
465         );
466
467         $stateProvider.state(
468             'workspace.composition.artifacts', {
469                 url: 'artifacts',
470                 parent: 'workspace.composition',
471                 templateUrl: './view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html',
472                 controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
473             }
474         );
475
476         $stateProvider.state(
477             'workspace.composition.relations', {
478                 url: 'relations',
479                 parent: 'workspace.composition',
480                 templateUrl: './view-models/workspace/tabs/composition/tabs/relations/relations-view.html',
481                 controller: viewModelsModuleName + '.RelationsViewModel'
482             }
483         );
484
485         $stateProvider.state(
486             'workspace.composition.structure', {
487                 url: 'structure',
488                 parent: 'workspace.composition',
489                 templateUrl: './view-models/workspace/tabs/composition/tabs/structure/structure-view.html',
490                 controller: viewModelsModuleName + '.StructureViewModel'
491             }
492         );
493         $stateProvider.state(
494             'workspace.composition.lifecycle', {
495                 url: 'lifecycle',
496                 parent: 'workspace.composition',
497                 templateUrl: './view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html',
498                 controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
499             }
500         );
501
502         $stateProvider.state(
503             'workspace.composition.api', {
504                 url: 'api',
505                 parent: 'workspace.composition',
506                 templateUrl: './view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html',
507                 controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
508             }
509         );
510         $stateProvider.state(
511             'workspace.composition.deployment', {
512                 url: 'deployment',
513                 parent: 'workspace.composition',
514                 templateUrl: './view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html',
515                 controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
516             }
517         );
518
519         $stateProvider.state(
520             'adminDashboard', {
521                 url: '/adminDashboard',
522                 templateUrl: './view-models/admin-dashboard/admin-dashboard-view.html',
523                 controller: viewModelsModuleName + '.AdminDashboardViewModel',
524                 permissions: ['ADMIN']
525             }
526         );
527
528         $stateProvider.state(
529             'onboardVendor', {
530                 url: '/onboardVendor',
531                 templateUrl: './view-models/onboard-vendor/onboard-vendor-view.html',
532                 controller: viewModelsModuleName + '.OnboardVendorViewModel'//,
533             }
534         );
535
536         // Build the states for all hosted apps dynamically
537         _.each(hostedApplications, (hostedApp)=> {
538             if (hostedApp.exists) {
539                 $stateProvider.state(
540                     hostedApp.state.name, {
541                         url: hostedApp.state.url,
542                         templateUrl: './view-models/dcae-app/dcae-app-view.html',
543                         controller: viewModelsModuleName + hostedApp.state.controllerName
544                     }
545                 );
546             }
547         });
548
549         $stateProvider.state(
550             'catalog', {
551                 url: '/catalog',
552                 templateUrl: './view-models/catalog/catalog-view.html',
553                 controller: viewModelsModuleName + '.CatalogViewModel',
554                 resolve: {
555                     auth: ["$q", "UserServiceNg2", ($q:any, userService:UserService) => {
556                         let userInfo:IUserProperties = userService.getLoggedinUser();
557                         if (userInfo) {
558                             return $q.when(userInfo);
559                         } else {
560                             return $q.reject({authenticated: false});
561                         }
562                     }]
563                 }
564             }
565         );
566
567         $stateProvider.state(
568             'support', {
569                 url: '/support',
570                 templateUrl: './view-models/support/support-view.html',
571                 controller: viewModelsModuleName + '.SupportViewModel'
572             }
573         );
574
575         $stateProvider.state(
576             'error-403', {
577                 url: '/error-403',
578                 templateUrl: "./view-models/modals/error-modal/error-403-view.html",
579                 controller: viewModelsModuleName + '.ErrorViewModel'
580             }
581         );
582
583         tooltipsConfigProvider.options({
584             side: 'bottom',
585             delay: '600',
586             class: 'tooltip-custom',
587             lazy: 0,
588             try: 0
589         });
590
591     }
592 ]);
593
594 ng1appModule.value('ValidationPattern', /^[\s\w\&_.:-]{1,1024}$/);
595 ng1appModule.value('ComponentNameValidationPattern', /^(?=.*[^. ])[\s\w\&_.:-]{1,1024}$/); //DE250513 - same as ValidationPattern above, plus requirement that name not consist of dots and/or spaces alone.
596 ng1appModule.value('PropertyNameValidationPattern', /^[a-zA-Z0-9_:-]{1,50}$/);// DE210977
597 ng1appModule.value('TagValidationPattern', /^[\s\w_.-]{1,50}$/);
598 ng1appModule.value('VendorReleaseValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
599 ng1appModule.value('VendorNameValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,60}$/);
600 ng1appModule.value('VendorModelNumberValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,65}$/);
601 ng1appModule.value('ServiceTypeAndRoleValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,256}$/);
602 ng1appModule.value('ContactIdValidationPattern', /^[\s\w-]{1,50}$/);
603 ng1appModule.value('UserIdValidationPattern', /^[\s\w-]{1,50}$/);
604 ng1appModule.value('ProjectCodeValidationPattern', /^[\s\w-]{5,50}$/);
605 ng1appModule.value('LabelValidationPattern', /^[\sa-zA-Z0-9+-]{1,25}$/);
606 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})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/);
607 ng1appModule.value('IntegerValidationPattern', /^(([-+]?\d+)|([-+]?0x[0-9a-fA-F]+))$/);
608 ng1appModule.value('IntegerNoLeadingZeroValidationPattern', /^(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)$/);
609 ng1appModule.value('FloatValidationPattern', /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?$/);
610 ng1appModule.value('NumberValidationPattern', /^((([-+]?\d+)|([-+]?0x[0-9a-fA-F]+))|([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?))$/);
611 ng1appModule.value('KeyValidationPattern', /^[\s\w-]{1,50}$/);
612 ng1appModule.value('CommentValidationPattern', /^[\u0000-\u00BF]*$/);
613 ng1appModule.value('BooleanValidationPattern', /^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])$/);
614 ng1appModule.value('MapKeyValidationPattern', /^[\w]{1,50}$/);
615
616 ng1appModule.constant('sdcConfig', sdcConfig);
617 ng1appModule.constant('sdcMenu', sdcMenu);
618
619 ng1appModule.run([
620     '$http',
621     'Sdc.Services.CacheService',
622     'Sdc.Services.CookieService',
623     'Sdc.Services.ConfigurationUiService',
624     'UserServiceNg2',
625     'Sdc.Services.CategoryResourceService',
626     'Sdc.Services.SdcVersionService',
627     '$state',
628     '$rootScope',
629     '$location',
630     'sdcMenu',
631     'ModalsHandler',
632     'Sdc.Services.EcompHeaderService',
633     'LeftPaletteLoaderService',
634     'Sdc.Services.DataTypesService',
635     'AngularJSBridge',
636     '$templateCache',
637     ($http:ng.IHttpService,
638      cacheService:CacheService,
639      cookieService:CookieService,
640      ConfigurationUi:ConfigurationUiService,
641      userService:UserService,
642      categoryResourceService:ICategoryResourceClass,
643      sdcVersionService:SdcVersionService,
644      $state:ng.ui.IStateService,
645      $rootScope:ng.IRootScopeService,
646      $location:ng.ILocationService,
647      sdcMenu:IAppMenu,
648      ModalsHandler:ModalsHandler,
649      ecompHeaderService:EcompHeaderService,
650      LeftPaletteLoaderService:LeftPaletteLoaderService,
651      DataTypesService:DataTypesService,
652      AngularJSBridge,
653      $templateCache:ng.ITemplateCacheService):void => {
654         $templateCache.put('notification-custom-template.html', require('./view-models/shared/notification-custom-template.html'));
655         $templateCache.put('notification-custom-template.html', require('./view-models/shared/notification-custom-template.html'));
656         //handle cache data - version
657         let initAsdcVersion:Function = ():void => {
658
659             let onFailed = (response) => {
660                 console.info('onFailed initAsdcVersion', response);
661                 cacheService.set('version', 'N/A');
662             };
663
664             let onSuccess = (version:any) => {
665                 let tmpVerArray = version.version.split(".");
666                 let ver = tmpVerArray[0] + "." + tmpVerArray[1] + "." + tmpVerArray[2];
667                 cacheService.set('version', ver);
668             };
669
670             sdcVersionService.getVersion().then(onSuccess, onFailed);
671
672         };
673
674         let initEcompMenu:Function = (user):void => {
675             ecompHeaderService.getMenuItems(user.userId).then((data)=> {
676                 $rootScope['menuItems'] = data;
677             });
678         };
679
680         let initConfigurationUi:Function = ():void => {
681             ConfigurationUi
682                 .getConfigurationUi()
683                 .then((configurationUi:any) => {
684                     cacheService.set('UIConfiguration', configurationUi);
685                 });
686         };
687
688         let initCategories:Function = ():void => {
689             let onError = ():void => {
690                 console.log('Failed to init categories');
691             };
692
693             categoryResourceService.getAllCategories((categories: Categories):void => {
694                 cacheService.set('serviceCategories', categories.serviceCategories);
695                 cacheService.set('resourceCategories', categories.resourceCategories);
696             }, onError);
697         };
698
699         // Add hosted applications to sdcConfig
700         sdcConfig.hostedApplications = hostedApplications;
701
702         //handle http config
703         $http.defaults.withCredentials = true;
704         $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
705         $http.defaults.headers.common[cookieService.getUserIdSuffix()] = cookieService.getUserId();
706
707         initAsdcVersion();
708         initConfigurationUi();
709        // initLeftPalette();
710         DataTypesService.initDataTypes();
711
712         //handle stateChangeStart
713         let internalDeregisterStateChangeStartWatcher:Function = ():void => {
714             if (deregisterStateChangeStartWatcher) {
715                 deregisterStateChangeStartWatcher();
716                 deregisterStateChangeStartWatcher = null;
717             }
718         };
719
720         let removeLoader:Function = ():void => {
721             $(".sdc-loading-page .main-loader").addClass("animated fadeOut");
722             $(".sdc-loading-page .caption1").addClass("animated fadeOut");
723             $(".sdc-loading-page .caption2").addClass("animated fadeOut");
724             window.setTimeout(():void=> {
725                 $(".sdc-loading-page .main-loader").css("display", "none");
726                 $(".sdc-loading-page .caption1").css("display", "none");
727                 $(".sdc-loading-page .caption2").css("display", "none");
728                 $(".sdc-loading-page").addClass("animated fadeOut");
729             }, 1000);
730         };
731
732         let onNavigateOut:Function = (toState, toParams):void => {
733             let onOk = ():void => {
734                 $state.current.data.unsavedChanges = false;
735                 $state.go(toState.name, toParams);
736             };
737
738             let data = sdcMenu.alertMessages.exitWithoutSaving;
739             //open notify to user if changes are not saved
740             ModalsHandler.openAlertModal(data.title, data.message).then(onOk);
741         };
742
743         let onStateChangeStart:Function = (event, toState, toParams, fromState, fromParams):void => {
744             console.info((new Date()).getTime());
745             console.info('$stateChangeStart', toState.name);
746             //set body class
747             $rootScope['bodyClass'] = 'default-class';
748             if (toState.data && toState.data.bodyClass) {
749                 $rootScope['bodyClass'] = toState.data.bodyClass;
750             }
751
752             // Workaround in case we are entering other state then workspace (user move to catalog)
753             // remove the changeComponentCsarVersion, user should open again the VSP list and select one for update.
754             if (toState.name.indexOf('workspace') === -1) {
755                 if (cacheService.contains(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
756                     cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
757                 }
758             }
759
760             //saving last state to params , for breadcrumbs
761             if (['dashboard', 'catalog', 'onboardVendor'].indexOf(fromState.name) > -1) {
762                 toParams.previousState = fromState.name;
763             } else {
764                 toParams.previousState = fromParams.previousState;
765             }
766
767             if (toState.name !== 'error-403' && !userService.getLoggedinUser()) {
768                 internalDeregisterStateChangeStartWatcher();
769                 event.preventDefault();
770
771                 userService.authorize().subscribe((userInfo:IUserProperties) => {
772                     if (!doesUserHasAccess(toState, userInfo)) {
773                         $state.go('error-403');
774                         console.info('User has no permissions');
775                         registerStateChangeStartWatcher();
776                         return;
777                     }
778                     userService.setLoggedinUser(userInfo);
779                     cacheService.set('user', userInfo);
780                     initCategories();
781                     //   initEcompMenu(userInfo);
782                     setTimeout(function () {
783
784                         removeLoader();
785
786                         // initCategories();
787                         if (userService.getLoggedinUser().role === 'ADMIN') {
788                             // toState.name = "adminDashboard";
789                             $state.go("adminDashboard", toParams);
790                             registerStateChangeStartWatcher();
791                             return;
792                         }
793
794                         // After user authorized init categories
795                         window.setTimeout(():void=> {
796                             if ($state.current.name === '') {
797                                 $state.go(toState.name, toParams);
798                             }
799
800                             console.log("------$state.current.name=" + $state.current.name);
801                             console.info('-----registerStateChangeStartWatcher authorize $stateChangeStart');
802                             registerStateChangeStartWatcher();
803
804                         }, 1000);
805
806                     }, 0);
807
808                 }, () => {
809                     $state.go('error-403');
810
811                     console.info('registerStateChangeStartWatcher error-403 $stateChangeStart');
812                     registerStateChangeStartWatcher();
813                 });
814             }
815             else if (userService.getLoggedinUser()) {
816                 internalDeregisterStateChangeStartWatcher();
817                 if (!doesUserHasAccess(toState, userService.getLoggedinUser())) {
818                     event.preventDefault();
819                     $state.go('error-403');
820                     console.info('User has no permissions');
821                 }
822                 if (toState.name === "welcome") {
823                     $state.go("dashboard");
824                 }
825                 registerStateChangeStartWatcher();
826                 //if form is dirty and not save  - notify to user
827                 if (fromState.data && fromState.data.unsavedChanges && fromParams.id != toParams.id) {
828                     event.preventDefault();
829                     onNavigateOut(toState, toParams);
830                 }
831             }
832
833         };
834
835         let doesUserHasAccess:Function = (toState, user):boolean => {
836
837             let isUserHasAccess = true;
838             if (toState.permissions && toState.permissions.length > 0) {
839                 isUserHasAccess = _.includes(toState.permissions, user.role);
840             }
841             return isUserHasAccess;
842         };
843         let deregisterStateChangeStartWatcher:Function;
844
845         let registerStateChangeStartWatcher:Function = ():void => {
846             internalDeregisterStateChangeStartWatcher();
847             console.info('registerStateChangeStartWatcher $stateChangeStart');
848             deregisterStateChangeStartWatcher = $rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams):void => {
849                 onStateChangeStart(event, toState, toParams, fromState, fromParams);
850             });
851         };
852
853         registerStateChangeStartWatcher();
854     }]);
855