Project

General

Profile

1
import {ChangeDetectorRef, Component, OnDestroy, OnInit} from '@angular/core';
2
import {ActivatedRoute, Params, Router} from '@angular/router';
3
import {DomSanitizer, Meta, Title} from '@angular/platform-browser';
4
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
5

    
6
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
7
import {StringUtils} from '../openaireLibrary/utils/string-utils.class';
8

    
9
import {ErrorCodes} from '../openaireLibrary/utils/properties/errorCodes';
10
import {ErrorMessagesComponent} from '../openaireLibrary/utils/errorMessages.component';
11
import {HelperService} from "../openaireLibrary/utils/helper/helper.service";
12
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
13
import {StakeholderService} from "../services/stakeholder.service";
14
import {Category, ChartHelper, IndicatorPath, Stakeholder, SubCategory, Topic} from "../utils/entities/stakeholder";
15
import {StatisticsService} from "../utils/services/statistics.service";
16
import {Item, Sidebar} from "../utils/entities/sidebar";
17
import {IndicatorUtils} from "../utils/indicator-utils";
18
import {StakeholderCreator} from "../utils/entities/stakeholderCreator";
19
import {LayoutService} from "../library/sharedComponents/sidebar/layout.service";
20

    
21
@Component({
22
  selector: 'monitor',
23
  templateUrl: 'monitor.component.html',
24
})
25
export class MonitorComponent implements OnInit, OnDestroy {
26
  public piwiksub: any;
27
  public pageContents = null;
28
  public divContents = null;
29
  public status: number;
30
  public loading: boolean = true;
31
  public indicatorUtils: IndicatorUtils = new IndicatorUtils();
32
  public activeTopic: Topic = null;
33
  public activeCategory: Category = null;
34
  public activeSubCategory: SubCategory = null;
35
  public sideBar: Sidebar = null;
36
  public errorCodes: ErrorCodes;
37
  public stakeholder: Stakeholder;
38
  public numberResults: Map<number, number> = new Map<number, number>();
39
  public chartsActiveType: Map<number, IndicatorPath> = new Map<number, IndicatorPath>();
40
  private errorMessages: ErrorMessagesComponent;
41
  properties: EnvProperties;
42
  fundingL0;
43
  startYear;
44
  endYear;
45

    
46
  constructor(
47
    private route: ActivatedRoute,
48
    private _router: Router,
49
    private _meta: Meta,
50
    private _title: Title,
51
    private _piwikService: PiwikService,
52
    private helper: HelperService,
53
    private stakeholderService: StakeholderService,
54
    private statisticsService: StatisticsService,
55
    private layoutService: LayoutService,
56
    private seoService: SEOService,
57
    private cdr: ChangeDetectorRef,
58
    private sanitizer: DomSanitizer) {
59
      this.errorCodes = new ErrorCodes();
60
      this.errorMessages = new ErrorMessagesComponent();
61
      this.status = this.errorCodes.LOADING;
62
  }
63

    
64
  public ngOnInit() {
65
    this.layoutService.setHasSidebar(false);
66
    this.layoutService.setHasHeader(false);
67
    this.route.data
68
      .subscribe((data: { envSpecific: EnvProperties }) => {
69
        this.route.params.subscribe(params => {
70
          this.properties = data.envSpecific;
71
          var url = data.envSpecific.baseLink + this._router.url;
72
          if (!this.stakeholder || this.stakeholder.index_id !== params['stakeholder']) {
73
            this.status = this.errorCodes.LOADING;
74
            this.numberResults = new Map<number, number>();
75
            this.chartsActiveType = new Map<number, IndicatorPath>();
76
            // this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
77
            let stakeholder:Stakeholder = null;
78
            if(params['stakeholder']=="fwf"){
79
              stakeholder = StakeholderCreator.createFunderFromDefaultProfile("fwf","funder","fwf_________::FWF",
80
                "Austrian Science Fund (FWF)","FWF",
81
                false,"fwf",true,true, null);
82
              stakeholder.logoUrl = "./assets/fwf.png";
83
            }else if(params['stakeholder']=="arc"){
84
              stakeholder = StakeholderCreator.createFunderFromDefaultProfile("arc","funder","arc_________::ARC",
85
                "Australian Research Council (ARC)","ARC",
86
                false,"arc",true,true, null);
87
                stakeholder.logoUrl = "./assets/arc1.gif";
88
            }else{
89
              stakeholder = StakeholderCreator.createFunderFromDefaultProfile("ec","funder","ec__________::EC",
90
                "European Commission","EC",
91
                false,"ec",true,true, null);
92
              stakeholder.logoUrl = "./assets/ec.png";
93
            }
94

    
95
              if(stakeholder) {
96
                this.stakeholder = stakeholder;
97
                this.seoService.createLinkForCanonicalURL(url, false);
98
                this._meta.updateTag({content: url}, "property='og:url'");
99
                var description = "Monitor Dashboard | " + this.stakeholder.index_name;
100
                var title = "Monitor Dashboard | " + this.stakeholder.index_shortName;
101
                this._meta.updateTag({content: description}, "name='description'");
102
                this._meta.updateTag({content: description}, "property='og:description'");
103
                this._meta.updateTag({content: title}, "property='og:title'");
104
                this._title.setTitle(title);
105
                if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
106
                  this.piwiksub = this._piwikService.trackView(this.properties, title, this.properties.piwikSiteId).subscribe();
107
                }
108
                //this.getDivContents();
109
                this.getPageContents();
110
                this.status = this.errorCodes.DONE;
111
                this.setView(params);
112
              }
113
            // }, error => {
114
            //   this.navigateToError();
115
            // })
116
          } else {
117
            this.setView(params);
118
          }
119
        });
120
      });
121
  }
122

    
123
  public get open() {
124
    return this.layoutService.open;
125
  }
126

    
127
  public toggleOpen(event = null) {
128
    if(!event) {
129
      this.layoutService.setOpen(!this.open);
130
    } else if(event && event['value'] === true) {
131
      this.layoutService.setOpen(false);
132
    }
133
  }
134

    
135
  private getPageContents() {
136
    this.helper.getPageHelpContents(this._router.url, this.properties, 'monitor').subscribe(contents => {
137
      this.pageContents = contents;
138
    })
139
  }
140

    
141
  private getDivContents() {
142
    this.helper.getDivHelpContents(this._router.url, this.properties, 'monitor').subscribe(contents => {
143
      this.divContents = contents;
144
    })
145
  }
146

    
147
  private setView(params: Params) {
148
    if (params && params['topic']) {
149
      this.activeTopic = this.stakeholder.topics.filter(topic => topic.alias === decodeURIComponent(params['topic']))[0];
150
      if (this.activeTopic) {
151
        if (params['category']) {
152
          this.activeCategory = this.activeTopic.categories.filter(category =>
153
            (category.alias === params['category']) && category.isPublic && category.isActive)[0];
154
        } else {
155
          let category: Category = this.activeTopic.categories[0];
156
          if(category) {
157
            this.navigateTo(this.stakeholder.alias, this.activeTopic.alias, category.alias);
158
          } else {
159
            this.navigateToError();
160
          }
161
          return;
162
        }
163
        if (this.activeCategory) {
164
          if (params['subCategory']) {
165
            this.activeSubCategory = this.activeCategory.subCategories.filter(subCategory =>
166
              (subCategory.alias === params['subCategory'] && subCategory.isPublic && subCategory.isActive))[0];
167
          } else {
168
            this.activeSubCategory = this.activeCategory.subCategories.filter(subCategory =>
169
              !subCategory.alias && subCategory.isPublic && subCategory.isActive)[0];
170
          }
171
          if (this.activeSubCategory) {
172
            this.setSideBar();
173
            this.setIndicators();
174
            return;
175
          } else {
176
            let subCategory: SubCategory = this.activeCategory.subCategories.filter(subCategory =>
177
              subCategory.isPublic && subCategory.isActive)[0];
178
            this.navigateTo(this.stakeholder.alias, this.activeTopic.alias, this.activeCategory.alias, subCategory.alias);
179
            return;
180
          }
181
        }
182
      }
183
      this.navigateToError();
184
    } else {
185
      let topic: Topic = this.stakeholder.topics[0];
186
      let category: Category = topic.categories.filter(category => category.isPublic && category.isActive)[0];
187
      if(topic && category) {
188
        this.navigateTo(this.stakeholder.alias, topic.alias, category.alias);
189
      } else {
190
        this.navigateToError();
191
      }
192
    }
193
  }
194

    
195
  private setSideBar() {
196
    let items: Item[] = [];
197
    this.activeTopic.categories.forEach(category => {
198
      if (category.isPublic && category.isActive) {
199
        let subItems: Item[] = [];
200
        category.subCategories.forEach(subCategory => {
201
          if (subCategory.alias != null && subCategory.isPublic && subCategory.isActive) {
202
            subItems.push(new Item(subCategory.name, (
203
              '/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias + '/' + subCategory.alias),
204
              null, null, false));
205
          }
206
        });
207
        const open = this.activeCategory.alias === category.alias;
208
        items.push(new Item(category.name, (
209
          '/' +  this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias),
210
          subItems, null, open));
211
      }
212
    });
213
    this.sideBar = new Sidebar(items, null);
214
  }
215

    
216
  private setIndicators() {
217
    let urls: Map<string, number[]> = new Map<string, number[]>();
218
    this.activeSubCategory.numbers.forEach((number, index) => {
219
      if (number.isActive && number.isPublic) {
220
        let url = number.indicatorPaths[0].url;
221
        //add fundingLevel0 filter in the query
222
        if(this.fundingL0 && number.indicatorPaths[0].filters.get("fundingL0")){
223
          url = url + number.indicatorPaths[0].filters.get("fundingL0").replace(ChartHelper.prefix+'fundingL0'+ChartHelper.suffix,encodeURIComponent(this.fundingL0));
224
        }
225
        const pair = JSON.stringify([number.indicatorPaths[0].source, url]);
226
        const indexes = urls.get(pair) ? urls.get(pair) : [];
227
        indexes.push(index);
228
        urls.set(pair, indexes);
229
      }
230
    });
231
    urls.forEach((indexes, pair) => {
232
      pair = JSON.parse(pair);
233
      this.statisticsService.getNumbers(pair[0], pair[1]).subscribe(response => {
234
        indexes.forEach(index => {
235
          let result = JSON.parse(JSON.stringify(response));
236
          this.activeSubCategory.numbers[index].indicatorPaths[0].jsonPath.forEach(jsonPath => {
237
            if (result) {
238
              result = result[jsonPath];
239
            }
240
          });
241
          this.numberResults.set(index, result);
242
        });
243
      })
244
    });
245
    this.activeSubCategory.charts.forEach((chart, index) => {
246
      if (chart.indicatorPaths.length > 0) {
247
        chart.indicatorPaths[0].safeResourceUrl = this.getUrlByStakeHolder(chart.indicatorPaths[0]);
248
        this.chartsActiveType.set(index, chart.indicatorPaths[0]);
249
      }
250
    });
251
    this.cdr.detectChanges();
252
  }
253

    
254
  public getUrlByStakeHolder(indicatorPath: IndicatorPath) {
255
    return this.sanitizer.bypassSecurityTrustResourceUrl(
256
      this.statisticsService.getChartUrl(indicatorPath.source, this.indicatorUtils.getFullUrl(indicatorPath, this.fundingL0, this.startYear, this.endYear)));
257
  }
258

    
259
  public setActiveChart(index, type: string) {
260
    let activeChart = this.activeSubCategory.charts[index].indicatorPaths.filter(indicatorPath => indicatorPath.type === type)[0];
261
    activeChart.safeResourceUrl = this.getUrlByStakeHolder(activeChart);
262
    this.chartsActiveType.set(index, activeChart);
263
  }
264

    
265
  private navigateToError() {
266
    this._router.navigate(['/error'], {queryParams: {'page': this._router.url}});
267
  }
268

    
269
  public navigateTo(stakeholder: string, topic: string, category: string = null, subcategory: string = null) {
270
    let url = stakeholder + '/' + topic + ((category) ? ('/'
271
      + category) : '') + ((subcategory) ? ('/' + subcategory) : '');
272
    return this._router.navigate([url]);
273
  }
274

    
275
  public quote(param: string): string {
276
    return StringUtils.quote(param);
277
  }
278

    
279
  public ngOnDestroy() {
280
    if (this.piwiksub) {
281
      this.piwiksub.unsubscribe();
282
    }
283
  }
284
}
(3-3/4)