2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 import * as _ from "lodash";
23 import {ModalsHandler, ValidationUtils, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, DEFAULT_ICON,
24 ResourceType, ComponentState, instantiationType, ComponentFactory} from "app/utils";
25 import {CacheService, EventListenerService, ProgressService, OnboardingService} from "app/services";
26 import {IAppConfigurtaion, IValidate, IMainCategory, Resource, ISubCategory,Service, ICsarComponent, Component} from "app/models";
27 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
28 import {Dictionary} from "lodash";
29 import { PREVIOUS_CSAR_COMPONENT } from "../../../../utils/constants";
32 export class Validation {
33 componentNameValidationPattern:RegExp;
34 contactIdValidationPattern:RegExp;
35 tagValidationPattern:RegExp;
36 VendorReleaseValidationPattern:RegExp;
37 VendorNameValidationPattern:RegExp;
38 VendorModelNumberValidationPattern:RegExp;
39 commentValidationPattern:RegExp;
40 projectCodeValidationPattern:RegExp;
43 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
44 selectedCategory:string;
47 export interface IEnvironmentContext {
49 validValues:Array<string>;
52 export interface IGeneralScope extends IWorkspaceViewModelScope {
53 validation:Validation;
54 editForm:ng.IFormController;
55 categories:Array<IMainCategory>;
56 environmentContextObj:IEnvironmentContext;
57 latestCategoryId:string;
58 latestVendorName:string;
59 importedFileExtension:any;
61 isShowFileBrowse:boolean;
62 isShowOnboardingSelectionBrowse:boolean;
63 importedToscaBrowseFileText:string;
64 importCsarProgressKey:string;
65 browseFileLabel:string;
66 componentCategories:componentCategories;
67 instantiationTypes:Array<instantiationType>;
71 onImportFileChange():void;
72 validateField(field:any):boolean;
73 validateName(isInit:boolean):void;
74 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
75 onVendorNameChange(oldVendorName:string):void;
76 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
77 onCategoryChange():void;
78 onEcompGeneratedNamingChange():void;
79 openOnBoardingModal():void;
80 initCategoreis():void;
81 initEnvironmentContext():void;
82 initInstantiationTypes():void;
83 onInstantiationTypeChange():void;
85 possibleToUpdateIcon():boolean;
88 export class GeneralViewModel {
92 'Sdc.Services.CacheService',
93 'ComponentNameValidationPattern',
94 'ContactIdValidationPattern',
95 'TagValidationPattern',
96 'VendorReleaseValidationPattern',
97 'VendorNameValidationPattern',
98 'VendorModelNumberValidationPattern',
99 'CommentValidationPattern',
102 'ProjectCodeValidationPattern',
105 'EventListenerService',
107 'Sdc.Services.ProgressService',
111 'Sdc.Services.OnboardingService',
115 constructor(private $scope:IGeneralScope,
116 private cacheService:CacheService,
117 private ComponentNameValidationPattern:RegExp,
118 private ContactIdValidationPattern:RegExp,
119 private TagValidationPattern:RegExp,
120 private VendorReleaseValidationPattern:RegExp,
121 private VendorNameValidationPattern:RegExp,
122 private VendorModelNumberValidationPattern:RegExp,
123 private CommentValidationPattern:RegExp,
124 private ValidationUtils:ValidationUtils,
125 private sdcConfig:IAppConfigurtaion,
126 private ProjectCodeValidationPattern:RegExp,
127 private $state:ng.ui.IStateService,
128 private ModalsHandler:ModalsHandler,
129 private EventListenerService:EventListenerService,
130 private Notification:any,
131 private progressService:ProgressService,
132 protected $interval:any,
133 private $filter:ng.IFilterService,
134 private $timeout:ng.ITimeoutService,
135 private onBoardingService:OnboardingService,
136 private ComponentFactory:ComponentFactory) {
138 this.initScopeValidation();
139 this.initScopeMethods();
146 private initScopeValidation = ():void => {
147 this.$scope.validation = new Validation();
148 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
149 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
150 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
151 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
152 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
153 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
154 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
155 this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
158 private loadOnboardingFileCache = ():ng.IPromise<Dictionary<any>> =>{
160 let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
161 let onSuccess = (vsps:Array<ICsarComponent>) =>{
162 onboardCsarFilesMap = {};
163 _.each(vsps, (vsp:ICsarComponent)=>{
164 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
165 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
167 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
168 return onboardCsarFilesMap;
170 let onError = (): void =>{
171 console.log("Error getting onboarding list");
173 return this.onBoardingService.getOnboardingVSPs().then(onSuccess, onError);
176 private setImportedFileText = ():void => {
178 if(!this.$scope.isShowOnboardingSelectionBrowse) return;
180 //these variables makes it easier to read this logic
181 let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
182 let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
184 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
185 let assignFileName = ():void => {
186 if(this.$scope.component.vspArchived){
187 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
189 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
194 if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
197 this.loadOnboardingFileCache().then((onboardingFiles) => {
198 onboardCsarFilesMap = onboardingFiles;
199 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
206 isCreateModeAvailable(verifyObj:string): boolean {
207 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
208 return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
211 private initScope = ():void => {
214 this.$scope.importCsarProgressKey = "importCsarProgressKey";
216 this.$scope.browseFileLabel = this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType === ResourceType.VF ? "Upload file" : "Upload VFC";
217 this.$scope.progressService = this.progressService;
218 this.$scope.componentCategories = new componentCategories();
219 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
222 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
225 this.$scope.initCategoreis();
227 // Init Environment Context
228 this.$scope.initEnvironmentContext();
230 // Init the decision if to show file browse.
231 this.$scope.isShowFileBrowse = false;
232 if (this.$scope.component.isResource()) {
233 let resource:Resource = <Resource>this.$scope.component;
234 console.log(resource.name + ": " + resource.csarUUID);
235 if (resource.importedFile) { // Component has imported file.
236 this.$scope.isShowFileBrowse = true;
238 if (this.$scope.isEditMode() && resource.resourceType == ResourceType.VF && !resource.csarUUID) {
239 this.$scope.isShowFileBrowse = true;
241 } else if(this.$scope.component.isService()){
242 // Init Instantiation types
243 this.$scope.initInstantiationTypes();
246 // Work around to change the csar version
247 if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
248 //(<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
249 this.cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
250 this.$scope.updateUnsavedFileFlag(true);
252 if (!this.$scope.isViewMode() && this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
253 this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
254 this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
259 // Init the decision if to show onboarding
260 if (this.$scope.component.isResource() && this.$scope.isEditMode() &&
261 (<Resource>this.$scope.component).resourceType == ResourceType.VF && (<Resource>this.$scope.component).csarUUID) {
262 this.$scope.isShowOnboardingSelectionBrowse = true;
263 this.setImportedFileText();
265 this.$scope.isShowOnboardingSelectionBrowse = false;
269 //init file extensions based on the file that was imported.
270 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
271 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
272 let fileExtension:string = fileName.split(".").pop();
273 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
274 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
275 (<Resource>this.$scope.component).importedFile.filetype = "csar";
276 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
277 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
278 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
280 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
281 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
282 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
283 //(<Resource>this.$scope.component).importedFile.filetype="csar";
288 this.$scope.setValidState(true);
290 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
291 let uniqueId:string = mainCategory;
293 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
298 //TODO remove this after handling contact in UI
299 if (this.$scope.isCreateMode()) {
300 this.$scope.component.contactId = this.cacheService.get("user").userId;
301 this.$scope.originComponent.contactId = this.$scope.component.contactId;
305 this.$scope.$on('$destroy', () => {
306 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
307 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
312 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
313 private convertCategoryStringToOneArray = ():Array<IMainCategory> => {
314 let tmp = this.$scope.component.selectedCategory.split("_#_");
315 let mainCategory = tmp[0];
316 let subCategory = tmp[1];
318 // Find the selected category and add the relevant sub category.
319 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
320 return item["name"] === mainCategory;
324 let mainCategoryClone = angular.copy(selectedMainCategory);
326 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
327 return item["name"] === subCategory;
329 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
331 let tmpSelected = <IMainCategory> mainCategoryClone;
333 let result:Array<IMainCategory> = [];
334 result.push(tmpSelected);
339 private updateComponentNameInBreadcrumbs = ():void => {
340 //update breadcrum after changing name
341 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
342 this.$scope.updateMenuComponentName(this.$scope.component.name);
345 private initScopeMethods = ():void => {
347 this.$scope.initCategoreis = ():void => {
348 if (this.$scope.componentType === ComponentType.RESOURCE) {
349 this.$scope.categories = this.cacheService.get('resourceCategories');
352 if (this.$scope.componentType === ComponentType.SERVICE) {
353 this.$scope.categories = this.cacheService.get('serviceCategories');
357 this.$scope.initInstantiationTypes = ():void => {
358 if (this.$scope.componentType === ComponentType.SERVICE) {
359 this.$scope.instantiationTypes = new Array();
360 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
361 this.$scope.instantiationTypes.push(instantiationType.MACRO);
362 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
363 if (instantiationTypeField === ""){
364 this.$scope.instantiationTypes.push("");
366 else if (this.isCreateModeAvailable(instantiationTypeField)) {
367 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
373 this.$scope.initEnvironmentContext = ():void => {
374 if (this.$scope.componentType === ComponentType.SERVICE) {
375 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
376 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
377 // In creation new service OR check outing old service without environmentContext parameter - set default value
378 if(this.isCreateModeAvailable(environmentContext)){
379 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
384 this.$scope.validateField = (field:any):boolean => {
385 if (field && field.$dirty && field.$invalid) {
391 this.$scope.openOnBoardingModal = ():void => {
392 if(this.$scope.component.vspArchived) return;
393 let csarUUID = (<Resource>this.$scope.component).csarUUID;
394 let csarVersion = (<Resource>this.$scope.component).csarVersion;
395 this.ModalsHandler.openOnboadrdingModal('Update', csarUUID, csarVersion).then((result)=> {
398 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
399 (component:Component)=> {
400 if (result.componentCsar && component.isResource()){
401 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
402 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
405 this.$scope.setComponent(component);
406 this.$scope.updateUnsavedFileFlag(true);
407 this.setImportedFileText();
415 this.$scope.updateIcon = ():void => {
416 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
417 if(isDirty && !this.$scope.isCreateMode()){
418 this.setUnsavedChanges(true);
425 this.$scope.possibleToUpdateIcon = ():boolean => {
426 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
433 this.$scope.validateName = (isInit:boolean):void => {
434 if (isInit === undefined) {
438 let name = this.$scope.component.name;
439 if (!name || name === "") {
440 if (this.$scope.editForm
441 && this.$scope.editForm["componentName"]
442 && this.$scope.editForm["componentName"].$error) {
444 // Clear the error name already exists
445 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
450 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
452 let onFailed = (response) => {
453 //console.info('onFaild', response);
454 //this.$scope.isLoading = false;
457 let onSuccess = (validation:IValidate) => {
458 this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
459 if (validation.isValid) {
460 //update breadcrumb after changing name
461 this.updateComponentNameInBreadcrumbs();
466 // When page is init after update
467 if (this.$scope.component.name !== this.$scope.originComponent.name) {
468 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
470 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
474 // Validating on change (has debounce)
475 if (this.$scope.editForm
476 && this.$scope.editForm["componentName"]
477 && this.$scope.editForm["componentName"].$error
478 && !this.$scope.editForm["componentName"].$error.pattern
479 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
481 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
483 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
485 } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
487 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
493 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
494 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm){
495 this.$scope.save().then(() => {
496 this.$scope.handleChangeLifecycleState(nextState);
498 console.error("Save failed, unable to change lifecycle state to " + nextState);
500 } else if(!this.$scope.isValidForm){
501 console.error("Form is not valid");
503 let newCsarVersion:string;
504 if(this.$scope.unsavedFile){
505 newCsarVersion = (<Resource>this.$scope.component).csarVersion;
507 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
512 this.$scope.revert = ():void => {
513 //in state of import file leave the file in place
515 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
517 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
518 (<Resource>this.$scope.component).importedFile = angular.copy(this.$scope.restoreFile);
521 this.setImportedFileText();
522 this.$scope.updateBreadcrumbs(this.$scope.component); //update on workspace
524 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
525 this.setUnsavedChanges(false);
526 this.$scope.updateUnsavedFileFlag(false);
527 this.$scope.editForm.$setPristine();
530 this.$scope.onImportFileChange = () => {
532 if( !this.$scope.restoreFile && this.$scope.editForm.fileElement.value && this.$scope.editForm.fileElement.value.filename || //if file started empty but we have added a new one
533 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ //or file was swapped for a new one
534 this.$scope.updateUnsavedFileFlag(true);
536 this.$scope.updateUnsavedFileFlag(false);
537 this.$scope.editForm.fileElement.$setPristine();
541 this.$scope.$watchCollection('component.name', (newData:any):void => {
542 this.$scope.validateName(false);
545 // Notify the parent if this step valid or not.
546 this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
547 this.$scope.setValidState(newVal);
550 this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
551 if (newVal && !this.$scope.isCreateMode()) {
552 this.setUnsavedChanges(true);
557 this.$scope.onCategoryChange = ():void => {
558 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
559 this.$scope.component.categories = this.convertCategoryStringToOneArray();
560 this.$scope.component.icon = DEFAULT_ICON;
563 this.$scope.onEcompGeneratedNamingChange = ():void =>{
564 if(!(<Service>this.$scope.component).ecompGeneratedNaming){
565 (<Service>this.$scope.component).namingPolicy = '';
569 this.$scope.onVendorNameChange = (oldVendorName:string):void => {
570 if (this.$scope.component.icon === oldVendorName) {
571 this.$scope.component.icon = DEFAULT_ICON;
574 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
578 private setUnsavedChanges = (hasChanges:boolean):void => {
579 this.$state.current.data.unsavedChanges = hasChanges;