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, StakeholderUtils} 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 stakeholderUtils: StakeholderUtils = new StakeholderUtils();
33
  public activeTopic: Topic = null;
34
  public activeCategory: Category = null;
35
  public activeSubCategory: SubCategory = null;
36
  public sideBar: Sidebar = null;
37
  public errorCodes: ErrorCodes;
38
  public stakeholder: Stakeholder;
39
  public numberResults: Map<number, number> = new Map<number, number>();
40
  public chartsActiveType: Map<number, IndicatorPath> = new Map<number, IndicatorPath>();
41
  private errorMessages: ErrorMessagesComponent;
42
  properties: EnvProperties;
43
  fundingL0;
44
  startYear;
45
  endYear;
46

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

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

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

    
129
  public get open() {
130
    return this.layoutService.open;
131
  }
132

    
133
  public toggleOpen(event = null) {
134
    if(!event) {
135
      this.layoutService.setOpen(!this.open);
136
    } else if(event && event['value'] === true) {
137
      this.layoutService.setOpen(false);
138
    }
139
  }
140

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

    
147
  private getDivContents() {
148
    this.helper.getDivHelpContents(this._router.url, this.properties, 'monitor').subscribe(contents => {
149
      this.divContents = contents;
150
    })
151
  }
152

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

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

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

    
260
  public getUrlByStakeHolder(indicatorPath: IndicatorPath) {
261
    return this.sanitizer.bypassSecurityTrustResourceUrl(
262
      this.statisticsService.getChartUrl(indicatorPath.source, this.indicatorUtils.getFullUrl(indicatorPath, this.fundingL0, this.startYear, this.endYear)));
263
  }
264

    
265
  public setActiveChart(index, type: string) {
266
    let activeChart = this.activeSubCategory.charts[index].indicatorPaths.filter(indicatorPath => indicatorPath.type === type)[0];
267
    activeChart.safeResourceUrl = this.getUrlByStakeHolder(activeChart);
268
    this.chartsActiveType.set(index, activeChart);
269
  }
270

    
271
  private navigateToError() {
272
    this._router.navigate(['/error'], {queryParams: {'page': this._router.url}});
273
  }
274

    
275
  public navigateTo(stakeholder: string, topic: string, category: string = null, subcategory: string = null) {
276
    let url = stakeholder + '/' + topic + ((category) ? ('/'
277
      + category) : '') + ((subcategory) ? ('/' + subcategory) : '');
278
    return this._router.navigate([url]);
279
  }
280

    
281
  public quote(param: string): string {
282
    return StringUtils.quote(param);
283
  }
284

    
285
  public ngOnDestroy() {
286
    if (this.piwiksub) {
287
      this.piwiksub.unsubscribe();
288
    }
289
  }
290
}
(3-3/4)