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} from "app/utils";
25 import {CacheService, EventListenerService, ProgressService, OnboardingService} from "app/services";
26 import {IAppConfigurtaion, IValidate, IMainCategory, Resource, ISubCategory,Service, ICsarComponent} from "app/models";
27 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
28 import {Dictionary} from "lodash";
30 export class Validation {
31 componentNameValidationPattern:RegExp;
32 contactIdValidationPattern:RegExp;
33 tagValidationPattern:RegExp;
34 VendorReleaseValidationPattern:RegExp;
35 VendorNameValidationPattern:RegExp;
36 VendorModelNumberValidationPattern:RegExp;
37 commentValidationPattern:RegExp;
38 projectCodeValidationPattern:RegExp;
41 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
42 selectedCategory:string;
45 export interface IEnvironmentContext {
47 validValues:Array<string>;
50 export interface IGeneralScope extends IWorkspaceViewModelScope {
51 validation:Validation;
52 editForm:ng.IFormController;
53 categories:Array<IMainCategory>;
54 environmentContextObj:IEnvironmentContext;
55 latestCategoryId:string;
56 latestVendorName:string;
57 importedFileExtension:any;
59 isShowFileBrowse:boolean;
60 isShowOnboardingSelectionBrowse:boolean;
61 importedToscaBrowseFileText:string;
62 importCsarProgressKey:string;
63 browseFileLabel:string;
64 componentCategories:componentCategories;
66 onToscaFileChange():void;
67 validateField(field:any):boolean;
68 validateName(isInit:boolean):void;
69 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
70 onVendorNameChange(oldVendorName:string):void;
71 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
72 onCategoryChange():void;
73 onEcompGeneratedNamingChange():void;
74 openOnBoardingModal():void;
75 initCategoreis():void;
76 initEnvironmentContext():void;
78 possibleToUpdateIcon():boolean;
81 export class GeneralViewModel {
85 'Sdc.Services.CacheService',
86 'ComponentNameValidationPattern',
87 'ContactIdValidationPattern',
88 'TagValidationPattern',
89 'VendorReleaseValidationPattern',
90 'VendorNameValidationPattern',
91 'VendorModelNumberValidationPattern',
92 'CommentValidationPattern',
95 'ProjectCodeValidationPattern',
98 'EventListenerService',
100 'Sdc.Services.ProgressService',
104 'Sdc.Services.OnboardingService'
107 constructor(private $scope:IGeneralScope,
108 private cacheService:CacheService,
109 private ComponentNameValidationPattern:RegExp,
110 private ContactIdValidationPattern:RegExp,
111 private TagValidationPattern:RegExp,
112 private VendorReleaseValidationPattern:RegExp,
113 private VendorNameValidationPattern:RegExp,
114 private VendorModelNumberValidationPattern:RegExp,
115 private CommentValidationPattern:RegExp,
116 private ValidationUtils:ValidationUtils,
117 private sdcConfig:IAppConfigurtaion,
118 private ProjectCodeValidationPattern:RegExp,
119 private $state:ng.ui.IStateService,
120 private ModalsHandler:ModalsHandler,
121 private EventListenerService:EventListenerService,
122 private Notification:any,
123 private progressService:ProgressService,
124 protected $interval:any,
125 private $filter:ng.IFilterService,
126 private $timeout:ng.ITimeoutService,
127 private onBoardingService:OnboardingService) {
129 this.initScopeValidation();
130 this.initScopeMethods();
137 private initScopeValidation = ():void => {
138 this.$scope.validation = new Validation();
139 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
140 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
141 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
142 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
143 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
144 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
145 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
146 this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
149 private initImportedToscaBrowseFile = ():void =>{
150 // Init the decision if to show onboarding
151 this.$scope.isShowOnboardingSelectionBrowse = false;
152 if (this.$scope.component.isResource() &&
153 this.$scope.isEditMode() &&
154 (<Resource>this.$scope.component).resourceType == ResourceType.VF &&
155 (<Resource>this.$scope.component).csarUUID) {
156 this.$scope.isShowOnboardingSelectionBrowse = true;
157 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
158 // The onboardCsarFilesMap in cache contains map of [packageId]:[vsp display name for brows]
159 // if the map is empty - Do request to BE
160 if(onboardCsarFilesMap) {
161 if (onboardCsarFilesMap[(<Resource>this.$scope.component).csarUUID]){
162 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[(<Resource>this.$scope.component).csarUUID][(<Resource>this.$scope.component).csarVersion];
165 if(!onboardCsarFilesMap || !this.$scope.importedToscaBrowseFileText){
167 let onSuccess = (vsps:Array<ICsarComponent>): void =>{
168 onboardCsarFilesMap = {};
169 _.each(vsps, (vsp:ICsarComponent)=>{
170 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
171 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
173 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
174 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[(<Resource>this.$scope.component).csarUUID][(<Resource>this.$scope.component).csarVersion];
177 let onError = (): void =>{
178 console.log("Error getting onboarding list");
181 this.onBoardingService.getOnboardingVSPs().then(onSuccess, onError);
186 private initScope = ():void => {
188 // Work around to change the csar version
189 if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
190 (<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
193 this.$scope.importCsarProgressKey = "importCsarProgressKey";
194 this.$scope.browseFileLabel = this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType === ResourceType.VF ? "Upload file" : "Upload VFC";
195 this.$scope.progressService = this.progressService;
196 this.$scope.componentCategories = new componentCategories();
197 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
200 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
203 this.$scope.initCategoreis();
205 // Init Environment Context
206 this.$scope.initEnvironmentContext();
208 // Init the decision if to show file browse.
209 this.$scope.isShowFileBrowse = false;
210 if (this.$scope.component.isResource()) {
211 let resource:Resource = <Resource>this.$scope.component;
212 console.log(resource.name + ": " + resource.csarUUID);
213 if (resource.importedFile) { // Component has imported file.
214 this.$scope.isShowFileBrowse = true;
216 if (this.$scope.isEditMode() && resource.resourceType == ResourceType.VF && !resource.csarUUID) {
217 this.$scope.isShowFileBrowse = true;
221 this.initImportedToscaBrowseFile();
223 //init file extensions based on the file that was imported.
224 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
225 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
226 let fileExtension:string = fileName.split(".").pop();
227 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
228 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
229 (<Resource>this.$scope.component).importedFile.filetype = "csar";
230 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
231 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
232 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
234 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
235 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
236 //(<Resource>this.$scope.component).importedFile.filetype="csar";
239 this.$scope.setValidState(true);
241 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
242 let uniqueId:string = mainCategory;
244 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
249 //TODO remove this after handling contact in UI
250 if (this.$scope.isCreateMode()) {
251 this.$scope.component.contactId = this.cacheService.get("user").userId;
252 this.$scope.originComponent.contactId = this.$scope.component.contactId;
257 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
258 private convertCategoryStringToOneArray = ():Array<IMainCategory> => {
259 let tmp = this.$scope.component.selectedCategory.split("_#_");
260 let mainCategory = tmp[0];
261 let subCategory = tmp[1];
263 // Find the selected category and add the relevant sub category.
264 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
265 return item["name"] === mainCategory;
269 let mainCategoryClone = angular.copy(selectedMainCategory);
271 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
272 return item["name"] === subCategory;
274 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
276 let tmpSelected = <IMainCategory> mainCategoryClone;
278 let result:Array<IMainCategory> = [];
279 result.push(tmpSelected);
284 private updateComponentNameInBreadcrumbs = ():void => {
285 //update breadcrum after changing name
286 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
287 this.$scope.updateMenuComponentName(this.$scope.component.name);
290 private initScopeMethods = ():void => {
292 this.$scope.initCategoreis = ():void => {
293 if (this.$scope.componentType === ComponentType.RESOURCE) {
294 this.$scope.categories = this.cacheService.get('resourceCategories');
297 if (this.$scope.componentType === ComponentType.SERVICE) {
298 this.$scope.categories = this.cacheService.get('serviceCategories');
303 this.$scope.initEnvironmentContext = ():void => {
304 if (this.$scope.componentType === ComponentType.SERVICE) {
305 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
306 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
307 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
308 // In creation new service OR check outing old service without environmentContext parameter - set default value
309 if(this.$scope.isCreateMode() || (isCheckout && !environmentContext)){
310 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
315 this.$scope.validateField = (field:any):boolean => {
316 if (field && field.$dirty && field.$invalid) {
322 this.$scope.openOnBoardingModal = ():void => {
323 let csarUUID = (<Resource>this.$scope.component).csarUUID;
324 this.ModalsHandler.openOnboadrdingModal('Update', csarUUID).then(()=> {
326 this.$scope.uploadFileChangedInGeneralTab();
332 this.$scope.updateIcon = ():void => {
333 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
334 if(!this.$scope.isCreateMode()){
335 this.$state.current.data.unsavedChanges = this.$state.current.data.unsavedChanges || isDirty;
342 this.$scope.possibleToUpdateIcon = ():boolean => {
343 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName)){
350 this.$scope.validateName = (isInit:boolean):void => {
351 if (isInit === undefined) {
355 let name = this.$scope.component.name;
356 if (!name || name === "") {
357 if (this.$scope.editForm
358 && this.$scope.editForm["componentName"]
359 && this.$scope.editForm["componentName"].$error) {
361 // Clear the error name already exists
362 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
367 //?????????????????????????
368 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
370 let onFailed = (response) => {
371 //console.info('onFaild', response);
372 //this.$scope.isLoading = false;
375 let onSuccess = (validation:IValidate) => {
376 this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
377 if (validation.isValid) {
378 //update breadcrumb after changing name
379 this.updateComponentNameInBreadcrumbs();
384 // When page is init after update
385 if (this.$scope.component.name !== this.$scope.originComponent.name) {
386 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
388 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
392 // Validating on change (has debounce)
393 if (this.$scope.editForm
394 && this.$scope.editForm["componentName"]
395 && this.$scope.editForm["componentName"].$error
396 && !this.$scope.editForm["componentName"].$error.pattern
397 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
399 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
401 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
403 } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
405 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
410 this.$scope.$watchCollection('component.name', (newData:any):void => {
411 this.$scope.validateName(false);
414 // Notify the parent if this step valid or not.
415 this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
416 this.$scope.setValidState(newVal);
419 this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
420 if (newVal !== oldVal) {
421 this.$state.current.data.unsavedChanges = newVal && !this.$scope.isCreateMode();
425 this.$scope.onCategoryChange = ():void => {
426 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
427 this.$scope.component.categories = this.convertCategoryStringToOneArray();
428 this.$scope.component.icon = DEFAULT_ICON;
431 this.$scope.onEcompGeneratedNamingChange = ():void =>{
432 if(!(<Service>this.$scope.component).ecompGeneratedNaming){
433 (<Service>this.$scope.component).namingPolicy = '';
437 this.$scope.onVendorNameChange = (oldVendorName:string):void => {
438 if (this.$scope.component.icon === oldVendorName) {
439 this.$scope.component.icon = DEFAULT_ICON;
442 this.EventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, this.$scope.reload);
443 this.EventListenerService.registerObserverCallback(EVENTS.ON_REVERT, ()=>{
444 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;