Project

General

Profile

1
import {AfterViewInit, 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 {LayoutService} from "../library/sharedComponents/sidebar/layout.service";
19

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

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

    
63
  public ngOnInit() {
64
    this.route.data
65
      .subscribe((data: { envSpecific: EnvProperties }) => {
66
        this.route.params.subscribe(params => {
67
          this.properties = data.envSpecific;
68
          var url = data.envSpecific.baseLink + this._router.url;
69
          if (!this.stakeholder || this.stakeholder.index_id !== params['stakeholder']) {
70
            this.status = this.errorCodes.LOADING;
71
            this.numberResults = new Map<number, number>();
72
            this.chartsActiveType = new Map<number, IndicatorPath>();
73
            this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
74
              if(stakeholder) {
75
                this.stakeholder = stakeholder;
76
                this.seoService.createLinkForCanonicalURL(url, false);
77
                this._meta.updateTag({content: url}, "property='og:url'");
78
                var description = "Monitor Dashboard | " + this.stakeholder.index_name;
79
                var title = "Monitor Dashboard | " + this.stakeholder.index_shortName;
80
                this._meta.updateTag({content: description}, "name='description'");
81
                this._meta.updateTag({content: description}, "property='og:description'");
82
                this._meta.updateTag({content: title}, "property='og:title'");
83
                this._title.setTitle(title);
84
                if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
85
                  this.piwiksub = this._piwikService.trackView(this.properties, title, this.properties.piwikSiteId).subscribe();
86
                }
87
                //this.getDivContents();
88
                this.getPageContents();
89
                this.status = this.errorCodes.DONE;
90
                this.setView(params);
91
              }
92
            }, error => {
93
              this.navigateToError();
94
            })
95
          } else {
96
            this.setView(params);
97
          }
98
        });
99
      });
100
  }
101

    
102
  public get open() {
103
    return this.layoutService.open;
104
  }
105

    
106
  public toggleOpen(event = null) {
107
    if(!event) {
108
      this.layoutService.setOpen(!this.open);
109
    } else if(event && event['value'] === true) {
110
      this.layoutService.setOpen(false);
111
    }
112
  }
113

    
114
  private getPageContents() {
115
    this.helper.getPageHelpContents(this._router.url, this.properties, 'monitor').subscribe(contents => {
116
      this.pageContents = contents;
117
    })
118
  }
119

    
120
  private getDivContents() {
121
    this.helper.getDivHelpContents(this._router.url, this.properties, 'monitor').subscribe(contents => {
122
      this.divContents = contents;
123
    })
124
  }
125

    
126
  private setView(params: Params) {
127
    if (params && params['topic']) {
128
      this.activeTopic = this.stakeholder.topics.filter(topic => topic.alias === decodeURIComponent(params['topic']))[0];
129
      if (this.activeTopic) {
130
        if (params['category']) {
131
          this.activeCategory = this.activeTopic.categories.filter(category =>
132
            (category.alias === params['category']) && category.isPublic && category.isActive)[0];
133
        } else {
134
          let category: Category = this.activeTopic.categories[0];
135
          if(category) {
136
            this.navigateTo(this.stakeholder.alias, this.activeTopic.alias, category.alias);
137
          } else {
138
            this.navigateToError();
139
          }
140
          return;
141
        }
142
        if (this.activeCategory) {
143
          if (params['subCategory']) {
144
            this.activeSubCategory = this.activeCategory.subCategories.filter(subCategory =>
145
              (subCategory.alias === params['subCategory'] && subCategory.isPublic && subCategory.isActive))[0];
146
          } else {
147
            this.activeSubCategory = this.activeCategory.subCategories.filter(subCategory =>
148
              !subCategory.alias && subCategory.isPublic && subCategory.isActive)[0];
149
          }
150
          if (this.activeSubCategory) {
151
            this.setSideBar();
152
            this.setIndicators();
153
            return;
154
          } else {
155
            let subCategory: SubCategory = this.activeCategory.subCategories.filter(subCategory =>
156
              subCategory.isPublic && subCategory.isActive)[0];
157
            this.navigateTo(this.stakeholder.alias, this.activeTopic.alias, this.activeCategory.alias, subCategory.alias);
158
            return;
159
          }
160
        }
161
      }
162
      this.navigateToError();
163
    } else {
164
      let topic: Topic = this.stakeholder.topics[0];
165
      let category: Category = topic.categories.filter(category => category.isPublic && category.isActive)[0];
166
      if(topic && category) {
167
        this.navigateTo(this.stakeholder.alias, topic.alias, category.alias);
168
      } else {
169
        this.navigateToError();
170
      }
171
    }
172
  }
173

    
174
  private setSideBar() {
175
    let items: Item[] = [];
176
    this.activeTopic.categories.forEach(category => {
177
      if (category.isPublic && category.isActive) {
178
        let subItems: Item[] = [];
179
        category.subCategories.forEach(subCategory => {
180
          if (subCategory.alias != null && subCategory.isPublic && subCategory.isActive) {
181
            subItems.push(new Item(subCategory.name, (
182
              '/monitor/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias + '/' + subCategory.alias),
183
              null, null, false));
184
          }
185
        });
186
        const open = this.activeCategory.alias === category.alias;
187
        items.push(new Item(category.name, (
188
          '/monitor/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias),
189
          subItems, null, open));
190
      }
191
    });
192
    this.sideBar = new Sidebar(items, null);
193
  }
194

    
195
  private setIndicators() {
196
    let urls: Map<string, number[]> = new Map<string, number[]>();
197
    this.activeSubCategory.numbers.forEach((number, index) => {
198
      if (number.isActive && number.isPublic) {
199
        let url = number.indicatorPaths[0].url;
200
        //add fundingLevel0 filter in the query
201
        if(this.fundingL0 && number.indicatorPaths[0].filters.get("fundingL0")){
202
          url = url + number.indicatorPaths[0].filters.get("fundingL0").replace(ChartHelper.prefix+'fundingL0'+ChartHelper.suffix,encodeURIComponent(this.fundingL0));
203
        }
204
        const pair = JSON.stringify([number.indicatorPaths[0].source, url]);
205
        const indexes = urls.get(pair) ? urls.get(pair) : [];
206
        indexes.push(index);
207
        urls.set(pair, indexes);
208
      }
209
    });
210
    urls.forEach((indexes, pair) => {
211
      pair = JSON.parse(pair);
212
      this.statisticsService.getNumbers(pair[0], pair[1]).subscribe(response => {
213
        indexes.forEach(index => {
214
          let result = JSON.parse(JSON.stringify(response));
215
          this.activeSubCategory.numbers[index].indicatorPaths[0].jsonPath.forEach(jsonPath => {
216
            if (result) {
217
              result = result[jsonPath];
218
            }
219
          });
220
          this.numberResults.set(index, result);
221
        });
222
      })
223
    });
224
    this.activeSubCategory.charts.forEach((chart, index) => {
225
      if (chart.indicatorPaths.length > 0) {
226
        chart.indicatorPaths[0].safeResourceUrl = this.getUrlByStakeHolder(chart.indicatorPaths[0]);
227
        this.chartsActiveType.set(index, chart.indicatorPaths[0]);
228
      }
229
    });
230
    this.cdr.detectChanges();
231
  }
232

    
233
  public getUrlByStakeHolder(indicatorPath: IndicatorPath) {
234
    return this.sanitizer.bypassSecurityTrustResourceUrl(
235
      this.statisticsService.getChartUrl(indicatorPath.source, this.indicatorUtils.getFullUrl(indicatorPath, this.fundingL0, this.startYear, this.endYear)));
236
  }
237

    
238
  public setActiveChart(index, type: string) {
239
    let activeChart = this.activeSubCategory.charts[index].indicatorPaths.filter(indicatorPath => indicatorPath.type === type)[0];
240
    activeChart.safeResourceUrl = this.getUrlByStakeHolder(activeChart);
241
    this.chartsActiveType.set(index, activeChart);
242
  }
243

    
244
  private navigateToError() {
245
    this._router.navigate(['/error'], {queryParams: {'page': this._router.url}});
246
  }
247

    
248
  public navigateTo(stakeholder: string, topic: string, category: string = null, subcategory: string = null) {
249
    let url = '/monitor/' + stakeholder + '/' + topic + ((category) ? ('/'
250
      + category) : '') + ((subcategory) ? ('/' + subcategory) : '');
251
    return this._router.navigate([url]);
252
  }
253

    
254
  public quote(param: string): string {
255
    return StringUtils.quote(param);
256
  }
257

    
258
  public ngOnDestroy() {
259
    if (this.piwiksub) {
260
      this.piwiksub.unsubscribe();
261
    }
262
  }
263
}
(3-3/4)