Designer-view component for top-nav
[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 {DesignerFrameComponent} from "./ng2/components/ui/designer/designer-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('designerFrame', downgradeComponent( {component: DesignerFrameComponent, inputs: ['designer']} ) 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             'adminDashboard', {
522                 url: '/adminDashboard',
523                 templateUrl: './view-models/admin-dashboard/admin-dashboard-view.html',
524                 controller: viewModelsModuleName + '.AdminDashboardViewModel',
525                 permissions: ['ADMIN']
526             }
527         );
528
529         $stateProvider.state(
530             'onboardVendor', {
531                 url: '/onboardVendor',
532                 templateUrl: './view-models/onboard-vendor/onboard-vendor-view.html',
533                 controller: viewModelsModuleName + '.OnboardVendorViewModel'//,
534             }
535         );
536
537         $stateProvider.state(
538             'designers', {
539                 url: '/designers/*path',
540                 templateUrl: './view-models/designers/designers-view.html',
541                 controller: viewModelsModuleName + '.DesignersViewModel'
542             }
543         );
544
545         // Build the states for all hosted apps dynamically
546         _.each(hostedApplications, (hostedApp)=> {
547             if (hostedApp.exists) {
548                 $stateProvider.state(
549                     hostedApp.state.name, {
550                         url: hostedApp.state.url,
551                         templateUrl: './view-models/dcae-app/dcae-app-view.html',
552                         controller: viewModelsModuleName + hostedApp.state.controllerName
553                     }
554                 );
555             }
556         });
557
558         $stateProvider.state(
559             'catalog', {
560                 url: '/catalog',
561                 templateUrl: './view-models/catalog/catalog-view.html',
562                 controller: viewModelsModuleName + '.CatalogViewModel',
563                 resolve: {
564                     auth: ["$q", "UserServiceNg2", ($q:any, userService:UserService) => {
565                         let userInfo:IUserProperties = userService.getLoggedinUser();
566                         if (userInfo) {
567                             return $q.when(userInfo);
568                         } else {
569                             return $q.reject({authenticated: false});
570                         }
571                     }]
572                 }
573             }
574         );
575
576         $stateProvider.state(
577             'support', {
578                 url: '/support',
579                 templateUrl: './view-models/support/support-view.html',
580                 controller: viewModelsModuleName + '.SupportViewModel'
581             }
582         );
583
584         $stateProvider.state(
585             'error-403', {
586                 url: '/error-403',
587                 templateUrl: "./view-models/modals/error-modal/error-403-view.html",
588                 controller: viewModelsModuleName + '.ErrorViewModel'
589             }
590         );
591
592         tooltipsConfigProvider.options({
593             side: 'bottom',
594             delay: '600',
595             class: 'tooltip-custom',
596             lazy: 0,
597             try: 0
598         });
599
600     }
601 ]);
602
603 ng1appModule.value('ValidationPattern', /^[\s\w\&_.:-]{1,1024}$/);
604 ng1appModule.value('ComponentNameValidationPattern', /^(?=.*[^. ])[\s\w\&_.:-]{1,1024}$/); //DE250513 - same as ValidationPattern above, plus requirement that name not consist of dots and/or spaces alone.
605 ng1appModule.value('PropertyNameValidationPattern', /^[a-zA-Z0-9_:-]{1,50}$/);// DE210977
606 ng1appModule.value('TagValidationPattern', /^[\s\w_.-]{1,50}$/);
607 ng1appModule.value('VendorReleaseValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
608 ng1appModule.value('VendorNameValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,60}$/);
609 ng1appModule.value('VendorModelNumberValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,65}$/);
610 ng1appModule.value('ServiceTypeAndRoleValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,256}$/);
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         $templateCache.put('notification-custom-template.html', require('./view-models/shared/notification-custom-template.html'));
665         //handle cache data - version
666         let initAsdcVersion:Function = ():void => {
667
668             let onFailed = (response) => {
669                 console.info('onFailed initAsdcVersion', response);
670                 cacheService.set('version', 'N/A');
671             };
672
673             let onSuccess = (version:any) => {
674                 let tmpVerArray = version.version.split(".");
675                 let ver = tmpVerArray[0] + "." + tmpVerArray[1] + "." + tmpVerArray[2];
676                 cacheService.set('version', ver);
677             };
678
679             sdcVersionService.getVersion().then(onSuccess, onFailed);
680
681         };
682
683         let initEcompMenu:Function = (user):void => {
684             ecompHeaderService.getMenuItems(user.userId).then((data)=> {
685                 $rootScope['menuItems'] = data;
686             });
687         };
688
689         let initConfigurationUi:Function = ():void => {
690             ConfigurationUi
691                 .getConfigurationUi()
692                 .then((configurationUi:any) => {
693                     cacheService.set('UIConfiguration', configurationUi);
694                 });
695         };
696
697         let initCategories:Function = ():void => {
698             let onError = ():void => {
699                 console.log('Failed to init categories');
700             };
701
702             categoryResourceService.getAllCategories((categories: Categories):void => {
703                 cacheService.set('serviceCategories', categories.serviceCategories);
704                 cacheService.set('resourceCategories', categories.resourceCategories);
705             }, onError);
706         };
707
708         // Add hosted applications to sdcConfig
709         sdcConfig.hostedApplications = hostedApplications;
710
711         //handle http config
712         $http.defaults.withCredentials = true;
713         $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
714         $http.defaults.headers.common[cookieService.getUserIdSuffix()] = cookieService.getUserId();
715
716         initAsdcVersion();
717         initConfigurationUi();
718        // initLeftPalette();
719         DataTypesService.initDataTypes();
720
721         //handle stateChangeStart
722         let internalDeregisterStateChangeStartWatcher:Function = ():void => {
723             if (deregisterStateChangeStartWatcher) {
724                 deregisterStateChangeStartWatcher();
725                 deregisterStateChangeStartWatcher = null;
726             }
727         };
728
729         let removeLoader:Function = ():void => {
730             $(".sdc-loading-page .main-loader").addClass("animated fadeOut");
731             $(".sdc-loading-page .caption1").addClass("animated fadeOut");
732             $(".sdc-loading-page .caption2").addClass("animated fadeOut");
733             window.setTimeout(():void=> {
734                 $(".sdc-loading-page .main-loader").css("display", "none");
735                 $(".sdc-loading-page .caption1").css("display", "none");
736                 $(".sdc-loading-page .caption2").css("display", "none");
737                 $(".sdc-loading-page").addClass("animated fadeOut");
738             }, 1000);
739         };
740
741         let onNavigateOut:Function = (toState, toParams):void => {
742             let onOk = ():void => {
743                 $state.current.data.unsavedChanges = false;
744                 $state.go(toState.name, toParams);
745             };
746
747             let data = sdcMenu.alertMessages.exitWithoutSaving;
748             //open notify to user if changes are not saved
749             ModalsHandler.openAlertModal(data.title, data.message).then(onOk);
750         };
751
752         let onStateChangeStart:Function = (event, toState, toParams, fromState, fromParams):void => {
753             console.info((new Date()).getTime());
754             console.info('$stateChangeStart', toState.name);
755             //set body class
756             $rootScope['bodyClass'] = 'default-class';
757             if (toState.data && toState.data.bodyClass) {
758                 $rootScope['bodyClass'] = toState.data.bodyClass;
759             }
760
761             // Workaround in case we are entering other state then workspace (user move to catalog)
762             // remove the changeComponentCsarVersion, user should open again the VSP list and select one for update.
763             if (toState.name.indexOf('workspace') === -1) {
764                 if (cacheService.contains(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
765                     cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
766                 }
767             }
768
769             //saving last state to params , for breadcrumbs
770             if (['dashboard', 'catalog', 'onboardVendor'].indexOf(fromState.name) > -1) {
771                 toParams.previousState = fromState.name;
772             } else {
773                 toParams.previousState = fromParams.previousState;
774             }
775
776             if (toState.name !== 'error-403' && !userService.getLoggedinUser()) {
777                 internalDeregisterStateChangeStartWatcher();
778                 event.preventDefault();
779
780                 userService.authorize().subscribe((userInfo:IUserProperties) => {
781                     if (!doesUserHasAccess(toState, userInfo)) {
782                         $state.go('error-403');
783                         console.info('User has no permissions');
784                         registerStateChangeStartWatcher();
785                         return;
786                     }
787                     userService.setLoggedinUser(userInfo);
788                     cacheService.set('user', userInfo);
789                     initCategories();
790                     //   initEcompMenu(userInfo);
791                     setTimeout(function () {
792
793                         removeLoader();
794
795                         // initCategories();
796                         if (userService.getLoggedinUser().role === 'ADMIN') {
797                             // toState.name = "adminDashboard";
798                             $state.go("adminDashboard", toParams);
799                             registerStateChangeStartWatcher();
800                             return;
801                         }
802
803                         // After user authorized init categories
804                         window.setTimeout(():void=> {
805                             if ($state.current.name === '') {
806                                 $state.go(toState.name, toParams);
807                             }
808
809                             console.log("------$state.current.name=" + $state.current.name);
810                             console.info('-----registerStateChangeStartWatcher authorize $stateChangeStart');
811                             registerStateChangeStartWatcher();
812
813                         }, 1000);
814
815                     }, 0);
816
817                 }, () => {
818                     $state.go('error-403');
819
820                     console.info('registerStateChangeStartWatcher error-403 $stateChangeStart');
821                     registerStateChangeStartWatcher();
822                 });
823             }
824             else if (userService.getLoggedinUser()) {
825                 internalDeregisterStateChangeStartWatcher();
826                 if (!doesUserHasAccess(toState, userService.getLoggedinUser())) {
827                     event.preventDefault();
828                     $state.go('error-403');
829                     console.info('User has no permissions');
830                 }
831                 if (toState.name === "welcome") {
832                     $state.go("dashboard");
833                 }
834                 registerStateChangeStartWatcher();
835                 //if form is dirty and not save  - notify to user
836                 if (fromState.data && fromState.data.unsavedChanges && fromParams.id != toParams.id) {
837                     event.preventDefault();
838                     onNavigateOut(toState, toParams);
839                 }
840             }
841
842         };
843
844         let doesUserHasAccess:Function = (toState, user):boolean => {
845
846             let isUserHasAccess = true;
847             if (toState.permissions && toState.permissions.length > 0) {
848                 isUserHasAccess = _.includes(toState.permissions, user.role);
849             }
850             return isUserHasAccess;
851         };
852         let deregisterStateChangeStartWatcher:Function;
853
854         let registerStateChangeStartWatcher:Function = ():void => {
855             internalDeregisterStateChangeStartWatcher();
856             console.info('registerStateChangeStartWatcher $stateChangeStart');
857             deregisterStateChangeStartWatcher = $rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams):void => {
858                 onStateChangeStart(event, toState, toParams, fromState, fromParams);
859             });
860         };
861
862         registerStateChangeStartWatcher();
863     }]);
864