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