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 "../openaireLibrary/monitor/services/stakeholder.service";
14
import {Category, ChartHelper, IndicatorPath, Stakeholder, SubCategory, Topic} from "../openaireLibrary/monitor/entities/stakeholder";
15
import {StatisticsService} from "../utils/services/statistics.service";
16
import {IndicatorUtils, StakeholderUtils} from "../utils/indicator-utils";
17
import {LayoutService} from "../openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
18
import {FormBuilder, FormControl} from "@angular/forms";
19
import {IDeactivateComponent} from "../openaireLibrary/utils/can-exit.guard";
20
import {Subscription} from "rxjs";
21
import {Session, User} from "../openaireLibrary/login/utils/helper.class";
22
import {MenuItem} from "../openaireLibrary/sharedComponents/menu";
23
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
24
import {StakeholderCreator} from "../utils/entities/stakeholderCreator";
25

    
26
@Component({
27
  selector: 'monitor',
28
  templateUrl: 'monitor.component.html',
29
})
30
export class MonitorComponent implements OnInit, OnDestroy, IDeactivateComponent {
31
  private static sidebarStatus: {
32
    id;
33
    status;
34
  };
35
  public user: User;
36
  public userMenuItems: MenuItem[] = [new MenuItem("", "My profile", "", "", false, [], [], {})];
37
  public subscriptions: any[] = [];
38
  public piwiksub: any;
39
  public pageContents = null;
40
  public divContents = null;
41
  public status: number;
42
  public loading: boolean = true;
43
  public isViewPublic: boolean = false;
44
  public indicatorUtils: IndicatorUtils = new IndicatorUtils();
45
  public stakeholderUtils: StakeholderUtils = new StakeholderUtils();
46
  public activeTopic: Topic = null;
47
  public activeCategory: Category = null;
48
  public activeSubCategory: SubCategory = null;
49
  public sideBarItems: MenuItem[] = [];
50
  public errorCodes: ErrorCodes;
51
  public stakeholder: Stakeholder;
52
  public numberResults: Map<string, number> = new Map<string, number>();
53
  public chartsActiveType: Map<string, IndicatorPath> = new Map<string, IndicatorPath>();
54
  private errorMessages: ErrorMessagesComponent;
55
  properties: EnvProperties;
56
  fundingL0;
57
  startYear;
58
  endYear;
59

    
60
  public keyword: FormControl;
61
  
62
  constructor(
63
    private route: ActivatedRoute,
64
    private _router: Router,
65
    private _meta: Meta,
66
    private _title: Title,
67
    private _piwikService: PiwikService,
68
    private helper: HelperService,
69
    private stakeholderService: StakeholderService,
70
    private userManagementService: UserManagementService,
71
    private statisticsService: StatisticsService,
72
    private layoutService: LayoutService,
73
    private seoService: SEOService,
74
    private cdr: ChangeDetectorRef,
75
    private sanitizer: DomSanitizer, private _fb: FormBuilder) {
76
    this.errorCodes = new ErrorCodes();
77
    this.errorMessages = new ErrorMessagesComponent();
78
    this.status = this.errorCodes.LOADING;
79
  }
80
  
81
  public ngOnInit() {
82
    this.keyword = this._fb.control('');
83
    this.keyword.valueChanges.subscribe(value => {
84
      console.log("Keyword Changed!");
85
      //TODO do a real action
86
    });
87
    this.route.data
88
      .subscribe((data: { envSpecific: EnvProperties }) => {
89
        let subscription: Subscription;
90
        this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
91
          this.user = user;
92

    
93
          this.route.params.subscribe(params => {
94
            this.loading = true;
95
            this.activeTopic = null;
96
            this.activeCategory = null;
97
            this.activeSubCategory = null;
98

    
99
            if (subscription) {
100
              subscription.unsubscribe();
101
            }
102
            this.properties = data.envSpecific;
103
            var url = data.envSpecific.baseLink + this._router.url;
104
            this.route.queryParams.subscribe(params => {
105
              this.isViewPublic = (params['view'] == 'public');
106
            });
107
            this.buildMenu();
108

    
109
            if (!this.stakeholder || this.stakeholder.alias !== params['stakeholder']) {
110
              this.status = this.errorCodes.LOADING;
111
              this.numberResults = new Map<string, number>();
112
              this.chartsActiveType = new Map<string, IndicatorPath>();
113
              subscription = this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
114
                // let stakeholder: Stakeholder = null;
115
                // if (params['stakeholder'] == "fwf") {
116
                //   stakeholder = new Stakeholder(null, "funder", "fwf_________::FWF", "Austrian Science Fund (FWF)", "FWF",
117
                //     "fwf", true, true, null);
118
                //   stakeholder = this.stakeholderUtils.createFunderFromDefaultProfile(stakeholder, StakeholderCreator.createFunderDefaultProfile(stakeholder).topics);
119
                //   stakeholder.logoUrl = "./assets/fwf.png";
120
                // } else if (params['stakeholder'] == "arc") {
121
                //   stakeholder = new Stakeholder(null, "funder", "arc_________::ARC",
122
                //     "Australian Research Council (ARC)", "ARC", "arc", true, true, null);
123
                //   stakeholder = this.stakeholderUtils.createFunderFromDefaultProfile(stakeholder, StakeholderCreator.createFunderDefaultProfile(stakeholder).topics);
124
                //   stakeholder.logoUrl = "./assets/arc1.gif";
125
                // } else if (params['stakeholder'] == "ec")  {
126
                //   stakeholder = new Stakeholder(null, "funder", "ec__________::EC",
127
                //     "European Commission", "EC",
128
                //     "ec", true, true, null);
129
                //   stakeholder = this.stakeholderUtils.createFunderFromDefaultProfile(stakeholder, StakeholderCreator.createFunderDefaultProfile(stakeholder).topics);
130
                //   stakeholder.logoUrl = "./assets/ec.png";
131
                // }
132
                if (stakeholder) {
133
                  this.stakeholder = stakeholder;
134
                  console.info(this.stakeholder);
135

    
136
                  this.seoService.createLinkForCanonicalURL(url, false);
137
                  this._meta.updateTag({content: url}, "property='og:url'");
138
                  var description = "Monitor Dashboard | " + this.stakeholder.index_name;
139
                  var title = "Monitor Dashboard | " + this.stakeholder.index_shortName;
140
                  this._meta.updateTag({content: description}, "name='description'");
141
                  this._meta.updateTag({content: description}, "property='og:description'");
142
                  this._meta.updateTag({content: title}, "property='og:title'");
143
                  this._title.setTitle(title);
144
                  if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
145
                    this.piwiksub = this._piwikService.trackView(this.properties, title, this.properties.piwikSiteId).subscribe();
146
                  }
147
                  //this.getDivContents();
148
                  this.getPageContents();
149
                  this.status = this.errorCodes.DONE;
150
                  this.setView(params);
151
                  this.layoutService.setOpen(true);
152
                }
153
              }, error => {
154
                this.navigateToError();
155
              });
156
              this.subscriptions.push(subscription);
157
            } else {
158
              this.setView(params);
159
            }
160
            // this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
161
            //   this.user = user;
162
            //   this.buildMenu();
163
            // }, error => {
164
            //   console.log("App couldn't fetch properties");
165
            //   console.log(error);
166
            // }));
167
          });
168
        }));
169
      });
170
  }
171
  
172
  canExit() {
173
    if (this.sideBarItems.length > 0) {
174
      let status = [];
175
      this.sideBarItems.forEach(item => {
176
        status.push(item.open);
177
      });
178
      MonitorComponent.sidebarStatus = {
179
        id: this.activeTopic.alias,
180
        status: status
181
      };
182
    }
183
    return true;
184
  }
185
  
186
  public get open() {
187
    return this.layoutService.open;
188
  }
189
  
190
  private getPageContents() {
191
    this.helper.getPageHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
192
      this.pageContents = contents;
193
    })
194
  }
195
  
196
  private getDivContents() {
197
    this.helper.getDivHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
198
      this.divContents = contents;
199
    })
200
  }
201
  
202
  private setView(params: Params) {
203
    if (params['topic']) {
204
      this.activeTopic = this.stakeholder.topics.find(topic => topic.alias === decodeURIComponent(params['topic']) && this.isPublicOrIsMember(topic.isPublic) && topic.isActive);
205
      if (this.activeTopic) {
206
        if (params['category']) {
207
          this.activeCategory = this.activeTopic.categories.find(category =>
208
            (category.alias === params['category']) && this.isPublicOrIsMember(category.isPublic) && category.isActive);
209
          if (!this.activeCategory) {
210
            this.navigateToError();
211
            return;
212
          }
213
        } else {
214
          this.activeCategory = this.activeTopic.categories.find(category => this.isPublicOrIsMember(category.isPublic) && category.isActive);
215
          if (this.activeCategory) {
216
            this.activeSubCategory = this.activeCategory.subCategories.find(subCategory =>
217
              this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive);
218
            this.setSideBar();
219
            if (this.activeSubCategory) {
220
              this.setIndicators();
221
            }
222
          } else {
223
            this.setSideBar();
224
          }
225
          return;
226
        }
227
        if (this.activeCategory) {
228
          if (params['subCategory']) {
229
            this.activeSubCategory = this.activeCategory.subCategories.find(subCategory =>
230
              (subCategory.alias === params['subCategory'] && this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive));
231
            if (!this.activeSubCategory) {
232
              this.navigateToError();
233
              return;
234
            }
235
          } else {
236
            this.activeSubCategory = this.activeCategory.subCategories.find(subCategory =>
237
              this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive);
238
          }
239
          if (this.activeSubCategory) {
240
            this.setSideBar();
241
            this.setIndicators();
242
          } else {
243
            this.navigateToError();
244
          }
245
          return;
246
        } else {
247
          this.activeSubCategory = null;
248
        }
249
      } else {
250
        this.navigateToError();
251
        return;
252
      }
253
    } else {
254
      this.activeTopic = this.stakeholder.topics.find(topic => this.isPublicOrIsMember(topic.isPublic) && topic.isActive);
255
      if (this.activeTopic) {
256
        this.activeCategory = this.activeTopic.categories.find(category => this.isPublicOrIsMember(category.isPublic) && category.isActive);
257
        if (this.activeCategory) {
258
          this.activeSubCategory = this.activeCategory.subCategories.find(subCategory => this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive);
259
          if (this.activeSubCategory) {
260
            this.setSideBar();
261
            this.setIndicators();
262
          } else {
263
            this.navigateToError();
264
          }
265
        } else {
266
          this.navigateToError();
267
        }
268
      } else {
269
        this.navigateToError();
270
      }
271
    }
272
  }
273
  
274
  private setSideBar() {
275
    let items: MenuItem[] = [];
276
    this.activeTopic.categories.forEach((category, index) => {
277
      if (this.isPublicOrIsMember(category.isPublic) && category.isActive) {
278
        let subItems: MenuItem[] = [];
279
        category.subCategories.forEach(subCategory => {
280
          if (this.isPublicOrIsMember(subCategory.isPublic) && subCategory.isActive) {
281
            subItems.push(new MenuItem(subCategory.alias, subCategory.name, "", (
282
              '/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias + '/' + subCategory.alias),
283
              null, null, [], {}));
284
          }
285
        });
286
        let open = this.activeCategory.alias === category.alias;
287
        if (MonitorComponent.sidebarStatus && MonitorComponent.sidebarStatus.id === this.activeTopic.alias) {
288
          open = MonitorComponent.sidebarStatus.status[index];
289
        }
290
        //  constructor(id: string, title: string, url: string, route: string, needsAuthorization: boolean, entitiesRequired: string[], routeRequired: string[], params) {
291
        let categoryItem: MenuItem = new MenuItem(category.alias, category.name, "", (
292
          '/' + this.stakeholder.alias + '/' + this.activeTopic.alias + '/' + category.alias),
293
          null, [], [], {});
294
        categoryItem.items = subItems;
295
        categoryItem.open = open;
296
        items.push(categoryItem);
297
      }
298
    });
299
    if (items.length === 0) {
300
      items.push(new MenuItem('noCategories', 'No categories available yet', "", "", false, [], [], {}));
301
    }
302
    this.sideBarItems = items;
303
    this.loading = false;
304
  }
305
  
306
  private setIndicators() {
307
    let urls: Map<string, [number, number][]> = new Map<string, [number, number][]>();
308
    this.activeSubCategory.numbers.forEach((section, i) => {
309
      section.indicators.forEach((number, j) => {
310
        if (number.isActive && this.isPublicOrIsMember(number.isPublic)) {
311
          let url = number.indicatorPaths[0].url;
312
          //add fundingLevel0 filter in the query
313
          if (this.fundingL0 && number.indicatorPaths[0].filters.get("fundingL0")) {
314
            url = url + number.indicatorPaths[0].filters.get("fundingL0").replace(ChartHelper.prefix + 'fundingL0' + ChartHelper.suffix, encodeURIComponent(this.fundingL0));
315
          }
316
          const pair = JSON.stringify([number.indicatorPaths[0].source, url]);
317
          const indexes = urls.get(pair) ? urls.get(pair) : [];
318
          indexes.push([i, j]);
319
          urls.set(pair, indexes);
320
        }
321
      });
322
    });
323
    urls.forEach((indexes, pair) => {
324
      pair = JSON.parse(pair);
325
      this.statisticsService.getNumbers(pair[0], pair[1]).subscribe(response => {
326
        indexes.forEach(([i, j]) => {
327
          let result = JSON.parse(JSON.stringify(response));
328
          this.activeSubCategory.numbers[i].indicators[j].indicatorPaths[0].jsonPath.forEach(jsonPath => {
329
            if (result) {
330
              result = result[jsonPath];
331
            }
332
          });
333
          this.numberResults.set(i + '-' + j, result);
334
        });
335
      })
336
    });
337
    this.activeSubCategory.charts.forEach((section, i) => {
338
      section.indicators.forEach((indicator, j) => {
339
        if (indicator.indicatorPaths.length > 0) {
340
          indicator.indicatorPaths[0].safeResourceUrl = this.getUrlByStakeHolder(indicator.indicatorPaths[0]);
341
          this.chartsActiveType.set(i + '-' + j, indicator.indicatorPaths[0]);
342
        }
343
      });
344
    });
345
    this.cdr.detectChanges();
346
  }
347
  
348
  public getUrlByStakeHolder(indicatorPath: IndicatorPath) {
349
    return this.sanitizer.bypassSecurityTrustResourceUrl(
350
      this.statisticsService.getChartUrl(indicatorPath.source, this.indicatorUtils.getFullUrl(this.stakeholder, indicatorPath, this.fundingL0, this.startYear, this.endYear)));
351
  }
352
  
353
  public setActiveChart(i: number, j: number, type: string) {
354
    let activeChart = this.activeSubCategory.charts[i].indicators[j].indicatorPaths.filter(indicatorPath => indicatorPath.type === type)[0];
355
    activeChart.safeResourceUrl = this.getUrlByStakeHolder(activeChart);
356
    this.chartsActiveType.set(i + '-' + j, activeChart);
357
  }
358
  
359
  private navigateToError() {
360
    this._router.navigate(['/error'], {queryParams: {'page': this._router.url}});
361
  }
362
  
363
  public navigateTo(stakeholder: string, topic: string, category: string = null, subcategory: string = null) {
364
    let url = stakeholder + '/' + topic + ((category) ? ('/'
365
      + category) : '') + ((subcategory) ? ('/' + subcategory) : '');
366
    return this._router.navigate([url]);
367
  }
368
  
369
  public quote(param: string): string {
370
    return StringUtils.quote(param);
371
  }
372
  
373
  public ngOnDestroy() {
374
    if (this.piwiksub) {
375
      this.piwiksub.unsubscribe();
376
    }
377
  }
378
  
379
  buildMenu() {
380
    this.userMenuItems = [];
381
    // if (Session.isPortalAdministrator(this.user)) {
382
    //   this.userMenuItems.push(new MenuItem("", "Manage helptexts",
383
    //     ((this.properties.environment == "beta") ? "https://beta.admin.connect.openaire.eu" : "https://admin.explore.openaire.eu") + "/dashboard?communityId=openaire", "", true, [], [], {}))
384
    //
385
    // }
386
    if (this.user) {
387
      this.userMenuItems.push(new MenuItem("", "Manage Stakeholders", "", "/admin", false, [], [], {}));
388
    }
389
    if (this.user) {
390
      this.userMenuItems.push(new MenuItem("", "User information", "", "/user-info", false, [], [], {}));
391
    }
392
  }
393

    
394
  isAdmin(){
395
    return this.user && (Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user) || Session.isMonitorCurator(this.user));
396
  }
397

    
398
  isLoggedIn() {
399
    return this.user;
400
  }
401

    
402
  public isPublicOrIsMember(isPublic: boolean): boolean {
403
    if (isPublic) {
404
      return true;
405
    } else {
406
      if (this.isViewPublic) { // preview for not members
407
        return false;
408
      } else if(this.user) {
409
        // if user is member, return true
410
        return true;
411
      }
412
      return false;
413
    }
414
  }
415
}
(3-3/4)