[Monitor]: Stakeholder Page: Change number and charts base on source.

git-svn-id: https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/uoa-monitor-portal/trunk/monitor@57377 d315682c-612b-4755-9ff5-7f18f6832af3
This commit is contained in:
Konstantinos Triantafyllou 2019-10-15 13:50:44 +00:00
parent 99148dd7d2
commit bb9c0b9e3e
9 changed files with 92 additions and 684 deletions

View File

@ -20,7 +20,7 @@
<div class="uk-navbar-center">
<ul class="uk-navbar-nav">
<ng-template ngFor [ngForOf]="stakeholder.topics" let-topic let-i="index">
<li [ngClass]="(topic.alias === activeTopic.alias)?'uk-active':''">
<li *ngIf="topic.isPublic && topic.isActive" [ngClass]="(topic.alias === activeTopic.alias)?'uk-active':''">
<a (click)="navigateTo(stakeholder.alias, topic.alias)">{{topic.name}}</a>
</li>
</ng-template>
@ -31,7 +31,7 @@
</div>
<div uk-grid>
<sidebar [menuItems]="sideMenuItems" class="uk-width-1-5 sidebar"></sidebar>
<div *ngIf="activeSubCategory" class="uk-width-expand uk-padding">
<div *ngIf="activeSubCategory" class="uk-width-expand uk-padding uk-text-center@s uk-text-left@m">
<h5 class="uk-margin-bottom uk-text-bold">Indicators</h5>
<div class="uk-grid-medium uk-margin-bottom" uk-grid>
<div *ngFor="let number of activeSubCategory.numbers; let i=index;"
@ -50,8 +50,7 @@
<div *ngFor="let chart of activeSubCategory.charts; let i=index;"
[class.uk-width-1-3@m]="chart.width === 'small'"
[class.uk-width-1-2@m]="chart.width === 'medium'"
[class.uk-width-1-1@m]="chart.width === 'large'"
#element>
[class.uk-width-1-1@m]="chart.width === 'large'">
<div>
<h5>{{chart.name}}</h5>
<div class="uk-card uk-card-default uk-padding-small" [attr.uk-tooltip]="chart.description">
@ -59,13 +58,16 @@
<button *ngFor="let indicatorPath of chart.indicatorPaths;"
class="uk-button"
(click)="setActiveChart(i, indicatorPath.type)"
[class.uk-button-secondary]="chartsActiveType.get(i) === indicatorPath.url">
[class.uk-button-secondary]="chartsActiveType.get(i).url === indicatorPath.url">
{{indicatorPath.type}}
</button>
</div>
<iframe [src]="getUrlByStakeHolder(chartsActiveType.get(i))"
[width]="element.offsetWidth"
<iframe *ngIf="chartsActiveType.get(i).source !== 'fake'" [src]="getUrlByStakeHolder(chartsActiveType.get(i))"
class="uk-width-1-1"
height="600"></iframe>
<img *ngIf="chartsActiveType.get(i).source === 'fake'" [src]="getUrlByStakeHolder(chartsActiveType.get(i))"
class="uk-width-1-1"
height="600">
</div>
</div>
</div>

View File

@ -11,8 +11,9 @@ import {ErrorMessagesComponent} from '../openaireLibrary/utils/errorMessages.com
import {HelperService} from "../openaireLibrary/utils/helper/helper.service";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {StakeholderService} from "../services/stakeholder.service";
import {Category, Stakeholder, SubCategory, Topic} from "../utils/entities/stakeholder";
import {Category, IndicatorPath, Stakeholder, SubCategory, Topic} from "../utils/entities/stakeholder";
import {MenuItem, RootMenuItem, SideMenuItem} from "../openaireLibrary/sharedComponents/menu";
import {StatisticsService} from "../utils/services/statistics.service";
@Component({
selector: 'monitor',
@ -31,7 +32,7 @@ export class MonitorComponent {
public errorCodes: ErrorCodes;
public stakeholder: Stakeholder;
public numberResults: Map<number, number> = new Map<number, number>();
public chartsActiveType: Map<number, string> = new Map<number, string>();
public chartsActiveType: Map<number, IndicatorPath> = new Map<number, IndicatorPath>();
private errorMessages: ErrorMessagesComponent;
properties: EnvProperties;
@ -43,6 +44,7 @@ export class MonitorComponent {
private _piwikService: PiwikService,
private helper: HelperService,
private stakeholderService: StakeholderService,
private statisticsService: StatisticsService,
private seoService: SEOService,
private sanitizer: DomSanitizer) {
this.errorCodes = new ErrorCodes();
@ -53,10 +55,10 @@ export class MonitorComponent {
public ngOnInit() {
this.route.data
.subscribe((data: { envSpecific: EnvProperties }) => {
this.route.params.subscribe( params => {
this.route.params.subscribe(params => {
this.properties = data.envSpecific;
var url = data.envSpecific.baseLink + this._router.url;
if(!this.stakeholder || this.stakeholder.index_id !== params['stakeholder']) {
if (!this.stakeholder || this.stakeholder.index_id !== params['stakeholder']) {
this.status = this.errorCodes.LOADING;
this.stakeholderService.getStakeholder(params['stakeholder']).subscribe(stakeholder => {
this.stakeholder = stakeholder;
@ -98,10 +100,10 @@ export class MonitorComponent {
}
private setView(params: Params) {
if(params && params['topic']) {
if (params && params['topic']) {
this.activeTopic = this.stakeholder.topics.filter(topic => topic.alias === decodeURIComponent(params['topic']))[0];
if(this.activeTopic) {
if(params['category']) {
if (this.activeTopic) {
if (params['category']) {
this.activeCategory = this.activeTopic.categories.filter(category =>
category.alias === decodeURIComponent(params['category']))[0];
} else {
@ -109,14 +111,14 @@ export class MonitorComponent {
this.navigateTo(this.stakeholder.alias, this.activeTopic.alias, category.alias);
return;
}
if(this.activeCategory) {
if(params['subCategory']) {
if (this.activeCategory) {
if (params['subCategory']) {
this.activeSubCategory = this.activeCategory.subCategories.filter(subCategory =>
subCategory.alias = decodeURIComponent(params['subCategory']))[0];
} else {
this.activeSubCategory = this.activeCategory.subCategories.filter(subCategory => !subCategory.alias)[0];
}
if(this.activeSubCategory) {
if (this.activeSubCategory) {
this.setSideBar();
this.setIndicators();
return;
@ -126,7 +128,7 @@ export class MonitorComponent {
this.navigateToError();
} else {
let topic: Topic = this.stakeholder.topics[0];
let category: Category = topic.categories[0];
let category: Category = topic.categories.filter(category => category.isPublic && category.isActive)[0];
this.navigateTo(this.stakeholder.alias, topic.alias, category.alias);
}
}
@ -134,76 +136,62 @@ export class MonitorComponent {
private setSideBar() {
this.sideMenuItems = [];
this.activeTopic.categories.forEach(category => {
let rootItem: MenuItem = new MenuItem(category.alias, category.name, null, (
'/monitor/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias),
false, null, null, null);
let items: RootMenuItem[] = [];
category.subCategories.forEach(subCategory => {
if(subCategory.alias != null) {
items.push({
items: [],
rootItem: new MenuItem(subCategory.alias, subCategory.name, null, (
'/monitor/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias + '/' + subCategory.alias),
false, null, null, null)
});
}
});
this.sideMenuItems.push({
rootItem: rootItem,
items: items,
ukIcon: null
});
});
}
private setIndicators() {
let urls: Map<string, number[]> = new Map<string, number[]>();
this.activeSubCategory.numbers.forEach((number,index) => {
number.indicatorPaths.forEach( indicatorPath => {
if (!urls.get(indicatorPath.url)) {
urls.set(indicatorPath.url, [index]);
} else {
urls.get(indicatorPath.url).push(index);
}
});
});
urls.forEach( (indexes, url) => {
this.stakeholderService.getNumber(this.properties, url, this.stakeholder).subscribe( response => {
indexes.forEach(index => {
let result = JSON.parse(JSON.stringify(response));
this.activeSubCategory.numbers[index].indicatorPaths[0].jsonPath.forEach( jsonPath => {
result = result[jsonPath];
});
this.numberResults.set(index, result);
if (category.isPublic && category.isActive) {
let rootItem: MenuItem = new MenuItem(category.alias, category.name, null, (
'/monitor/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias),
false, null, null, null);
let items: RootMenuItem[] = [];
category.subCategories.forEach(subCategory => {
if (subCategory.alias != null && subCategory.isPublic && subCategory.isActive) {
items.push({
items: [],
rootItem: new MenuItem(subCategory.alias, subCategory.name, null, (
'/monitor/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias + '/' + subCategory.alias),
false, null, null, null)
});
}
});
this.sideMenuItems.push({
rootItem: rootItem,
items: items,
ukIcon: null
});
});
});
this.activeSubCategory.charts.forEach((chart, index) => {
if(chart.indicatorPaths.length > 0) {
this.chartsActiveType.set(index, chart.indicatorPaths[0].url);
}
});
}
public getUrlByStakeHolder(url: string) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url.replace('{index_shortName}', this.stakeholder.index_shortName).
replace('{index_id}', this.stakeholder.index_id).
replace('{index_name}', this.stakeholder.index_name));
private setIndicators() {
this.activeSubCategory.numbers.forEach((number, index) => {
this.statisticsService.getNumbers(number.indicatorPaths[0].source, number.indicatorPaths[0].url).subscribe(response => {
number.indicatorPaths[0].jsonPath.forEach(jsonPath => {
response = response[jsonPath];
});
this.numberResults.set(index, response);
});
});
this.activeSubCategory.charts.forEach((chart, index) => {
if (chart.indicatorPaths.length > 0) {
this.chartsActiveType.set(index, chart.indicatorPaths[0]);
}
});
}
public getUrlByStakeHolder(indicatorPath: IndicatorPath) {
return this.sanitizer.
bypassSecurityTrustResourceUrl(this.statisticsService.getChartUrl(indicatorPath.source, indicatorPath.url));
}
public setActiveChart(index, type: string) {
let url = this.activeSubCategory.charts[index].indicatorPaths.
filter(indicatorPath => indicatorPath.type === type)[0].url;
this.chartsActiveType.set(index, url);
this.chartsActiveType.set(index, this.activeSubCategory.charts[index].indicatorPaths.filter(indicatorPath => indicatorPath.type === type)[0]);
}
private navigateToError() {
this._router.navigate(['/error'],{queryParams: {'page': this._router.url}});
this._router.navigate(['/error'], {queryParams: {'page': this._router.url}});
}
public navigateTo(stakeholder: string, topic: string, category: string = null, subcategory: string = null) {
let url = 'monitor/' + stakeholder+ '/' + topic + ((category)?('/'
+ category):'') + ((subcategory)?('/' + subcategory):'');
let url = 'monitor/' + stakeholder + '/' + topic + ((category) ? ('/'
+ category) : '') + ((subcategory) ? ('/' + subcategory) : '');
return this._router.navigate([url]);
}

View File

@ -15,6 +15,7 @@ import {MonitorRoutingModule} from "./monitor-routing.module";
import {MonitorComponent} from "./monitor.component";
import {StakeholderService} from "../services/stakeholder.service";
import {SideBarModule} from "../openaireLibrary/sharedComponents/sidebar/sideBar.module";
import {StatisticsService} from "../utils/services/statistics.service";
@NgModule({
imports: [
@ -26,7 +27,8 @@ import {SideBarModule} from "../openaireLibrary/sharedComponents/sidebar/sideBar
],
providers: [
FreeGuard, PreviousRouteRecorder,
PiwikService, StakeholderService
PiwikService, StakeholderService,
StatisticsService
],
exports: [
MonitorComponent

View File

@ -1,9 +1,8 @@
import {Injectable} from "@angular/core";
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {Observable} from "rxjs";
import {HttpClient} from "@angular/common/http";
import {BehaviorSubject, Observable} from "rxjs";
import {Indicator, Stakeholder} from "../utils/entities/stakeholder";
import {map} from "rxjs/operators";
import {EnvProperties} from "../openaireLibrary/utils/properties/env-properties";
@Injectable()
export class StakeholderService {
@ -12,7 +11,7 @@ export class StakeholderService {
}
getStakeholder(alias: string): Observable<Stakeholder> {
return this.http.get<any>('./assets/stakeholders.json').pipe(map(json => {
/*return this.http.get<any>('./assets/stakeholders.json').pipe(map(json => {
let stakeholder = json.stakeholders.filter(stakeholder => stakeholder.alias === alias)[0];
if (stakeholder) {
stakeholder.topics = stakeholder.topics.filter(topic => topic.isActive && topic.isPublic);
@ -25,25 +24,7 @@ export class StakeholderService {
}
})
}
}));
}
getIndicator(id: string): Observable<Indicator> {
return this.http.get<any>('./assets/stakeholders.json').pipe(map(json => {
return json.indicators.filter(indicator => indicator.id === id)[0];
}))
}
getIndicators(ids: string[]): Observable<Indicator[]> {
return this.http.get<any>('./assets/stakeholders.json').pipe(map(json => {
return json.indicators.filter(indicator => ids.indexOf(indicator.id) !== -1);
}))
}
getNumber(properties: EnvProperties, url: string, stakeholder: Stakeholder): Observable<any> {
const statsUrl = url.replace('{index_shortName}', stakeholder.index_shortName).
replace('{index_id}', stakeholder.index_id).
replace('{index_name}', stakeholder.index_name);
return this.http.get<any>(properties.statisticsAPIURL + statsUrl);
}));*/
return new BehaviorSubject<Stakeholder>(Stakeholder.createECStakeholder()).asObservable();
}
}

View File

@ -1,17 +0,0 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import{StatisticsComponent} from './statistics.component';
import {FreeGuard} from '../openaireLibrary/login/freeGuard.guard';
import {PreviousRouteRecorder} from '../openaireLibrary/utils/piwik/previousRouteRecorder.guard';
// import {IsRouteEnabled} from '../openaireLibrary/error/isRouteEnabled.guard'
@NgModule({
imports: [
RouterModule.forChild([
{ path: '', component: StatisticsComponent, canActivate: [FreeGuard], canDeactivate: [PreviousRouteRecorder] }
])
]
})
export class StatisticsRoutingModule { }

View File

@ -1,192 +0,0 @@
<div class=" uk-section uk-margin-small-top tm-middle uk-container" id="tm-main">
<div class="uk-container uk-margin-bottom">
<article class="uk-article ">
<div *ngIf="status == errorCodes.LOADING" class="uk-animation-fade uk-width-1-1" role="alert"><span class="loading-gif uk-align-center"></span></div>
<div *ngIf="status == errorCodes.ERROR" class="uk-alert uk-alert-warning" style="margin-top:40px; padding-left:40px;">
An error occured
</div>
<div *ngIf=" (status == errorCodes.DONE) && (!statisticsSum || !statisticsDisplay || ((statisticsSum.total_projects==0) && (allowedEntities.length == 0)))" class="uk-alert uk-alert-info" style="margin-top:40px; padding-left:40px;">
No statistics are available for {{ communityId.toUpperCase() }}
</div>
<div *ngIf="statisticsSum && (statisticsSum.total_projects>0) && statisticsDisplay" class="uk-margin uk-margin-top">
<div class="uk-grid">
<div class="uk-width-1-6@m uk-visible@m uk-margin-top">
<div uk-sticky="offset: 120">
<ul class="uk-tab uk-tab-left" uk-tab="connect:#tabs">
<!-- <ul class="uk-tab uk-tab-left uk-width-1-6 uk-margin-top" data-uk-tab="{connect:'#tabs'}"> -->
<li *ngFor="let entity of allowedEntities"
(click)="onChangeEntity(entity)" [class]="displayedEntity == entity?'uk-active':''">
<a href="#">{{ entitiesMap.get(entity) }}</a>
</li>
</ul>
</div>
</div>
<div class="uk-hidden@m uk-clearfix uk-width-1-1 uk-margin-bottom">
<button class="uk-button uk-button-default uk-hidden@m " type="button">
<span uk-navbar-toggle-icon></span> <span class="uk-margin-small-left">{{entitiesMap.get(displayedEntity)}}</span>
</button>
<ul id="toggle-small-tabs" class="uk-subnav uk-subnav-pill uk-dropdown uk-hidden@m uk-margin-top"
uk-switcher="connect:#tabs; animation: uk-animation-fade"
uk-dropdown="mode: click" uk-toggle="target: #toggle-small-tabs">
<li *ngFor="let entity of allowedEntities"
(click)="onChangeEntity(entity)" [class]="displayedEntity == entity?'uk-active':''">
<a>{{ entitiesMap.get(entity) }}</a>
</li>
</ul>
</div>
<ul id="tabs" class="uk-switcher uk-margin uk-width-expand" style="min-height:450px; padding-left:40px;">
<li *ngFor="let entity of allowedEntities" [class]="displayedEntity == entity?'uk-active':''">
<div *ngIf="(displayedEntity == entity) && statisticsSum[entity]">
<div class="uk-text-uppercase uk-text-bold uk-heading-divider">
<h2>{{ entitiesMap.get(entity) }} statistics</h2>
<div *ngIf="!statisticsSum[entity] ||
!statisticsDisplay.entities[entity] ||
statisticsSum[entity].total==0"
class="uk-alert uk-alert-info">
No {{ entitiesMap.get(entity) }} statistics available
</div>
<div *ngIf="statisticsDisplay.entities[entity] && statisticsSum[entity].total>0">
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['total'][currentMode]">
{{statisticsSum[entity].total|number}} {{ entity + ( (entity == 'software' || statisticsSum[entity].total == 1) ? '' : 's') }}
</span>
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['project'][currentMode] &&
statisticsSum[entity].projects>0">
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['total'][currentMode]">
linked to
</span>
{{statisticsSum[entity].projects|number}} project{{ statisticsSum[entity].projects == 1 ? '' : 's' }}.
</span><br>
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['open'][currentMode] &&
statisticsSum[entity].open_access>0">
{{statisticsSum[entity].open_access|number}}
{{statisticsSum[entity].open_access == 1 ? 'is' : 'are'}} OA
</span>
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['closed'][currentMode] &&
statisticsSum[entity].closed_access>0">
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['open'][currentMode]">
,
</span>
{{statisticsSum[entity].closed_access|number}}
{{statisticsSum[entity].closed_access == 1 ? 'is' : 'are'}} closed
</span>
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['restricted'][currentMode] &&
statisticsSum[entity].restricted>0">
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['open'][currentMode] ||
statisticsDisplay.entities[entity].numbers.map['closed'][currentMode]">
,
</span>
{{statisticsSum[entity].restricted|number}}
{{statisticsSum[entity].restricted == 1 ? 'is' : 'are'}} restricted
</span>
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['embargo'][currentMode] &&
statisticsSum[entity].embargo>0">
<span *ngIf="statisticsDisplay.entities[entity].numbers.map['open'][currentMode] ||
statisticsDisplay.entities[entity].numbers.map['closed'][currentMode] ||
statisticsDisplay.entities[entity].numbers.map['restricted'][currentMode]">
and
</span>
{{statisticsSum[entity].embargo|number}}
{{statisticsSum[entity].embargo == 1 ? 'is' : 'are'}} still in embargo.
</span>
</div>
</div>
<div *ngIf="statisticsSum[entity].total>0 && allowedCharts[entity].length==0"
class="uk-alert uk-alert-info">
No charts available
</div>
<div *ngIf="statisticsSum[entity].total>0 && allowedCharts[entity].length>0">
<div class="uk-grid">
<div *ngIf="statisticsDisplay.entities[entity].charts.map['timeline'] &&
statisticsDisplay.entities[entity].charts.map['timeline'][currentMode] &&
chartsInfoMap[entity + 'Timeline'] &&
(displayedTimeline == (entity + 'Timeline'))">
<iframe [src]=displayedTimelineUrl width="1000" height="450"></iframe>
</div>
<div *ngIf="statisticsDisplay.entities[entity].charts.map['graph'] &&
statisticsDisplay.entities[entity].charts.map['graph'][currentMode] &&
chartsInfoMap[entity + 'Graph'] &&
(displayedGraph == (entity + 'Graph'))">
<iframe [src]=displayedGraphUrl width="1000" height="450"></iframe>
</div>
</div>
<hr *ngIf="(statisticsDisplay.entities[entity].charts.map['timeline'] &&
statisticsDisplay.entities[entity].charts.map['timeline'][currentMode] &&
chartsInfoMap[entity + 'Timeline'] &&
(displayedTimeline == (entity + 'Timeline'))) || (statisticsDisplay.entities[entity].charts.map['graph'] &&
statisticsDisplay.entities[entity].charts.map['graph'][currentMode] &&
chartsInfoMap[entity + 'Graph'] &&
(displayedGraph == (entity + 'Graph')))">
<div *ngIf="statisticsDisplay.entities[entity].charts.map['projectColumn'][currentMode] ||
statisticsDisplay.entities[entity].charts.map['projectPie'][currentMode] ||
statisticsDisplay.entities[entity].charts.map['projectTable'][currentMode]">
<div>
<h4 class="uk-text-uppercase uk-text-bold">{{ entitiesMap.get(entity) }} per project</h4>
</div>
<div>
<ul class="uk-tab uk-margin-top" data-uk-tab="{connect: '#projectChartTabs'">
<li *ngIf=" statisticsDisplay.entities[entity].charts.map['projectColumn'] &&
statisticsDisplay.entities[entity].charts.map['projectColumn'][currentMode] &&
chartsInfoMap[entity + 'Projectcolumn']"
(click)="changeDisplayedProjectChart(entity + 'Projectcolumn')">
<a href="#">Columns</a>
</li>
<li *ngIf=" statisticsDisplay.entities[entity].charts.map['projectPie'] &&
statisticsDisplay.entities[entity].charts.map['projectPie'][currentMode] &&
chartsInfoMap[entity + 'Projectpie']"
(click)="changeDisplayedProjectChart(entity + 'Projectpie')">
<a href="#">Pie</a>
</li>
<li *ngIf=" statisticsDisplay.entities[entity].charts.map['projectTable'] &&
statisticsDisplay.entities[entity].charts.map['projectTable'][currentMode] &&
chartsInfoMap[entity + 'Projecttable']"
(click)="changeDisplayedProjectChart(entity + 'Projecttable')">
<a href="#">Table</a>
</li>
</ul>
<ul id="projectChartTabs" class="uk-switcher uk-margin">
<li *ngIf="statisticsDisplay.entities[entity].charts.map['projectColumn'][currentMode]">
<div *ngIf="displayedProjectChart == (entity + 'Projectcolumn')">
<iframe [src]=displayedProjectChartUrl width="1000" height="450"></iframe>
</div>
</li>
<li *ngIf="statisticsDisplay.entities[entity].charts.map['projectPie'][currentMode]">
<div *ngIf="displayedProjectChart == (entity + 'Projectpie')">
<iframe [src]=displayedProjectChartUrl width="1000" height="450"></iframe>
</div>
</li>
<li *ngIf="statisticsDisplay.entities[entity].charts.map['projectTable'][currentMode]">
<div *ngIf="displayedProjectChart == (entity + 'Projecttable')">
<iframe [src]=displayedProjectChartUrl width="1000" height="450"></iframe>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</article>
</div>
</div>

View File

@ -1,314 +0,0 @@
import {Component, Input} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Location, TitleCasePipe} from '@angular/common';
import {Title, Meta} from '@angular/platform-browser';
import {DomSanitizer} from '@angular/platform-browser';
import "rxjs/add/observable/zip";
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {ErrorCodes} from '../openaireLibrary/utils/properties/errorCodes';
import {StatisticsService} from '../utils/services/statistics.service';
import {ConfigurationService} from '../openaireLibrary/utils/configuration/configuration.service';
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {ConnectHelper} from '../openaireLibrary/connect/connectHelper';
import {
availableCharts, availableEntitiesMap, StatisticsDisplay,
StatisticsSummary
} from "../openaireLibrary/connect/statistics/statisticsEntities";
import {PiwikHelper} from '../utils/piwikHelper';
import {CommunityCharts} from "../openaireLibrary/connect/statistics/communityCharts";
import {HelperFunctions} from "../openaireLibrary/utils/HelperFunctions.class";
import {CommunityService} from "../openaireLibrary/connect/community/community.service";
@Component({
selector: 'statistics',
templateUrl: 'statistics.component.html',
})
export class StatisticsComponent {
public piwiksub: any;
public pageTitle = "OpenAIRE";
properties: EnvProperties;
@Input() communityId = null;
@Input() currentMode = 'showInMonitor';
communityInfo: any = null;
entitiesList: string[] = [];
entitiesMap: Map<string, string> = availableEntitiesMap;
chartCatsList: string[] = availableCharts;
allowedCharts: Map<string, string[]> = new Map<string, string[]>();
allowedEntities: string[] = [];
allowedChartsMode = {showInMonitor: new Map<string, string[]>(), showInDashboard: new Map<string, string[]>()};
allowedEntitiesMode = {showInMonitor: [], showInDashboard: []};
statisticsSum: StatisticsSummary = null;
statisticsDisplay: StatisticsDisplay = null;
chartTitlesMode = {showInMonitor: {}, showInDashboard: {}};
chartsInfoMap: {};
displayedTimeline: string;
displayedTimelineUrl: string;
displayedGraph: string;
displayedGraphUrl: string;
displayedProjectChart: string;
displayedProjectChartUrl: string;
displayedEntity: string;
public errorCodes: ErrorCodes = new ErrorCodes();
status = null;
communityName = null;
constructor(
private route: ActivatedRoute,
private _router: Router,
private location: Location,
private _meta: Meta,
private _title: Title,
private _piwikService: PiwikService,
private _statisticsService: StatisticsService,
private _configService: ConfigurationService,
private titleCase: TitleCasePipe,
private _communityService: CommunityService,
private sanitizer: DomSanitizer) {
}
public ngOnInit() {
if (this.currentMode == "showInMonitor") {
var description = "open access, research, scientific publication, European Commission, EC, FP7, ERC, Horizon 2020, H2020, search, projects ";
var title = "Monitor";
this._title.setTitle(title);
this._meta.updateTag({content: description}, "name='description'");
this._meta.updateTag({content: description}, "property='og:description'");
this._meta.updateTag({content: title}, "property='og:title'");
}
this.route.data
.subscribe((data: { envSpecific: EnvProperties }) => {
this.properties = data.envSpecific;
var url = data.envSpecific.baseLink + this._router.url;
this._meta.updateTag({content: url}, "property='og:url'");
this.route.queryParams.subscribe(
communityId => {
this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain);
if(!this.communityId) {
this.communityId = communityId['communityId'];
}
if (this.currentMode == "showInMonitor" && this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
this.piwiksub = this._piwikService.trackView(this.properties, "Monitor " + this.communityId, PiwikHelper.siteIDs[this.communityId]).subscribe();
}
this._communityService.getCommunity(this.properties, this.properties.communityAPI + this.communityId).subscribe(
community => {
if (typeof document !== 'undefined') {
HelperFunctions.scroll();
}
this.communityName = community.shortTitle;
this.createStatisticsObjects();
});
// console.log(" Stats! "+ this.properties.statisticsAPIURL);
});
});
}
public ngOnDestroy() {
if (this.piwiksub) {
this.piwiksub.unsubscribe();
}
}
getCamelCaseString(inputString: string) {
return this.titleCase.transform(inputString);
}
createStatisticsObjects() {
// console.log(" Stats! "+ this.properties.statisticsAPIURL);
this.status = this.errorCodes.LOADING;
this._statisticsService.getCommunityStatistics(this.properties, this.communityId).subscribe(
res => {
this.statisticsSum = res;
if (res["other"]) { //hack because in stats API the entity name is "other" while in admin API is "orp". This component uses also "orp" name
this.statisticsSum["orp"] = res["other"];
}
this.getDisplayOptions();
},
error => {
//console.log(error);
this.handleError("Error getting community statistics for community with id: " + this.communityId, error);
this.status = this.errorCodes.ERROR;
});
}
getDisplayOptions() {
this._statisticsService.getCommunityAdminStatisticsChoices(this.properties, this.communityId)
.subscribe(
res => {
this.statisticsDisplay = res;
this.createChartUrlMap();
this.getCommunityInfo();
this.status = this.errorCodes.DONE;
},
error => {
//console.log(error);
this.handleError("Error getting community statistics choices by administrators for community with id: " + this.communityId, error);
this.status = this.errorCodes.ERROR;
}
);
}
getCommunityInfo() {
// console.log(`calling ${this.properties.adminToolsAPIURL}/communityFull/${this.communityId}`);
this._configService.getCommunityInformation(this.properties, this.communityId).subscribe(
res => {
this.communityInfo = res;
/*for(let i=0; i<this.communityInfo.entities.length; i++){
if (this.communityInfo.entities[i]["isEnabled"] ) {
this.entitiesList.push(this.communityInfo.entities[i]['pid']);
}
}
console.log(this.entitiesList);*/
},
error => {
//console.log(error)
this.handleError("Error getting community with id: " + this.communityId, error);
},
() => this.initializeDisplayedCharts()
);
}
initializeDisplayedCharts() {
let firstEntity: string;
this.entitiesList = Array.from(this.entitiesMap.keys());
this.allowedChartsMode[this.currentMode] = this.allowedCharts;
this.allowedEntitiesMode[this.currentMode] = this.allowedEntities;
let titles = [];
// console.log('this.entitiesList is',this.entitiesList);
// console.log(`my current mode is: ${this.currentMode}`);
for (let entity of this.entitiesList) {
if (this.statisticsDisplay.entities[entity] && this.statisticsSum[entity].total && this.communityInfo.entities.filter(x => x['pid'] == entity && x['isEnabled'] === true).length) {
this.allowedChartsMode.showInDashboard[entity] = [];
this.allowedChartsMode.showInMonitor[entity] = [];
for (let chart of this.chartCatsList) {
if (this.statisticsSum[entity].total &&
this.statisticsDisplay.entities[entity].charts.map[chart] &&
this.statisticsDisplay.entities[entity].charts.map[chart]["showInDashboard"] &&
this.chartsInfoMap[entity + this.getCamelCaseString(chart)].url) {
this.allowedChartsMode.showInDashboard[entity].push(entity + this.getCamelCaseString(chart));
if (titles.indexOf("dashboard" + this.chartsInfoMap[entity + this.getCamelCaseString(chart)].title) == -1) {
titles.push("dashboard" + this.chartsInfoMap[entity + this.getCamelCaseString(chart)].title);
this.chartTitlesMode.showInDashboard[entity + this.getCamelCaseString(chart)] = true;
} else {
this.chartTitlesMode.showInDashboard[entity + this.getCamelCaseString(chart)] = false;
}
// console.log(`added ${entity} - ${chart} to allowedCharts`);
}
if (this.statisticsSum[entity].total &&
this.statisticsDisplay.entities[entity].charts.map[chart] &&
this.statisticsDisplay.entities[entity].charts.map[chart]["showInMonitor"] &&
this.chartsInfoMap[entity + this.getCamelCaseString(chart)].url) {
this.allowedChartsMode.showInMonitor[entity].push(entity + this.getCamelCaseString(chart));
if (titles.indexOf("monitor" + this.chartsInfoMap[entity + this.getCamelCaseString(chart)].title) == -1) {
titles.push("monitor" + this.chartsInfoMap[entity + this.getCamelCaseString(chart)].title);
this.chartTitlesMode.showInMonitor[entity + this.getCamelCaseString(chart)] = true;
} else {
this.chartTitlesMode.showInMonitor[entity + this.getCamelCaseString(chart)] = false;
}
// console.log(`added ${entity} - ${chart} to allowedCharts`);
}
}
if (this.allowedChartsMode.showInMonitor[entity].length) {
// console.log(`added ${entity} to allowedEntities`);
this.allowedEntitiesMode.showInMonitor.push(entity);
if (!firstEntity) {
firstEntity = entity;
this.onChangeEntity(entity);
}
}
if (this.allowedChartsMode.showInDashboard[entity].length) {
// console.log(`added ${entity} to allowedEntities`);
this.allowedEntitiesMode.showInDashboard.push(entity);
if (!firstEntity) {
firstEntity = entity;
this.onChangeEntity(entity);
}
}
}
}
}
createChartUrlMap() {
let communityCharts: CommunityCharts = new CommunityCharts(this.sanitizer);
this.chartsInfoMap = communityCharts.getChartsForCommunity(this.communityId, this.communityName, this.properties);
}
onChangeEntity(entity: string) {
this.displayedEntity = entity;
// console.log(`displayed entity is ${entity}`);
// console.log(`statisticsSum[${entity}].total is ${this.statisticsSum[entity].total}`);
if (this.statisticsSum[entity].total &&
this.allowedEntities.filter(x => x == entity).length) {
// console.log(`found ${entity} in allowedEntities`);
this.displayedTimeline = `${entity}Timeline`;
this.displayedTimelineUrl = this.chartsInfoMap[this.displayedTimeline].url;
// console.log(`displayed Timeline is: ${this.displayedTimeline}`);
this.displayedGraph = `${entity}Graph`;
this.displayedGraphUrl = this.chartsInfoMap[this.displayedGraph].url;
// console.log(`displayed Graph is: ${this.displayedGraph}`);
if (this.allowedCharts[entity]) {
let firstProjectChart = this.allowedCharts[entity].filter(x => x.includes(entity + 'Project'));
if (firstProjectChart[0]) {
this.changeDisplayedProjectChart(firstProjectChart[0]);
} else {
this.displayedProjectChart = '';
this.displayedProjectChartUrl = '';
// console.log(`displayed ProjectChart is: ${this.displayedProjectChart}`);
}
}
} else {
this.displayedTimeline = '';
this.displayedTimelineUrl = '';
// console.log(`displayed Timeline is: ${this.displayedTimeline}`);
this.displayedGraph = '';
this.displayedGraphUrl = '';
// console.log(`displayed Graph is: ${this.displayedGraph}`);
}
}
changeDisplayedProjectChart(chartName: string) {
this.displayedProjectChart = chartName;
this.displayedProjectChartUrl = this.chartsInfoMap[this.displayedProjectChart].url;
// console.log(`displayed ProjectChart is: ${this.displayedProjectChart}`);
}
private handleError(message: string, error) {
console.error("Statistics (Monitor) Page: " + message, error);
}
}
@Component({
selector: 'statistics-for-dashboard',
template: ''
// templateUrl: 'statistics-for-dashboard.component.html',
})
export class StatisticsForDashboardComponent extends StatisticsComponent {
ngOnInit() {
super.ngOnInit();
}
}

View File

@ -1,35 +0,0 @@
import {NgModule} from '@angular/core';
import {CommonModule, TitleCasePipe} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {RouterModule} from '@angular/router';
import {StatisticsRoutingModule} from './statistics-routing.module';
import {IFrameModule} from '../openaireLibrary/utils/iframe.module';
import {StatisticsComponent, StatisticsForDashboardComponent} from './statistics.component';
import {StatisticsService} from '../utils/services/statistics.service';
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {FreeGuard} from '../openaireLibrary/login/freeGuard.guard';
import {PreviousRouteRecorder} from '../openaireLibrary/utils/piwik/previousRouteRecorder.guard';
import {IsRouteEnabled} from '../openaireLibrary/error/isRouteEnabled.guard'
@NgModule({
imports: [
CommonModule, FormsModule, RouterModule,
StatisticsRoutingModule, IFrameModule
],
declarations: [
StatisticsComponent,
StatisticsForDashboardComponent
],
providers: [
IsRouteEnabled, FreeGuard, PreviousRouteRecorder,
PiwikService, StatisticsService, TitleCasePipe
],
exports: [
StatisticsForDashboardComponent
]
})
export class StatisticsModule { }

View File

@ -1,39 +1,32 @@
import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import { Observable } from 'rxjs/Rx';
import {StatisticsDisplay, StatisticsSummary} from "../../openaireLibrary/connect/statistics/statisticsEntities";
import {catchError, map} from "rxjs/operators";
import {throwError} from "rxjs";
import {EnvProperties} from "../../openaireLibrary/utils/properties/env-properties";
import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {EnvironmentSpecificService} from "../../openaireLibrary/utils/properties/environment-specific.service";
import {Observable} from "rxjs";
@Injectable()
export class StatisticsService {
numberSources: Map<string, string> = new Map<string, string>();
chartSources: Map<string, string> = new Map<string, string>();
constructor(private http:HttpClient) { }
getCommunityStatistics(properties:EnvProperties, communityId: string): Observable<StatisticsSummary> {
let url = properties.statisticsAPIURL+"/communities/"+communityId;
//console.log(`getting statistics summary from: ${url}`);
return this.http.get<any>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
//.map(res => <any>res.json())
.pipe(map(res => res['statistics']));
constructor(private http:HttpClient, private environmentSpecificService: EnvironmentSpecificService) {
this.environmentSpecificService.subscribeEnvironment().subscribe(properties => {
this.numberSources.set('statistics', properties.statisticsAPIURL);
this.numberSources.set('search', properties.searchAPIURLLAst);
this.numberSources.set('metrics', properties.metricsAPIURL);
this.chartSources.set('stats-tool', properties.statisticsFrameNewAPIURL);
this.chartSources.set('old', properties.statisticsFrameAPIURL);
this.chartSources.set('metrics', properties.metricsAPIURL);
this.chartSources.set('fake', '');
})
}
getCommunityAdminStatisticsChoices(properties: EnvProperties, communityId: string): Observable<StatisticsDisplay> {
let url = properties.adminToolsAPIURL+"/statistics/"+communityId;
//console.log(`getting admin choices for statistics from: ${url}`);
return this.http.get<StatisticsDisplay>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
//.map(stats => <StatisticsDisplay>stats.json())
.pipe(catchError(this.handleError));
getNumbers(source: string, url: string): Observable<any> {
return this.http.get<any>(this.numberSources.get(source) + url);
}
private handleError (error: HttpErrorResponse) {
// in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console
console.log(error);
return throwError(error || 'Server error');
getChartUrl(source: string, url: string): string {
return this.chartSources.get(source) + url;
}
}