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