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
              this.stakeholder = stakeholder;
70
              this.seoService.createLinkForCanonicalURL(url, false);
71
              this._meta.updateTag({content: url}, "property='og:url'");
72
              var description = "Monitor Dashboard | " + this.stakeholder.index_name;
73
              var title = "Monitor Dashboard | " + this.stakeholder.index_shortName;
74
              this._meta.updateTag({content: description}, "name='description'");
75
              this._meta.updateTag({content: description}, "property='og:description'");
76
              this._meta.updateTag({content: title}, "property='og:title'");
77
              this._title.setTitle(title);
78
              if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
79
                this.piwiksub = this._piwikService.trackView(this.properties, title, this.properties.piwikSiteId).subscribe();
80
              }
81
              //this.getDivContents();
82
              this.getPageContents();
83
              this.status = this.errorCodes.DONE;
84
              this.setView(params);
85
            }, error => {
86
              this.navigateToError();
87
            })
88
          } else {
89
            this.setView(params);
90
          }
91
        });
92
      });
93
  }
94

    
95
  public get open() {
96
    return this.sideBarService.open;
97
  }
98

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

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

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

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

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

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

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

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

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

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

    
241
  public quote(param: string): string {
242
    return StringUtils.quote(param);
243
  }
244

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