aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-ui/src/app/ng2/pages/home/home.component.ts
blob: 77fd3b5ae4c4eb09020dbdff9fd6703d59b6f360 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
'use strict';
import { Component as NgComponent, Inject, OnInit } from '@angular/core';
import { Component, IConfigRoles, IUserProperties, Resource } from 'app/models';
import { HomeFilter } from 'app/models/home-filter';
import { AuthenticationService, CacheService, HomeService } from 'app/services-ng2';
import { ModalsHandler } from 'app/utils';
import { SdcUiServices } from 'onap-ui-angular';
import { CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, ResourceType } from '../../../utils/constants';
import { ImportVSPService } from '../../components/modals/onboarding-modal/import-vsp.service';
import { ISdcConfig, SdcConfigToken } from '../../config/sdc-config.config';
import { IAppMenu, SdcMenuToken } from '../../config/sdc-menu.config';
import { EntityFilterPipe } from '../../pipes/entity-filter.pipe';
import { TranslateService } from '../../shared/translator/translate.service';
import { FoldersItemsMenu, FoldersItemsMenuGroup, FoldersMenu } from './folders';

@NgComponent({
    selector: 'home-page',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {
    public numberOfItemToDisplay: number;
    public homeItems: Component[];
    public homeFilteredItems: Component[];
    public homeFilteredSlicedItems: Component[];
    public folders: FoldersMenu;
    public roles: IConfigRoles;
    public user: IUserProperties;
    public showTutorial: boolean;
    public isFirstTime: boolean;
    public version: string;
    public homeFilter: HomeFilter;
    public vfcmtType: string;
    public displayActions: boolean;

    constructor(
        @Inject(SdcConfigToken) private sdcConfig: ISdcConfig,
        @Inject(SdcMenuToken) public sdcMenu: IAppMenu,
        @Inject('$state') private $state: ng.ui.IStateService,
        private homeService: HomeService,
        private authService: AuthenticationService,
        private cacheService: CacheService,
        private translateService: TranslateService,
        private modalsHandler: ModalsHandler,
        private modalService: SdcUiServices.ModalService,
        private loaderService: SdcUiServices.LoaderService,
        private importVSPService: ImportVSPService
    ) {}

    ngOnInit(): void {
        this.initHomeComponentVars();
        this.initFolders();
        this.initEntities();

        if (this.$state.params) {
            if (this.$state.params.folder) {
                const folderName = this.$state.params.folder.replaceAll('_', ' ');

                const selectedFolder = this.folders.getFolders().find((tmpFolder: FoldersItemsMenu) => tmpFolder.text === folderName);
                if (selectedFolder) {
                    this.setSelectedFolder(selectedFolder);
                }
                // Show the tutorial if needed when the dashboard page is opened.<script src="bower_components/angular-filter/dist/angular-filter.min.js"></script>
                // This is called from the welcome page.
            } else if (this.$state.params.show === 'tutorial') {
                this.showTutorial = true;
                this.isFirstTime = true;
            }
        }
    }

    // Open onboarding modal
    public notificationIconCallback(): void {
        this.importVSPService.openOnboardingModal().subscribe((result) => {
            if (!result.previousComponent || result.previousComponent.csarVersion !== result.componentCsar.csarVersion) {
                this.cacheService.set(CHANGE_COMPONENT_CSAR_VERSION_FLAG, result.componentCsar.csarVersion);
            }
            this.$state.go('workspace.general', {
                id: result.previousComponent && result.previousComponent.uniqueId,
                componentCsar: result.componentCsar,
                type: result.type
            });
        });
    }

    public onImportVf(file: any): void {
        if (file && file.filename) {
            // Check that the file has valid extension.
            const fileExtension: string = file.filename.split('.').pop();
            if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
                this.$state.go('workspace.general', {
                    type: ComponentType.RESOURCE.toLowerCase(),
                    importedFile: file,
                    resourceType: ResourceType.VF
                });
            } else {
                const title: string = this.translateService.translate('NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS_TITLE');
                const message: string = this.translateService.translate('NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS', {extensions: this.sdcConfig.csarFileExtension});
                this.modalService.openWarningModal(title, message, 'error-invalid-csar-ext');
            }
        }
    }

    public onImportVfc(file: any): void {
        if (file && file.filename) {
            // Check that the file has valid extension.
            const fileExtension: string = file.filename.split('.').pop();
            if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
                this.$state.go('workspace.general', {
                    type: ComponentType.RESOURCE.toLowerCase(),
                    importedFile: file,
                    resourceType: ResourceType.VFC
                });
            } else {
                const title: string = this.translateService.translate('NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS_TITLE');
                const message: string = this.translateService.translate('NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS', {extensions: this.sdcConfig.toscaFileExtension});
                this.modalService.openWarningModal(title, message, 'error-invalid-tosca-ext');
            }
        }
    }

    public onImportService(file: any): void {
        if (file && file.filename) {
            // Check that the file has valid extension.
            const fileExtension: string = file.filename.split(".").pop();
            if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
                this.$state.go('workspace.general', {
                    type: ComponentType.SERVICE.toLowerCase(),
                    importedFile: file,
                    serviceType: 'Service'
                });
            } else {
                const title: string = this.translateService.translate('NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS_TITLE');
                const message: string = this.translateService.translate('NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS', {extensions: this.sdcConfig.csarFileExtension});
                this.modalService.openWarningModal(title, message, 'error-invalid-csar-ext');
            }
        }
    };

    public openCreateModal(componentType: string, importedFile: any): void {
        if (importedFile) {
            this.initEntities(true); // Return from import
        } else {
            this.$state.go('workspace.general', {type: componentType.toLowerCase()});
        }
    }

    public createPNF(): void {
        this.$state.go('workspace.general', {
            type: ComponentType.RESOURCE.toLowerCase(),
            resourceType: ResourceType.PNF
        });
    }

    public createCR(): void {
        this.$state.go('workspace.general', {
            type: ComponentType.RESOURCE.toLowerCase(),
            resourceType: ResourceType.CR
        });
    }

    public entitiesCount(folderItem: FoldersItemsMenu): any {
        let total: number = 0;
        if (folderItem.isGroup()) {
            this.folders.getFolders().forEach((tmpFolder: FoldersItemsMenu) => {
                if (tmpFolder.group && tmpFolder.group === (folderItem as FoldersItemsMenuGroup).groupname) {
                    total = total + this._getTotalCounts(tmpFolder);
                }
            });
        } else {
            total = total + this._getTotalCounts(folderItem);
        }
        return total;
    }

    public updateFilter = () => {
        this.$state.go('.', this.homeFilter.toUrlParam(), {location: 'replace', notify: false});
        this.filterHomeItems();
    }

    public getCurrentFolderDistributed(): any[] {
        const states = [];
        if (this.folders) {
            const folderItem: FoldersItemsMenu = this.folders.getCurrentFolder();
            if (folderItem.isGroup()) {
                this.folders.getFolders().forEach((tmpFolder: FoldersItemsMenu) => {
                    if (tmpFolder.group && tmpFolder.group === (folderItem as FoldersItemsMenuGroup).groupname) {
                        this._setStates(tmpFolder, states);
                    }
                });
            } else {
                this._setStates(folderItem, states);
            }
        }
        return states;
    }

    public setSelectedFolder(folderItem: FoldersItemsMenu): void {
        this.folders.setSelected(folderItem);
    }

    public goToComponent(component: Component): void {
        const loaderService = this.loaderService;
        loaderService.activate();
        this.$state.go('workspace.general', {id: component.uniqueId, type: component.componentType.toLowerCase()}).then(() => {
            loaderService.deactivate();
        });
    }

    public raiseNumberOfElementToDisplay(recalculate: boolean = false) {
        const scrollPageAmount = 35;
        if (!this.homeItems) {
            this.numberOfItemToDisplay = 0;
        } else if (this.homeItems.length > this.numberOfItemToDisplay || recalculate) {
            let fullPagesAmount = Math.ceil(this.numberOfItemToDisplay / scrollPageAmount) * scrollPageAmount;
            if (!recalculate || fullPagesAmount === 0) {  // TODO trigger infiniteScroll to check bottom and fire onBottomHit by itself (sdc-ui)
                fullPagesAmount += scrollPageAmount;
            }
            this.numberOfItemToDisplay = Math.min(this.homeItems.length, fullPagesAmount);
            this.homeFilteredSlicedItems = this.homeFilteredItems.slice(0, this.numberOfItemToDisplay);
        }
    }

    public changeCheckboxesFilter(checkboxesFilterArray: string[], checkboxValue: string, checked?: boolean) {
        const checkboxIdx = checkboxesFilterArray.indexOf(checkboxValue);

        checked = (checked !== undefined) ? checked : checkboxIdx === -1;
        if (checked && checkboxIdx === -1) {
            checkboxesFilterArray.push(checkboxValue);
        } else if (!checked && checkboxIdx !== -1) {
            checkboxesFilterArray.splice(checkboxIdx, 1);
        }
        this.updateFilter();
    }

    public changeFilterTerm(filterTerm: string): void {
        this.homeFilter.search = { filterTerm };
        this.updateFilter();
    }

    public setDisplayActions(display?: boolean) {
        this.displayActions = display !== undefined ? display : !this.displayActions;
    }

    private _getTotalCounts(tmpFolder): number {
        let total: number = 0;
        if (tmpFolder.dist !== undefined) {
            const distributions = tmpFolder.dist.split(',');
            distributions.forEach((item: any) => {
                total = total + this.getEntitiesByStateDist(tmpFolder.state, item).length;
            });
        } else {
            total = total + this.getEntitiesByStateDist(tmpFolder.state, tmpFolder.dist).length;
        }
        return total;
    }

    private _setStates(tmpFolder, states) {
        if (tmpFolder.states !== undefined) {
            tmpFolder.states.forEach((item: any) => {
                states.push({state: item.state, dist: item.dist});
            });
        } else {
            states.push({state: tmpFolder.state, dist: tmpFolder.dist});
        }
    }

    private initEntities(reload?: boolean) {
        if (reload || this.componentShouldReload()) {
            this.loaderService.activate();
            this.homeService.getAllComponents(true).subscribe(
                (components: Component[]) => {
                    this.cacheService.set('breadcrumbsComponentsState', this.$state.current.name);  // dashboard
                    this.cacheService.set('breadcrumbsComponents', components);
                    this.homeItems = components;
                    this.loaderService.deactivate();
                    this.filterHomeItems();
                }, (error) => { this.loaderService.deactivate(); });
        } else {
            this.homeItems = this.cacheService.get('breadcrumbsComponents');
            this.filterHomeItems();
        }
    }

    private isDefaultFilter = (): boolean => {
        const defaultFilter = new HomeFilter();
        return angular.equals(defaultFilter, this.homeFilter);
    }

    private componentShouldReload = (): boolean => {
        const breadcrumbsValid: boolean = (this.$state.current.name === this.cacheService.get('breadcrumbsComponentsState') && this.cacheService.contains('breadcrumbsComponents'));
        return !breadcrumbsValid || this.isDefaultFilter();
    }

    private getEntitiesByStateDist(state: string, dist: string): Component[] {
        let gObj: Component[];
        if (this.homeItems && (state || dist)) {
            gObj = this.homeItems.filter((obj: Component) => {
                if (dist !== undefined && obj.distributionStatus === dist && obj.lifecycleState === state) {
                    return true;
                } else if (dist === undefined && (obj.lifecycleState === state || obj.distributionStatus === state)) {
                    return true;
                }
                return false;
            });
        } else {
            gObj = [];
        }
        return gObj;
    }

    private filterHomeItems() {
        this.homeFilteredItems = this.makeFilteredItems(this.homeItems, this.homeFilter);
        this.raiseNumberOfElementToDisplay(true);
        this.homeFilteredSlicedItems = this.homeFilteredItems.slice(0, this.numberOfItemToDisplay);
    }

    private makeFilteredItems(homeItems: Component[], filter: HomeFilter) {
        let filteredComponents: Component[] = homeItems;

        // filter: exclude all resources of type 'vfcmtType':
        filteredComponents = filteredComponents.filter((c) =>
            !c.isResource() || (c as Resource).resourceType.indexOf(this.vfcmtType) === -1);

        // common entity filter
        // --------------------------------------------------------------------------
        filteredComponents = EntityFilterPipe.transform(filteredComponents, filter);

        return filteredComponents;
    }

    private initFolders = (): void => {
        // Note: Do not use SdcUi.ChecklistComponent for folders checkboxes, since from the data structure
        // it is not determined that all checkboxes under the same group are managed by the same selectedValues array.
        if (this.user) {
            this.folders = new FoldersMenu(this.roles[this.user.role].folder);
        }
    }

    private initHomeComponentVars(): void {
        this.version = this.cacheService.get('version');
        this.numberOfItemToDisplay = 0;
        this.displayActions = false;
        this.user = this.authService.getLoggedinUser();
        this.roles = this.sdcMenu.roles;
        this.showTutorial = false;
        this.isFirstTime = false;
        this.vfcmtType = ResourceType.VFCMT;

        // Checkboxes filter init
        this.homeFilter = new HomeFilter(this.$state.params);

        // bind callbacks that are transferred as inputs
        this.notificationIconCallback = this.notificationIconCallback.bind(this);
    }

}