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>;
68 isHiddenCategorySelected: boolean;
72 onImportFileChange():void;
73 validateField(field:any):boolean;
74 validateName(isInit:boolean):void;
75 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
76 onVendorNameChange(oldVendorName:string):void;
77 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
78 onCategoryChange():void;
79 onEcompGeneratedNamingChange():void;
80 openOnBoardingModal():void;
81 initCategoreis():void;
82 initEnvironmentContext():void;
83 initInstantiationTypes():void;
84 onInstantiationTypeChange():void;
86 possibleToUpdateIcon():boolean;
89 export class GeneralViewModel {
93 'Sdc.Services.CacheService',
94 'ComponentNameValidationPattern',
95 'ContactIdValidationPattern',
96 'TagValidationPattern',
97 'VendorReleaseValidationPattern',
98 'VendorNameValidationPattern',
99 'VendorModelNumberValidationPattern',
100 'CommentValidationPattern',
103 'ProjectCodeValidationPattern',
106 'EventListenerService',
108 'Sdc.Services.ProgressService',
112 'Sdc.Services.OnboardingService',
116 constructor(private $scope:IGeneralScope,
117 private cacheService:CacheService,
118 private ComponentNameValidationPattern:RegExp,
119 private ContactIdValidationPattern:RegExp,
120 private TagValidationPattern:RegExp,
121 private VendorReleaseValidationPattern:RegExp,
122 private VendorNameValidationPattern:RegExp,
123 private VendorModelNumberValidationPattern:RegExp,
124 private CommentValidationPattern:RegExp,
125 private ValidationUtils:ValidationUtils,
126 private sdcConfig:IAppConfigurtaion,
127 private ProjectCodeValidationPattern:RegExp,
128 private $state:ng.ui.IStateService,
129 private ModalsHandler:ModalsHandler,
130 private EventListenerService:EventListenerService,
131 private Notification:any,
132 private progressService:ProgressService,
133 protected $interval:any,
134 private $filter:ng.IFilterService,
135 private $timeout:ng.ITimeoutService,
136 private onBoardingService:OnboardingService,
137 private ComponentFactory:ComponentFactory) {
139 this.initScopeValidation();
140 this.initScopeMethods();
147 private initScopeValidation = ():void => {
148 this.$scope.validation = new Validation();
149 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
150 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
151 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
152 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
153 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
154 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
155 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
156 this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
159 private loadOnboardingFileCache = ():ng.IPromise<Dictionary<any>> =>{
161 let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
162 let onSuccess = (vsps:Array<ICsarComponent>) =>{
163 onboardCsarFilesMap = {};
164 _.each(vsps, (vsp:ICsarComponent)=>{
165 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
166 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
168 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
169 return onboardCsarFilesMap;
171 let onError = (): void =>{
172 console.log("Error getting onboarding list");
174 return this.onBoardingService.getOnboardingVSPs().then(onSuccess, onError);
177 private setImportedFileText = ():void => {
179 if(!this.$scope.isShowOnboardingSelectionBrowse) return;
181 //these variables makes it easier to read this logic
182 let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
183 let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
185 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
186 let assignFileName = ():void => {
187 if(this.$scope.component.vspArchived){
188 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
190 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
195 if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
198 this.loadOnboardingFileCache().then((onboardingFiles) => {
199 onboardCsarFilesMap = onboardingFiles;
200 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
207 isCreateModeAvailable(verifyObj:string): boolean {
208 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
209 return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
212 private initScope = ():void => {
215 this.$scope.importCsarProgressKey = "importCsarProgressKey";
217 this.$scope.browseFileLabel = this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType === ResourceType.VF ? "Upload file" : "Upload VFC";
218 this.$scope.progressService = this.progressService;
219 this.$scope.componentCategories = new componentCategories();
220 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
223 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
226 this.$scope.initCategoreis();
228 // Init Environment Context
229 this.$scope.initEnvironmentContext();
231 // Init the decision if to show file browse.
232 this.$scope.isShowFileBrowse = false;
233 if (this.$scope.component.isResource()) {
234 let resource:Resource = <Resource>this.$scope.component;
235 console.log(resource.name + ": " + resource.csarUUID);
236 if (resource.importedFile) { // Component has imported file.
237 this.$scope.isShowFileBrowse = true;
239 if (this.$scope.isEditMode() && resource.resourceType == ResourceType.VF && !resource.csarUUID) {
240 this.$scope.isShowFileBrowse = true;
242 } else if(this.$scope.component.isService()){
243 // Init Instantiation types
244 this.$scope.initInstantiationTypes();
247 // Work around to change the csar version
248 if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
249 //(<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
250 this.cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
251 this.$scope.updateUnsavedFileFlag(true);
253 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
254 this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
255 this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
260 // Init the decision if to show onboarding
261 if (this.$scope.component.isResource() && this.$scope.isEditMode() &&
262 ((<Resource>this.$scope.component).resourceType == ResourceType.VF ||
263 (<Resource>this.$scope.component).resourceType == ResourceType.PNF)
264 && (<Resource>this.$scope.component).csarUUID) {
265 this.$scope.isShowOnboardingSelectionBrowse = true;
266 this.setImportedFileText();
268 this.$scope.isShowOnboardingSelectionBrowse = false;
272 //init file extensions based on the file that was imported.
273 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
274 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
275 let fileExtension:string = fileName.split(".").pop();
276 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
277 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
278 (<Resource>this.$scope.component).importedFile.filetype = "csar";
279 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
280 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
281 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
283 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
284 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
285 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
286 //(<Resource>this.$scope.component).importedFile.filetype="csar";
291 this.$scope.setValidState(true);
293 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
294 let uniqueId:string = mainCategory;
296 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
301 //TODO remove this after handling contact in UI
302 if (this.$scope.isCreateMode()) {
303 this.$scope.component.contactId = this.cacheService.get("user").userId;
304 this.$scope.originComponent.contactId = this.$scope.component.contactId;
308 this.$scope.$on('$destroy', () => {
309 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
310 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
315 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
316 private convertCategoryStringToOneArray = ():Array<IMainCategory> => {
317 let tmp = this.$scope.component.selectedCategory.split("_#_");
318 let mainCategory = tmp[0];
319 let subCategory = tmp[1];
321 // Find the selected category and add the relevant sub category.
322 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
323 return item["name"] === mainCategory;
327 let mainCategoryClone = angular.copy(selectedMainCategory);
329 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
330 return item["name"] === subCategory;
332 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
334 let tmpSelected = <IMainCategory> mainCategoryClone;
336 let result:Array<IMainCategory> = [];
337 result.push(tmpSelected);
342 private updateComponentNameInBreadcrumbs = ():void => {
343 //update breadcrum after changing name
344 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
345 this.$scope.updateMenuComponentName(this.$scope.component.name);
348 //Find if a category is applicable for External API or not
349 private isHiddenCategory = (category: string) => {
350 let items: Array<any> = new Array<any>();
351 items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
352 for(let index = 0; index < items.length; ++index) {
353 if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
360 private filteredCategories = () => {
361 let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
362 this.$scope.categories.forEach((category) => {
363 if (!this.isHiddenCategory(category.name)
364 && this.$scope.isCreateMode()
366 tempCategories.push(category);
367 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
368 && !this.isHiddenCategory(this.$scope.component.selectedCategory)
369 && !this.isHiddenCategory(category.name)
371 tempCategories.push(category);
372 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
373 && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
374 tempCategories.push(category);
378 return tempCategories;
381 private initScopeMethods = ():void => {
383 this.$scope.initCategoreis = ():void => {
384 if (this.$scope.componentType === ComponentType.RESOURCE) {
385 this.$scope.categories = this.cacheService.get('resourceCategories');
388 if (this.$scope.componentType === ComponentType.SERVICE) {
389 this.$scope.categories = this.cacheService.get('serviceCategories');
391 //Remove categories from dropdown applicable for External API
392 if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
393 this.$scope.categories = this.filteredCategories();
394 //Flag to disbale category if service is created through External API
395 this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
401 this.$scope.initInstantiationTypes = ():void => {
402 if (this.$scope.componentType === ComponentType.SERVICE) {
403 this.$scope.instantiationTypes = new Array();
404 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
405 this.$scope.instantiationTypes.push(instantiationType.MACRO);
406 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
407 if (instantiationTypeField === ""){
408 this.$scope.instantiationTypes.push("");
410 else if (this.isCreateModeAvailable(instantiationTypeField)) {
411 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
417 this.$scope.initEnvironmentContext = ():void => {
418 if (this.$scope.componentType === ComponentType.SERVICE) {
419 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
420 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
421 // In creation new service OR check outing old service without environmentContext parameter - set default value
422 if(this.isCreateModeAvailable(environmentContext)){
423 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
428 this.$scope.validateField = (field:any):boolean => {
429 if (field && field.$dirty && field.$invalid) {
435 this.$scope.openOnBoardingModal = ():void => {
436 if(this.$scope.component.vspArchived) return;
437 let csarUUID = (<Resource>this.$scope.component).csarUUID;
438 let csarVersion = (<Resource>this.$scope.component).csarVersion;
439 this.ModalsHandler.openOnboadrdingModal('Update', csarUUID, csarVersion).then((result)=> {
442 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
443 (component:Component)=> {
444 if (result.componentCsar && component.isResource()){
445 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
446 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
449 this.$scope.setComponent(component);
450 this.$scope.updateUnsavedFileFlag(true);
451 this.setImportedFileText();
459 this.$scope.updateIcon = ():void => {
460 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
461 if(isDirty && !this.$scope.isCreateMode()){
462 this.setUnsavedChanges(true);
469 this.$scope.possibleToUpdateIcon = ():boolean => {
470 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
477 this.$scope.validateName = (isInit:boolean):void => {
478 if (isInit === undefined) {
482 let name = this.$scope.component.name;
483 if (!name || name === "") {
484 if (this.$scope.editForm
485 && this.$scope.editForm["componentName"]
486 && this.$scope.editForm["componentName"].$error) {
488 // Clear the error name already exists
489 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
494 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
496 let onFailed = (response) => {
497 //console.info('onFaild', response);
498 //this.$scope.isLoading = false;
501 let onSuccess = (validation:IValidate) => {
502 this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
503 if (validation.isValid) {
504 //update breadcrumb after changing name
505 this.updateComponentNameInBreadcrumbs();
510 // When page is init after update
511 if (this.$scope.component.name !== this.$scope.originComponent.name) {
512 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
514 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
518 // Validating on change (has debounce)
519 if (this.$scope.editForm
520 && this.$scope.editForm["componentName"]
521 && this.$scope.editForm["componentName"].$error
522 && !this.$scope.editForm["componentName"].$error.pattern
523 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
525 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
527 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
529 } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
531 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
537 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
538 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm){
539 this.$scope.save().then(() => {
540 this.$scope.handleChangeLifecycleState(nextState);
542 console.error("Save failed, unable to change lifecycle state to " + nextState);
544 } else if(!this.$scope.isValidForm){
545 console.error("Form is not valid");
547 let newCsarVersion:string;
548 if(this.$scope.unsavedFile){
549 newCsarVersion = (<Resource>this.$scope.component).csarVersion;
551 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
556 this.$scope.revert = ():void => {
557 //in state of import file leave the file in place
559 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
561 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
562 (<Resource>this.$scope.component).importedFile = angular.copy(this.$scope.restoreFile);
565 this.setImportedFileText();
566 this.$scope.updateBreadcrumbs(this.$scope.component); //update on workspace
568 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
569 this.setUnsavedChanges(false);
570 this.$scope.updateUnsavedFileFlag(false);
571 this.$scope.editForm.$setPristine();
574 this.$scope.onImportFileChange = () => {
576 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
577 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ //or file was swapped for a new one
578 this.$scope.updateUnsavedFileFlag(true);
580 this.$scope.updateUnsavedFileFlag(false);
581 this.$scope.editForm.fileElement.$setPristine();
585 this.$scope.$watchCollection('component.name', (newData:any):void => {
586 this.$scope.validateName(false);
589 // Notify the parent if this step valid or not.
590 this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
591 this.$scope.setValidState(newVal);
594 this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
595 if (newVal && !this.$scope.isCreateMode()) {
596 this.setUnsavedChanges(true);
601 this.$scope.onCategoryChange = ():void => {
602 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
603 this.$scope.component.categories = this.convertCategoryStringToOneArray();
604 this.$scope.component.icon = DEFAULT_ICON;
607 this.$scope.onEcompGeneratedNamingChange = ():void =>{
608 if(!(<Service>this.$scope.component).ecompGeneratedNaming){
609 (<Service>this.$scope.component).namingPolicy = '';
613 this.$scope.onVendorNameChange = (oldVendorName:string):void => {
614 if (this.$scope.component.icon === oldVendorName) {
615 this.$scope.component.icon = DEFAULT_ICON;
618 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
622 private setUnsavedChanges = (hasChanges:boolean):void => {
623 this.$state.current.data.unsavedChanges = hasChanges;