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