[SDC] rebase 1710 code
[sdc.git] / catalog-ui / src / app / view-models / catalog / catalog-view-model.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 import {Component, IMainCategory, IGroup, IConfigStatuses, IAppMenu, IAppConfigurtaion, IUserProperties, ISubCategory} from "app/models";
23 import {EntityService, IUserResourceClass, CacheService} from "app/services";
24 import {ComponentFactory, ResourceType, MenuHandler, ChangeLifecycleStateHandler} from "app/utils";
25
26
27 interface Checkboxes {
28     componentTypes:Array<string>;
29     resourceSubTypes:Array<string>;
30 }
31
32 interface CheckboxesFilter {
33     // Types
34     selectedComponentTypes:Array<string>;
35     selectedResourceSubTypes:Array<string>;
36     // Categories
37     selectedCategoriesModel:Array<string>;
38     // Statuses
39     selectedStatuses:Array<string>;
40 }
41
42 interface Gui {
43     isLoading:boolean;
44     onResourceSubTypesClick:Function;
45     onComponentTypeClick:Function;
46     onCategoryClick:Function;
47     onSubcategoryClick:Function;
48     onGroupClick:Function;
49 }
50
51 export interface ICatalogViewModelScope extends ng.IScope {
52     checkboxes:Checkboxes;
53     checkboxesFilter:CheckboxesFilter;
54     gui:Gui;
55
56     categories:Array<IMainCategory>;
57     confStatus:IConfigStatuses;
58     sdcMenu:IAppMenu;
59     catalogFilterdItems:Array<Component>;
60     expandedSection:Array<string>;
61     actionStrategy:any;
62     user:IUserProperties;
63     catalogMenuItem:any;
64     version:string;
65     sortBy:string;
66     reverse:boolean;
67     vfcmtType:string;
68
69     //this is for UI paging
70     numberOfItemToDisplay:number;
71     isAllItemDisplay:boolean;
72
73     changeLifecycleState(entity:any, state:string):void;
74     sectionClick (section:string):void;
75     order(sortBy:string):void;
76     getNumOfElements(num:number):string;
77     goToComponent(component:Component):void;
78     raiseNumberOfElementToDisplay():void;
79 }
80
81 export class CatalogViewModel {
82     static '$inject' = [
83         '$scope',
84         '$filter',
85         'Sdc.Services.EntityService',
86         'sdcConfig',
87         'sdcMenu',
88         '$state',
89         '$q',
90         'Sdc.Services.UserResourceService',
91         'Sdc.Services.CacheService',
92         'ComponentFactory',
93         'ChangeLifecycleStateHandler',
94         'MenuHandler'
95     ];
96
97     constructor(private $scope:ICatalogViewModelScope,
98                 private $filter:ng.IFilterService,
99                 private EntityService:EntityService,
100                 private sdcConfig:IAppConfigurtaion,
101                 private sdcMenu:IAppMenu,
102                 private $state:ng.ui.IStateService,
103                 private $q:ng.IQService,
104                 private userResourceService:IUserResourceClass,
105                 private cacheService:CacheService,
106                 private ComponentFactory:ComponentFactory,
107                 private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler,
108                 private MenuHandler:MenuHandler) {
109
110
111         this.initScopeMembers();
112         this.initCatalogData(); // Async task to get catalog from server.
113         this.initScopeMethods();
114     }
115
116     private initCatalogData = ():void => {
117         let onSuccess = (followedResponse:Array<Component>):void => {
118             this.$scope.catalogFilterdItems = followedResponse;
119             this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
120             this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories'));
121             this.$scope.gui.isLoading = false;
122         };
123
124         let onError = ():void => {
125             console.info('Failed to load catalog CatalogViewModel::initCatalog');
126             this.$scope.gui.isLoading = false;
127         };
128         this.EntityService.getCatalog().then(onSuccess, onError);
129     };
130
131
132     private initScopeMembers = ():void => {
133         // Gui init
134         this.$scope.gui = <Gui>{};
135         this.$scope.gui.isLoading = true;
136         this.$scope.numberOfItemToDisplay = 0;
137         //this.$scope.categories = this.cacheService.get('categoriesMap');
138         this.$scope.sdcMenu = this.sdcMenu;
139         this.$scope.confStatus = this.sdcMenu.statuses;
140         this.$scope.expandedSection = ["type", "category", "status"];
141         this.$scope.user = this.userResourceService.getLoggedinUser();
142         this.$scope.catalogMenuItem = this.sdcMenu.catalogMenuItem;
143         this.$scope.version = this.cacheService.get('version');
144         this.$scope.sortBy = 'lastUpdateDate';
145         this.$scope.reverse = true;
146
147
148         // Checklist init
149         this.$scope.checkboxes = <Checkboxes>{};
150         this.$scope.checkboxes.componentTypes = ['Resource', 'Service'];
151         this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'PNF', 'CP', 'VL'];
152
153         // Checkboxes filter init
154         this.$scope.checkboxesFilter = <CheckboxesFilter>{};
155         this.$scope.checkboxesFilter.selectedComponentTypes = [];
156         this.$scope.checkboxesFilter.selectedResourceSubTypes = [];
157         this.$scope.checkboxesFilter.selectedCategoriesModel = [];
158         this.$scope.checkboxesFilter.selectedStatuses = [];
159
160         //      this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
161
162         this.$scope.vfcmtType = ResourceType.VFCMT;
163     };
164
165     private initScopeMethods = ():void => {
166         this.$scope.sectionClick = (section:string):void => {
167             let index:number = this.$scope.expandedSection.indexOf(section);
168             if (index !== -1) {
169                 this.$scope.expandedSection.splice(index, 1);
170             } else {
171                 this.$scope.expandedSection.push(section);
172             }
173         };
174
175
176         this.$scope.order = (sortBy:string):void => {//default sort by descending last update. default for alphabetical = ascending
177             this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : (sortBy === 'lastUpdateDate') ? true : false;
178             this.$scope.sortBy = sortBy;
179         };
180
181
182         this.$scope.goToComponent = (component:Component):void => {
183             this.$scope.gui.isLoading = true;
184             this.$state.go('workspace.general', {id: component.uniqueId, type: component.componentType.toLowerCase()});
185         };
186
187
188         // Will print the number of elements found in catalog
189         this.$scope.getNumOfElements = (num:number):string => {
190             if (!num || num === 0) {
191                 return "No Elements found";
192             } else if (num === 1) {
193                 return "1 Element found";
194             } else {
195                 return num + " Elements found";
196             }
197         };
198
199         /**
200          * Select | unselect sub resource when resource is clicked | unclicked.
201          * @param type
202          */
203         this.$scope.gui.onComponentTypeClick = (type:string):void => {
204             if (type === 'Resource') {
205                 if (this.$scope.checkboxesFilter.selectedComponentTypes.indexOf('Resource') === -1) {
206                     // If the resource was not selected, unselect all childs.
207                     this.$scope.checkboxesFilter.selectedResourceSubTypes = [];
208                 } else {
209                     // If the resource was selected, select all childs
210                     this.$scope.checkboxesFilter.selectedResourceSubTypes = angular.copy(this.$scope.checkboxes.resourceSubTypes);
211                 }
212             }
213         };
214
215         /**
216          * Selecting | unselect resources when sub resource is clicked | unclicked.
217          */
218         this.$scope.gui.onResourceSubTypesClick = ():void => {
219             if (this.$scope.checkboxesFilter.selectedResourceSubTypes && this.$scope.checkboxesFilter.selectedResourceSubTypes.length === this.$scope.checkboxes.resourceSubTypes.length) {
220                 this.$scope.checkboxesFilter.selectedComponentTypes.push('Resource');
221             } else {
222                 this.$scope.checkboxesFilter.selectedComponentTypes = _.without(this.$scope.checkboxesFilter.selectedComponentTypes, 'Resource');
223             }
224         };
225
226         this.$scope.gui.onCategoryClick = (category:IMainCategory):void => {
227             // Select | Unselect all childs
228             if (this.isCategorySelected(category.uniqueId)) {
229                 this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(category.subcategories, (item) => {
230                     return item.uniqueId;
231                 })));
232                 if (category.subcategories) {
233                     category.subcategories.forEach((sub:ISubCategory)=> { // Loop on all selected subcategories and mark the childrens
234                         this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(sub.groupings, (item) => {
235                             return item.uniqueId;
236                         })));
237                     });
238                 }
239             } else {
240                 this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(category.subcategories, (item) => {
241                     return item.uniqueId;
242                 }));
243                 if (category.subcategories) {
244                     category.subcategories.forEach((sub:ISubCategory)=> { // Loop on all selected subcategories and un mark the childrens
245                         this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(sub.groupings, (item) => {
246                             return item.uniqueId;
247                         }));
248                     });
249                 }
250             }
251         };
252
253         this.$scope.gui.onSubcategoryClick = (category:IMainCategory, subCategory:ISubCategory):void => {
254             // Select | Unselect all childs
255             if (this.isCategorySelected(subCategory.uniqueId)) {
256                 this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(subCategory.groupings, (item) => {
257                     return item.uniqueId;
258                 })));
259             } else {
260                 this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(subCategory.groupings, (item) => {
261                     return item.uniqueId;
262                 }));
263             }
264
265             // Mark | Un mark the parent when all childs selected.
266             if (this.areAllCategoryChildsSelected(category)) {
267                 // Add the category to checkboxesFilter.selectedCategoriesModel
268                 this.$scope.checkboxesFilter.selectedCategoriesModel.push(category.uniqueId);
269             } else {
270                 this.$scope.checkboxesFilter.selectedCategoriesModel = _.without(this.$scope.checkboxesFilter.selectedCategoriesModel, category.uniqueId);
271             }
272
273         };
274
275         this.$scope.raiseNumberOfElementToDisplay = ():void => {
276             this.$scope.numberOfItemToDisplay = this.$scope.numberOfItemToDisplay + 35;
277             if (this.$scope.catalogFilterdItems) {
278                 this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
279             }
280         };
281
282         this.$scope.gui.onGroupClick = (subCategory:ISubCategory):void => {
283             // Mark | Un mark the parent when all childs selected.
284             if (this.areAllSubCategoryChildsSelected(subCategory)) {
285                 // Add the category to checkboxesFilter.selectedCategoriesModel
286                 this.$scope.checkboxesFilter.selectedCategoriesModel.push(subCategory.uniqueId);
287             } else {
288                 this.$scope.checkboxesFilter.selectedCategoriesModel = _.without(this.$scope.checkboxesFilter.selectedCategoriesModel, subCategory.uniqueId);
289             }
290         };
291
292
293     };
294
295     private areAllCategoryChildsSelected = (category:IMainCategory):boolean => {
296         if (!category.subcategories) {
297             return false;
298         }
299         let allIds = _.map(category.subcategories, (sub:ISubCategory)=> {
300             return sub.uniqueId;
301         });
302         let total = _.intersection(this.$scope.checkboxesFilter.selectedCategoriesModel, allIds);
303         return total.length === category.subcategories.length ? true : false;
304     };
305
306     private areAllSubCategoryChildsSelected = (subCategory:ISubCategory):boolean => {
307         if (!subCategory.groupings) {
308             return false;
309         }
310         let allIds = _.map(subCategory.groupings, (group:IGroup)=> {
311             return group.uniqueId;
312         });
313         let total = _.intersection(this.$scope.checkboxesFilter.selectedCategoriesModel, allIds);
314         return total.length === subCategory.groupings.length ? true : false;
315     };
316
317     private isCategorySelected = (uniqueId:string):boolean => {
318         if (this.$scope.checkboxesFilter.selectedCategoriesModel.indexOf(uniqueId) !== -1) {
319             return true;
320         }
321         return false;
322     };
323 }