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 ||
262 (<Resource>this.$scope.component).resourceType == ResourceType.PNF)
263 && (<Resource>this.$scope.component).csarUUID) {
264 this.$scope.isShowOnboardingSelectionBrowse = true;
265 this.setImportedFileText();
267 this.$scope.isShowOnboardingSelectionBrowse = false;
271 //init file extensions based on the file that was imported.
272 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
273 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
274 let fileExtension:string = fileName.split(".").pop();
275 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
276 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
277 (<Resource>this.$scope.component).importedFile.filetype = "csar";
278 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
279 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
280 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
282 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
283 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
284 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
285 //(<Resource>this.$scope.component).importedFile.filetype="csar";
290 this.$scope.setValidState(true);
292 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
293 let uniqueId:string = mainCategory;
295 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
300 //TODO remove this after handling contact in UI
301 if (this.$scope.isCreateMode()) {
302 this.$scope.component.contactId = this.cacheService.get("user").userId;
303 this.$scope.originComponent.contactId = this.$scope.component.contactId;
307 this.$scope.$on('$destroy', () => {
308 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
309 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
314 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
315 private convertCategoryStringToOneArray = ():Array<IMainCategory> => {
316 let tmp = this.$scope.component.selectedCategory.split("_#_");
317 let mainCategory = tmp[0];
318 let subCategory = tmp[1];
320 // Find the selected category and add the relevant sub category.
321 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
322 return item["name"] === mainCategory;
326 let mainCategoryClone = angular.copy(selectedMainCategory);
328 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
329 return item["name"] === subCategory;
331 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
333 let tmpSelected = <IMainCategory> mainCategoryClone;
335 let result:Array<IMainCategory> = [];
336 result.push(tmpSelected);
341 private updateComponentNameInBreadcrumbs = ():void => {
342 //update breadcrum after changing name
343 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
344 this.$scope.updateMenuComponentName(this.$scope.component.name);
347 private initScopeMethods = ():void => {
349 this.$scope.initCategoreis = ():void => {
350 if (this.$scope.componentType === ComponentType.RESOURCE) {
351 this.$scope.categories = this.cacheService.get('resourceCategories');
354 if (this.$scope.componentType === ComponentType.SERVICE) {
355 this.$scope.categories = this.cacheService.get('serviceCategories');
359 this.$scope.initInstantiationTypes = ():void => {
360 if (this.$scope.componentType === ComponentType.SERVICE) {
361 this.$scope.instantiationTypes = new Array();
362 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
363 this.$scope.instantiationTypes.push(instantiationType.MACRO);
364 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
365 if (instantiationTypeField === ""){
366 this.$scope.instantiationTypes.push("");
368 else if (this.isCreateModeAvailable(instantiationTypeField)) {
369 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
375 this.$scope.initEnvironmentContext = ():void => {
376 if (this.$scope.componentType === ComponentType.SERVICE) {
377 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
378 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
379 // In creation new service OR check outing old service without environmentContext parameter - set default value
380 if(this.isCreateModeAvailable(environmentContext)){
381 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
386 this.$scope.validateField = (field:any):boolean => {
387 if (field && field.$dirty && field.$invalid) {
393 this.$scope.openOnBoardingModal = ():void => {
394 if(this.$scope.component.vspArchived) return;
395 let csarUUID = (<Resource>this.$scope.component).csarUUID;
396 let csarVersion = (<Resource>this.$scope.component).csarVersion;
397 this.ModalsHandler.openOnboadrdingModal('Update', csarUUID, csarVersion).then((result)=> {
400 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
401 (component:Component)=> {
402 if (result.componentCsar && component.isResource()){
403 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
404 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
407 this.$scope.setComponent(component);
408 this.$scope.updateUnsavedFileFlag(true);
409 this.setImportedFileText();
417 this.$scope.updateIcon = ():void => {
418 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
419 if(isDirty && !this.$scope.isCreateMode()){
420 this.setUnsavedChanges(true);
427 this.$scope.possibleToUpdateIcon = ():boolean => {
428 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
435 this.$scope.validateName = (isInit:boolean):void => {
436 if (isInit === undefined) {
440 let name = this.$scope.component.name;
441 if (!name || name === "") {
442 if (this.$scope.editForm
443 && this.$scope.editForm["componentName"]
444 && this.$scope.editForm["componentName"].$error) {
446 // Clear the error name already exists
447 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
452 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
454 let onFailed = (response) => {
455 //console.info('onFaild', response);
456 //this.$scope.isLoading = false;
459 let onSuccess = (validation:IValidate) => {
460 this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
461 if (validation.isValid) {
462 //update breadcrumb after changing name
463 this.updateComponentNameInBreadcrumbs();
468 // When page is init after update
469 if (this.$scope.component.name !== this.$scope.originComponent.name) {
470 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
472 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
476 // Validating on change (has debounce)
477 if (this.$scope.editForm
478 && this.$scope.editForm["componentName"]
479 && this.$scope.editForm["componentName"].$error
480 && !this.$scope.editForm["componentName"].$error.pattern
481 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
483 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
485 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
487 } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
489 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
495 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
496 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm){
497 this.$scope.save().then(() => {
498 this.$scope.handleChangeLifecycleState(nextState);
500 console.error("Save failed, unable to change lifecycle state to " + nextState);
502 } else if(!this.$scope.isValidForm){
503 console.error("Form is not valid");
505 let newCsarVersion:string;
506 if(this.$scope.unsavedFile){
507 newCsarVersion = (<Resource>this.$scope.component).csarVersion;
509 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
514 this.$scope.revert = ():void => {
515 //in state of import file leave the file in place
517 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
519 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
520 (<Resource>this.$scope.component).importedFile = angular.copy(this.$scope.restoreFile);
523 this.setImportedFileText();
524 this.$scope.updateBreadcrumbs(this.$scope.component); //update on workspace
526 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
527 this.setUnsavedChanges(false);
528 this.$scope.updateUnsavedFileFlag(false);
529 this.$scope.editForm.$setPristine();
532 this.$scope.onImportFileChange = () => {
534 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
535 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ //or file was swapped for a new one
536 this.$scope.updateUnsavedFileFlag(true);
538 this.$scope.updateUnsavedFileFlag(false);
539 this.$scope.editForm.fileElement.$setPristine();
543 this.$scope.$watchCollection('component.name', (newData:any):void => {
544 this.$scope.validateName(false);
547 // Notify the parent if this step valid or not.
548 this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
549 this.$scope.setValidState(newVal);
552 this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
553 if (newVal && !this.$scope.isCreateMode()) {
554 this.setUnsavedChanges(true);
559 this.$scope.onCategoryChange = ():void => {
560 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
561 this.$scope.component.categories = this.convertCategoryStringToOneArray();
562 this.$scope.component.icon = DEFAULT_ICON;
565 this.$scope.onEcompGeneratedNamingChange = ():void =>{
566 if(!(<Service>this.$scope.component).ecompGeneratedNaming){
567 (<Service>this.$scope.component).namingPolicy = '';
571 this.$scope.onVendorNameChange = (oldVendorName:string):void => {
572 if (this.$scope.component.icon === oldVendorName) {
573 this.$scope.component.icon = DEFAULT_ICON;
576 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
580 private setUnsavedChanges = (hasChanges:boolean):void => {
581 this.$state.current.data.unsavedChanges = hasChanges;