Sync Integ to Master
[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 * as _ from "lodash";
23 import {Component, IMainCategory, IGroup, IConfigStatuses, IAppMenu, IAppConfigurtaion, IUserProperties, ISubCategory} from "app/models";
24 import {EntityService, CacheService} from "app/services";
25 import {ComponentFactory, ResourceType, MenuHandler, ChangeLifecycleStateHandler} from "app/utils";
26 import {UserService} from "../../ng2/services/user.service";
27
28
29 interface Checkboxes {
30     componentTypes:Array<string>;
31     resourceSubTypes:Array<string>;
32 }
33
34 interface CheckboxesFilter {
35     // Types
36     selectedComponentTypes:Array<string>;
37     selectedResourceSubTypes:Array<string>;
38     // Categories
39     selectedCategoriesModel:Array<string>;
40     // Statuses
41     selectedStatuses:Array<string>;
42 }
43
44 interface Gui {
45     isLoading:boolean;
46     onResourceSubTypesClick:Function;
47     onComponentTypeClick:Function;
48     onCategoryClick:Function;
49     onSubcategoryClick:Function;
50     onGroupClick:Function;
51 }
52
53 export interface ICatalogViewModelScope extends ng.IScope {
54     checkboxes:Checkboxes;
55     checkboxesFilter:CheckboxesFilter;
56     gui:Gui;
57
58     categories:Array<IMainCategory>;
59     confStatus:IConfigStatuses;
60     sdcMenu:IAppMenu;
61     catalogFilterdItems:Array<Component>;
62     expandedSection:Array<string>;
63     actionStrategy:any;
64     user:IUserProperties;
65     catalogMenuItem:any;
66     version:string;
67     sortBy:string;
68     reverse:boolean;
69     vfcmtType:string;
70
71     //this is for UI paging
72     numberOfItemToDisplay:number;
73     isAllItemDisplay:boolean;
74
75     changeLifecycleState(entity:any, state:string):void;
76     sectionClick (section:string):void;
77     order(sortBy:string):void;
78     getNumOfElements(num:number):string;
79     goToComponent(component:Component):void;
80     raiseNumberOfElementToDisplay():void;
81 }
82
83 export class CatalogViewModel {
84     static '$inject' = [
85         '$scope',
86         '$filter',
87         'Sdc.Services.EntityService',
88         'sdcConfig',
89         'sdcMenu',
90         '$state',
91         '$q',
92         'UserServiceNg2',
93         'Sdc.Services.CacheService',
94         'ComponentFactory',
95         'ChangeLifecycleStateHandler',
96         'MenuHandler'
97     ];
98
99     constructor(private $scope:ICatalogViewModelScope,
100                 private $filter:ng.IFilterService,
101                 private EntityService:EntityService,
102                 private sdcConfig:IAppConfigurtaion,
103                 private sdcMenu:IAppMenu,
104                 private $state:ng.ui.IStateService,
105                 private $q:ng.IQService,
106                 private userService:UserService,
107                 private cacheService:CacheService,
108                 private ComponentFactory:ComponentFactory,
109                 private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler,
110                 private MenuHandler:MenuHandler) {
111
112
113         this.initScopeMembers();
114         this.initCatalogData(); // Async task to get catalog from server.
115         this.initScopeMethods();
116     }
117
118     private initCatalogData = ():void => {
119         let onSuccess = (followedResponse:Array<Component>):void => {
120             this.$scope.catalogFilterdItems = followedResponse;
121             this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
122             this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories'));
123             this.$scope.gui.isLoading = false;
124         };
125
126         let onError = ():void => {
127             console.info('Failed to load catalog CatalogViewModel::initCatalog');
128             this.$scope.gui.isLoading = false;
129         };
130         this.EntityService.getCatalog().then(onSuccess, onError);
131     };
132
133
134     private initScopeMembers = ():void => {
135         // Gui init
136         this.$scope.gui = <Gui>{};
137         this.$scope.gui.isLoading = true;
138         this.$scope.numberOfItemToDisplay = 0;
139         //this.$scope.categories = this.cacheService.get('categoriesMap');
140         this.$scope.sdcMenu = this.sdcMenu;
141         this.$scope.confStatus = this.sdcMenu.statuses;
142         this.$scope.expandedSection = ["type", "category", "status"];
143         this.$scope.user = this.userService.getLoggedinUser();
144         this.$scope.catalogMenuItem = this.sdcMenu.catalogMenuItem;
145         this.$scope.version = this.cacheService.get('version');
146         this.$scope.sortBy = 'lastUpdateDate';
147         this.$scope.reverse = true;
148
149
150         // Checklist init
151         this.$scope.checkboxes = <Checkboxes>{};
152         this.$scope.checkboxes.componentTypes = ['Resource', 'Service'];
153         this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'CR', 'PNF', 'CP', 'VL'];
154
155         // Checkboxes filter init
156         this.$scope.checkboxesFilter = <CheckboxesFilter>{};
157         this.$scope.checkboxesFilter.selectedComponentTypes = [];
158         this.$scope.checkboxesFilter.selectedResourceSubTypes = [];
159         this.$scope.checkboxesFilter.selectedCategoriesModel = [];
160         this.$scope.checkboxesFilter.selectedStatuses = [];
161
162         //      this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
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 }