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, 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 {SideBarService} from "../library/sharedComponents/sidebar/sideBar.service";
18

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

    
40
  constructor(
41
    private route: ActivatedRoute,
42
    private _router: Router,
43
    private _meta: Meta,
44
    private _title: Title,
45
    private _piwikService: PiwikService,
46
    private helper: HelperService,
47
    private stakeholderService: StakeholderService,
48
    private statisticsService: StatisticsService,
49
    private sideBarService: SideBarService,
50
    private seoService: SEOService,
51
    private cdr: ChangeDetectorRef,
52
    private sanitizer: DomSanitizer) {
53
      this.errorCodes = new ErrorCodes();
54
      this.errorMessages = new ErrorMessagesComponent();
55
      this.status = this.errorCodes.LOADING;
56
  }
57

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

    
97
  public get open() {
98
    return this.sideBarService.open;
99
  }
100

    
101
  public toggleOpen(event = null) {
102
    if(!event) {
103
      this.sideBarService.setOpen(!this.open);
104
    } else if(event && event['value'] === true) {
105
      this.sideBarService.setOpen(false);
106
    }
107
  }
108

    
109
  private getPageContents() {
110
    this.helper.getPageHelpContents(this._router.url, this.properties, 'monitor').subscribe(contents => {
111
      this.pageContents = contents;
112
    })
113
  }
114

    
115
  private getDivContents() {
116
    this.helper.getDivHelpContents(this._router.url, this.properties, 'monitor').subscribe(contents => {
117
      this.divContents = contents;
118
    })
119
  }
120

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

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

    
190
  private setIndicators() {
191
    let urls: Map<string, number[]> = new Map<string, number[]>();
192
    this.activeSubCategory.numbers.forEach((number, index) => {
193
      if (number.isActive && number.isPublic) {
194
        const pair = JSON.stringify([number.indicatorPaths[0].source, number.indicatorPaths[0].url]);
195
        const indexes = urls.get(pair) ? urls.get(pair) : [];
196
        indexes.push(index);
197
        urls.set(pair, indexes);
198
      }
199
    });
200
    urls.forEach((indexes, pair) => {
201
      pair = JSON.parse(pair);
202
      this.statisticsService.getNumbers(pair[0], pair[1]).subscribe(response => {
203
        indexes.forEach(index => {
204
          let result = JSON.parse(JSON.stringify(response));
205
          this.activeSubCategory.numbers[index].indicatorPaths[0].jsonPath.forEach(jsonPath => {
206
            if (result) {
207
              result = result[jsonPath];
208
            }
209
          });
210
          this.numberResults.set(index, result);
211
        });
212
      })
213
    });
214
    this.activeSubCategory.charts.forEach((chart, index) => {
215
      if (chart.indicatorPaths.length > 0) {
216
        chart.indicatorPaths[0].safeResourceUrl = this.getUrlByStakeHolder(chart.indicatorPaths[0]);
217
        this.chartsActiveType.set(index, chart.indicatorPaths[0]);
218
      }
219
    });
220
    this.cdr.detectChanges();
221
  }
222

    
223
  public getUrlByStakeHolder(indicatorPath: IndicatorPath) {
224
    return this.sanitizer.bypassSecurityTrustResourceUrl(this.statisticsService.getChartUrl(indicatorPath.source, indicatorPath.getFullUrl()));
225
  }
226

    
227
  public setActiveChart(index, type: string) {
228
    let activeChart = this.activeSubCategory.charts[index].indicatorPaths.filter(indicatorPath => indicatorPath.type === type)[0];
229
    activeChart.safeResourceUrl = this.getUrlByStakeHolder(activeChart);
230
    this.chartsActiveType.set(index, activeChart);
231
  }
232

    
233
  private navigateToError() {
234
    this._router.navigate(['/error'], {queryParams: {'page': this._router.url}});
235
  }
236

    
237
  public navigateTo(stakeholder: string, topic: string, category: string = null, subcategory: string = null) {
238
    let url = '/monitor/' + stakeholder + '/' + topic + ((category) ? ('/'
239
      + category) : '') + ((subcategory) ? ('/' + subcategory) : '');
240
    return this._router.navigate([url]);
241
  }
242

    
243
  public quote(param: string): string {
244
    return StringUtils.quote(param);
245
  }
246

    
247
  public ngOnDestroy() {
248
    if (this.piwiksub) {
249
      this.piwiksub.unsubscribe();
250
    }
251
  }
252
}
(3-3/4)