monitor-dashboard/src/app/monitor/monitor.component.ts

410 lines
17 KiB
TypeScript

import {ChangeDetectorRef, Component, OnDestroy, OnInit, ViewRef} from '@angular/core';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {DomSanitizer, Meta, Title} from '@angular/platform-browser';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {StringUtils} from '../openaireLibrary/utils/string-utils.class';
import {ErrorCodes} from '../openaireLibrary/utils/properties/errorCodes';
import {ErrorMessagesComponent} from '../openaireLibrary/utils/errorMessages.component';
import {HelperService} from "../openaireLibrary/utils/helper/helper.service";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {Category, ChartHelper, IndicatorPath, Stakeholder, SubCategory, Topic} from "../openaireLibrary/monitor/entities/stakeholder";
import {StatisticsService} from "../utils/services/statistics.service";
import {IndicatorUtils, StakeholderUtils} from "../utils/indicator-utils";
import {LayoutService} from "../openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
import {FormBuilder, FormControl} from "@angular/forms";
import {IDeactivateComponent} from "../openaireLibrary/utils/can-exit.guard";
import {Subscription} from "rxjs";
import {Session, User} from "../openaireLibrary/login/utils/helper.class";
import {MenuItem} from "../openaireLibrary/sharedComponents/menu";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {StakeholderCreator} from "../utils/entities/stakeholderCreator";
@Component({
selector: 'monitor',
templateUrl: 'monitor.component.html',
styleUrls:['monitor.component.css']
})
export class MonitorComponent implements OnInit, OnDestroy, IDeactivateComponent {
private static sidebarStatus: {
id;
status;
};
public user: User;
public userMenuItems: MenuItem[] = [new MenuItem("", "My profile", "", "", false, [], [], {})];
public subscriptions: any[] = [];
public piwiksub: any;
public pageContents = null;
public divContents = null;
public status: number;
public loading: boolean = true;
public isViewPublic: boolean = false;
public indicatorUtils: IndicatorUtils = new IndicatorUtils();
public stakeholderUtils: StakeholderUtils = new StakeholderUtils();
public activeTopic: Topic = null;
public activeCategory: Category = null;
public activeSubCategory: SubCategory = null;
public sideBarItems: MenuItem[] = [];
public topBarItems: MenuItem[] = [];
public errorCodes: ErrorCodes;
public stakeholder: Stakeholder;
public numberResults: Map<string, number> = new Map<string, number>();
public chartsActiveType: Map<string, IndicatorPath> = new Map<string, IndicatorPath>();
private errorMessages: ErrorMessagesComponent;
properties: EnvProperties;
fundingL0;
startYear;
endYear;
privateStakeholder = false;
public keyword: FormControl;
constructor(
private route: ActivatedRoute,
private _router: Router,
private _meta: Meta,
private _title: Title,
private _piwikService: PiwikService,
private helper: HelperService,
private stakeholderService: StakeholderService,
private userManagementService: UserManagementService,
private statisticsService: StatisticsService,
private layoutService: LayoutService,
private seoService: SEOService,
private cdr: ChangeDetectorRef,
private sanitizer: DomSanitizer, private _fb: FormBuilder) {
this.errorCodes = new ErrorCodes();
this.errorMessages = new ErrorMessagesComponent();
this.status = this.errorCodes.LOADING;
}
public ngOnInit() {
this.keyword = this._fb.control('');
this.keyword.valueChanges.subscribe(value => {
console.log("Keyword Changed!");
//TODO do a real action
});
this.route.data
.subscribe((data: { envSpecific: EnvProperties }) => {
let subscription: Subscription;
this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
this.user = user;
this.route.params.subscribe(params => {
this.loading = true;
this.activeTopic = null;
this.activeCategory = null;
this.activeSubCategory = null;
if (subscription) {
subscription.unsubscribe();
}
this.properties = data.envSpecific;
var url = data.envSpecific.baseLink + this._router.url;
this.route.queryParams.subscribe(params => {
this.isViewPublic = (params['view'] == 'public');
});
this.buildMenu();
if (!this.stakeholder || this.stakeholder.alias !== params['stakeholder']) {
this.status = this.errorCodes.LOADING;
this.numberResults = new Map<string, number>();
this.chartsActiveType = new Map<string, IndicatorPath>();
subscription = this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
if (stakeholder) {
this.stakeholder = stakeholder;
if(stakeholder.isActive && (stakeholder.isPublic || this.isAdmin())) {
this.seoService.createLinkForCanonicalURL(url, false);
this._meta.updateTag({content: url}, "property='og:url'");
var description = "Monitor Dashboard | " + this.stakeholder.name;
var title = "Monitor Dashboard | " + this.stakeholder.name;
this._meta.updateTag({content: description}, "name='description'");
this._meta.updateTag({content: description}, "property='og:description'");
this._meta.updateTag({content: title}, "property='og:title'");
this._title.setTitle(title);
if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
this.piwiksub = this._piwikService.trackView(this.properties, title, this.properties.piwikSiteId).subscribe();
}
//this.getDivContents();
this.getPageContents();
this.status = this.errorCodes.DONE;
this.setView(params);
this.layoutService.setOpen(true);
} else {
this.privateStakeholder = true;
// this.navigateToError();
if(subscription) {
subscription.unsubscribe();
}
}
}
});
this.subscriptions.push(subscription);
} else {
this.setView(params);
}
});
}));
});
}
canExit() {
if (this.sideBarItems.length > 0) {
let status = [];
this.sideBarItems.forEach(item => {
status.push(item.open);
});
MonitorComponent.sidebarStatus = {
id: this.activeTopic.alias,
status: status
};
}
return true;
}
public get open() {
return this.layoutService.open;
}
private getPageContents() {
this.helper.getPageHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
this.pageContents = contents;
})
}
private getDivContents() {
this.helper.getDivHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
this.divContents = contents;
})
}
private setView(params: Params) {
if (params['topic']) {
this.activeTopic = this.stakeholder.topics.find(topic => topic.alias === decodeURIComponent(params['topic']) && this.isPublicOrIsMember(topic.isPublic) && topic.isActive);
if (this.activeTopic) {
if (params['category']) {
this.activeCategory = this.activeTopic.categories.find(category =>
(category.alias === params['category']) && this.isPublicOrIsMember(category.isPublic) && category.isActive);
if (!this.activeCategory) {
this.navigateToError();
return;
}
} else {
this.activeCategory = this.activeTopic.categories.find(category => this.isPublicOrIsMember(category.isPublic) && category.isActive);
if (this.activeCategory) {
this.activeSubCategory = this.activeCategory.subCategories.find(subCategory =>
this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive);
this.setSideBar();
if (this.activeSubCategory) {
this.setIndicators();
}
} else {
this.setSideBar();
}
return;
}
if (this.activeCategory) {
if (params['subCategory']) {
this.activeSubCategory = this.activeCategory.subCategories.find(subCategory =>
(subCategory.alias === params['subCategory'] && this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive));
if (!this.activeSubCategory) {
this.navigateToError();
return;
}
} else {
this.activeSubCategory = this.activeCategory.subCategories.find(subCategory =>
this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive);
}
if (this.activeSubCategory) {
this.setSideBar();
this.setIndicators();
} else {
this.navigateToError();
}
return;
} else {
this.activeSubCategory = null;
}
} else {
this.navigateToError();
return;
}
} else {
this.activeTopic = this.stakeholder.topics.find(topic => this.isPublicOrIsMember(topic.isPublic) && topic.isActive);
if (this.activeTopic) {
this.activeCategory = this.activeTopic.categories.find(category => this.isPublicOrIsMember(category.isPublic) && category.isActive);
if (this.activeCategory) {
this.activeSubCategory = this.activeCategory.subCategories.find(subCategory => this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive);
if (this.activeSubCategory) {
this.setSideBar();
this.setIndicators();
// } else {
// this.navigateToError();
}
// } else {
// this.navigateToError();
}
// } else {
// this.navigateToError();
}
}
}
private setSideBar() {
let items: MenuItem[] = [];
this.stakeholder.topics.forEach((topic) => {
if (this.isPublicOrIsMember(topic.isPublic) && topic.isActive) {
let topicItem: MenuItem = new MenuItem(topic.alias, topic.name, "", (
'/' + this.stakeholder.alias + '/' + topic.alias ),
null, [], [], {});
topicItem.icon = topic.icon;
items.push(topicItem);
}
});
let categoryItems: MenuItem[] = [];
this.activeTopic.categories.forEach((category, index) => {
if (this.isPublicOrIsMember(category.isPublic) && category.isActive) {
let subItems: MenuItem[] = [];
/*category.subCategories.forEach(subCategory => {
if (this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive) {
subItems.push(new MenuItem(subCategory.alias, subCategory.name, "", (
'/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias + '/' + subCategory.alias),
null, null, [], {}));
}
});*/
let open = this.activeCategory.alias === category.alias;
if (MonitorComponent.sidebarStatus && MonitorComponent.sidebarStatus.id === this.activeTopic.alias) {
open = MonitorComponent.sidebarStatus.status[index];
}
// constructor(id: string, title: string, url: string, route: string, needsAuthorization: boolean, entitiesRequired: string[], routeRequired: string[], params) {
let categoryItem: MenuItem = new MenuItem(category.alias, category.name, "", (
'/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias),
null, [], [], {});
categoryItem.items = subItems;
categoryItem.open = open;
categoryItems.push(categoryItem);
}
});
this.topBarItems = categoryItems;
if (items.length === 0) {
items.push(new MenuItem('noCategories', 'No categories available yet', "", "", false, [], [], {}));
}
this.sideBarItems = items;
this.loading = false;
}
private setIndicators() {
let urls: Map<string, [number, number][]> = new Map<string, [number, number][]>();
this.activeSubCategory.numbers.forEach((section, i) => {
section.indicators.forEach((number, j) => {
if (number.isActive && this.isPublicOrIsMember(number.isPublic)) {
let url = number.indicatorPaths[0].url;
//add fundingLevel0 filter in the query
if (this.fundingL0 && number.indicatorPaths[0].filters.get("fundingL0")) {
url = url + number.indicatorPaths[0].filters.get("fundingL0").replace(ChartHelper.prefix + 'fundingL0' + ChartHelper.suffix, encodeURIComponent(this.fundingL0));
}
const pair = JSON.stringify([number.indicatorPaths[0].source, url]);
const indexes = urls.get(pair) ? urls.get(pair) : [];
indexes.push([i, j]);
urls.set(pair, indexes);
}
});
});
urls.forEach((indexes, pair) => {
pair = JSON.parse(pair);
this.statisticsService.getNumbers(pair[0], IndicatorUtils.getNumberUrl(this.stakeholder, pair[1])).subscribe(response => {
indexes.forEach(([i, j]) => {
let result = JSON.parse(JSON.stringify(response));
this.activeSubCategory.numbers[i].indicators[j].indicatorPaths[0].jsonPath.forEach(jsonPath => {
if (result) {
result = result[jsonPath];
}
});
this.numberResults.set(i + '-' + j, result);
});
})
});
this.activeSubCategory.charts.forEach((section, i) => {
section.indicators.forEach((indicator, j) => {
if (indicator.indicatorPaths.length > 0) {
indicator.indicatorPaths[0].safeResourceUrl = this.getUrlByStakeHolder(indicator.indicatorPaths[0]);
this.chartsActiveType.set(i + '-' + j, indicator.indicatorPaths[0]);
}
});
});
if (this.cdr && !(this.cdr as ViewRef).destroyed) {
this.cdr.detectChanges();
}
}
public getUrlByStakeHolder(indicatorPath: IndicatorPath) {
return this.sanitizer.bypassSecurityTrustResourceUrl(
this.statisticsService.getChartUrl(indicatorPath.source, this.indicatorUtils.getFullUrl(this.stakeholder, indicatorPath, this.fundingL0, this.startYear, this.endYear)));
}
public setActiveChart(i: number, j: number, type: string) {
let activeChart = this.activeSubCategory.charts[i].indicators[j].indicatorPaths.filter(indicatorPath => indicatorPath.type === type)[0];
activeChart.safeResourceUrl = this.getUrlByStakeHolder(activeChart);
this.chartsActiveType.set(i + '-' + j, activeChart);
}
private navigateToError() {
this._router.navigate(['/error'], {queryParams: {'page': this._router.url}});
}
public navigateTo(stakeholder: string, topic: string, category: string = null, subcategory: string = null) {
let url = stakeholder + '/' + topic + ((category) ? ('/'
+ category) : '') + ((subcategory) ? ('/' + subcategory) : '');
return this._router.navigate([url]);
}
public quote(param: string): string {
return StringUtils.quote(param);
}
public ngOnDestroy() {
if (this.piwiksub) {
this.piwiksub.unsubscribe();
}
}
buildMenu() {
this.userMenuItems = [];
// if (Session.isPortalAdministrator(this.user)) {
// this.userMenuItems.push(new MenuItem("", "Manage helptexts",
// ((this.properties.environment == "beta") ? "https://beta.admin.connect.openaire.eu" : "https://admin.explore.openaire.eu") + "/dashboard?communityId=openaire", "", true, [], [], {}))
//
// }
if (this.user) {
this.userMenuItems.push(new MenuItem("", "Manage profiles", "", "/admin", false, [], [], {}));
}
if (this.user) {
this.userMenuItems.push(new MenuItem("", "User information", "", "/user-info", false, [], [], {}));
}
}
isAdmin(){
return this.user && (Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user) || Session.isMonitorCurator(this.user));
}
isLoggedIn() {
return this.user;
}
public isPublicOrIsMember(isPublic: boolean): boolean {
if (isPublic) {
return true;
} else {
if (this.isViewPublic) { // preview for not members
return false;
} else if(this.user) {
// if user is member, return true
return true;
}
return false;
}
}
}