Project

General

Profile

1
import {Component, ElementRef, Input, ViewChild} from '@angular/core';
2
import {ActivatedRoute, Router} from '@angular/router';
3
import {Meta, Title} from '@angular/platform-browser';
4

    
5
import {OrganizationService} from '../../services/organization.service';
6
import {OrganizationInfo} from '../../utils/entities/organizationInfo';
7
import {ReportsService} from '../../services/reports.service';
8
import {FetchResearchResults} from '../../utils/fetchEntitiesClasses/fetchResearchResults.class';
9
// import {FetchDatasets}                  from '../../utils/fetchEntitiesClasses/fetchDatasets.class';
10
import {FetchProjects} from '../../utils/fetchEntitiesClasses/fetchProjects.class';
11
import {FetchDataproviders} from '../../utils/fetchEntitiesClasses/fetchDataproviders.class';
12
import {SearchResearchResultsService} from '../../services/searchResearchResults.service';
13
// import {SearchDatasetsService}      from '../../services/searchDatasets.service';
14
import {SearchDataprovidersService} from '../../services/searchDataproviders.service';
15
import {SearchProjectsService} from '../../services/searchProjects.service';
16
import {ErrorCodes} from '../../utils/properties/errorCodes';
17
import {SearchingProjectsTabComponent} from '../landing-utils/searchingProjectsInTab.component';
18
import {RouterHelper} from '../../utils/routerHelper.class';
19

    
20
import {ModalLoading} from '../../utils/modal/loading.component';
21
import {PiwikService} from '../../utils/piwik/piwik.service';
22
import {StringUtils} from '../../utils/string-utils.class';
23
import {EnvProperties} from '../../utils/properties/env-properties';
24
import {SEOService} from '../../sharedComponents/SEO/SEO.service';
25
import {HelperFunctions} from "../../utils/HelperFunctions.class";
26
import {HelperService} from "../../utils/helper/helper.service";
27

    
28
@Component({
29
  selector: 'organization',
30
  templateUrl: 'organization.component.html',
31
})
32

    
33
export class OrganizationComponent {
34
  @Input() piwikSiteId = null;
35
  @Input() communityId = null;
36

    
37
  public organizationInfo: OrganizationInfo;
38
  public organizationId: string;
39

    
40
  // Message variables
41
  public warningMessage = "";
42
  public errorMessage = "";
43
  public showLoading: boolean = true;
44

    
45
  // CSV variables
46
  public downloadURLAPI: string;
47
  public csvProjectParamsHead: string;
48
  public csvPublicationParamsHead: string;
49
  public csvParamsTail: string;
50
  public csvAffiliatedPublications: string;
51

    
52
  // Active tab variable for responsiveness
53
  public activeTab: string = "Publications";
54

    
55
  // Variables for publications, research data, projects, dataproviders tabs
56
  public fetchPublications: FetchResearchResults;
57
  public linkToSearchPublications: string = "";
58
  // public fetchDatasets: FetchDatasets;
59
  // public linkToSearchDatasets: string = "";
60
  public fetchProjects: FetchProjects;
61
  public fetchDataproviders: FetchDataproviders;
62
  public linkToSearchDataproviders: string = "";
63
  //public projectFunders:string[] = [];
64

    
65
  // Variables for projects query (query results only if projects tab is clicked)
66
  public projectsClicked: boolean = false;
67
  @ViewChild(SearchingProjectsTabComponent) searchingProjectsTabComponent: SearchingProjectsTabComponent;
68

    
69
  @ViewChild(ModalLoading) loading: ModalLoading;
70
  // Alert box when CSV: Project Publications for a funder is requested
71
  @ViewChild('AlertModalApplyAll') alertApplyAll;
72
  // Alert box when something is wrong with CSV requests
73
  @ViewChild('AlertModalCsvError') alertCsvError;
74

    
75
  public routerHelper: RouterHelper = new RouterHelper();
76
  public errorCodes: ErrorCodes = new ErrorCodes();
77
  public pageContents = null;
78
  public divContents = null;
79

    
80
  //private projectsNum: number = 0;
81
  //private fundersSet: Set<string>;
82
  //private emptyFundersSet: boolean = true;
83

    
84
  // Request results for publications, research data and content providers only the one time (first time tab is clicked)
85
  private reloadPublications: boolean = true;
86
  // private reloadDatasets: boolean = true;
87
  private reloadDataproviders: boolean = true;
88

    
89
  // Helper variables to specify funder in downloadPublicationsFile function
90
  private funder: string;
91
  private funderId: string;
92
  private funderCountPublications: number;
93
  sub: any;
94
  infoSub: any;
95
  piwiksub: any;
96
  downloadFileSub: any;
97
  downloadFilePiwikSub: any;
98
  countProjectsSub: any;
99
  countPublSub: any;
100
  downloadProjectPublSub: any;
101
  properties: EnvProperties;
102

    
103
  @ViewChild('AlertModalDeletedByInference') alertModalDeletedByInference;
104
  public deleteByInferenceOpened: boolean = false;
105

    
106
  //private ngUnsubscribe: Subject<void> = new Subject<void>();
107

    
108
  constructor(private element: ElementRef,
109
              private _organizationService: OrganizationService,
110
              private _piwikService: PiwikService,
111
              private  route: ActivatedRoute,
112
              private _searchDataprovidersService: SearchDataprovidersService,
113
              private _reportsService: ReportsService,
114
              private _searchResearchResultsService: SearchResearchResultsService,
115
              // private _searchDatasetsService: SearchDatasetsService,
116
              private _searchProjectsService: SearchProjectsService,
117
              private _meta: Meta,
118
              private _title: Title,
119
              private _router: Router,
120
              private helper: HelperService,
121
              private seoService: SEOService) {
122

    
123
    this.fetchPublications = new FetchResearchResults(this._searchResearchResultsService);
124
    // this.fetchDatasets = new FetchDatasets(this._searchDatasetsService);
125
    this.fetchProjects = new FetchProjects(this._searchProjectsService);
126
    this.fetchDataproviders = new FetchDataproviders(this._searchDataprovidersService);
127
  }
128

    
129
  ngOnInit() {
130
    this.route.data
131
      .subscribe((data: { envSpecific: EnvProperties }) => {
132
        this.properties = data.envSpecific;
133
        //this.getDivContents();
134
        this.getPageContents();
135
        this.updateUrl(data.envSpecific.baseLink + this._router.url);
136
      });
137
    this.sub = this.route.queryParams.subscribe(params => {
138
      this.organizationInfo = null;
139
      this.updateTitle("Organization");
140
      this.updateDescription("");
141
      this.projectsClicked = false;
142

    
143
      this.organizationId = params['organizationId'];
144

    
145
      if (this.organizationId) {
146
        this.getOrganizationInfo();
147
      } else {
148
        this.showLoading = false;
149
        this._router.navigate(['/error'], {queryParams: {"page": this.properties.searchLinkToOrganization + this.organizationId, "page_type": "organization"}});
150
        //this.warningMessage = "No valid organization id";
151
      }
152

    
153
      HelperFunctions.scroll();
154

    
155
      this.csvParamsTail = '" and relorganizationid exact "' + this.organizationId + '" ))';
156

    
157
    });
158

    
159
    this.downloadURLAPI = this.properties.csvAPIURL;
160
    this.csvAffiliatedPublications = this.downloadURLAPI + "?format=csv&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relorganizationid exact \"" + this.organizationId + "\"))";
161
    this.csvProjectParamsHead = 'format=csv&type=projects&fq=( (oaftype exact project)and (funder exact "';
162
    //this.csvPublicationParamsHead = 'format=csv-special&type=publications&page=0&query=((((oaftype exact result) and (resulttypeid exact publication)) and (funderid exact ';
163
  }
164

    
165
  private getPageContents() {
166
    this.helper.getPageHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
167
      this.pageContents = contents;
168
    })
169
  }
170

    
171
  private getDivContents() {
172
    this.helper.getDivHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
173
      this.divContents = contents;
174
    })
175
  }
176

    
177

    
178
  ngOnDestroy() {
179
    if (this.sub) {
180
      this.sub.unsubscribe();
181
    }
182
    if (this.piwiksub) {
183
      this.piwiksub.unsubscribe();
184
    }
185
    if (this.infoSub) {
186
      this.infoSub.unsubscribe();
187
    }
188
    if (this.downloadFileSub) {
189
      this.downloadFileSub.unsubscribe();
190
    }
191
    if (this.downloadFilePiwikSub) {
192
      this.downloadFilePiwikSub.unsubscribe();
193
    }
194
    if (this.countProjectsSub) {
195
      this.countProjectsSub.unsubscribe();
196
    }
197
    if (this.countPublSub) {
198
      this.countPublSub.unsubscribe();
199
    }
200
    if (this.downloadProjectPublSub) {
201
      this.downloadProjectPublSub.unsubscribe();
202
    }
203

    
204
    /*
205
    this.ngUnsubscribe.next();
206
    this.ngUnsubscribe.complete();
207
    */
208
  }
209

    
210
  private getOrganizationInfo() {
211

    
212
    this.warningMessage = '';
213
    this.errorMessage = ""
214
    this.showLoading = true;
215

    
216
    this.organizationInfo = null;
217

    
218
    this.infoSub = this._organizationService.getOrganizationInfo(this.organizationId, this.properties).subscribe(
219
      data => {
220
        if (data == null) {
221
          this.showLoading = false;
222
          this.errorMessage = 'No organization found';
223
        } else {
224
          this.organizationInfo = data;
225
          this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.properties.searchLinkToOrganization + this.organizationInfo.objIdentifier);
226
          this.updateTitle(this.organizationInfo.title.name);
227
          this.updateDescription("Organization, country, " + this.organizationInfo.title.name + ((this.organizationInfo.title.name && this.organizationInfo.title.name != this.organizationInfo.name) ? (", " + this.organizationInfo.name) : ""));
228
          if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
229
            this.piwiksub = this._piwikService.trackView(this.properties, this.organizationInfo.title.name, this.piwikSiteId).subscribe();
230
          }
231
          var refineFields: string [] = ["funder"];
232

    
233
          //this.searchPublications();
234
          this.fetchPublications.getNumForEntity("publication", "organization", this.organizationId, this.properties);
235
          // this.fetchDatasets.getNumForEntity("organization", this.organizationId, this.properties);
236
          this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0, refineFields, this.properties);
237

    
238
          this.fetchDataproviders.getNumForEntity("organization", this.organizationId, this.properties);
239

    
240
          this.showLoading = false;
241

    
242
          /*let projectsNum = 0;
243

    
244
          if(this.organizationInfo.projects != undefined) {
245
               this.fundersSet = new Set<string>();
246
              this.organizationInfo.projects.forEach(function (value, key, map) {
247
                  projectsNum += value.length;
248
                  this.fundersSet.add(key);
249
              }.bind(this));
250
          }
251

    
252
          this.projectsNum = projectsNum;*/
253
        }
254
      },
255
      err => {
256
        //console.log(err)
257
        this.handleError("Error getting organization for id: " + this.organizationId, err);
258
        if(err.status == 404) {
259
          this._router.navigate(['/error'], {queryParams: {"page": this.properties.searchLinkToOrganization + this.organizationId, "page_type": "organization"}});
260
        }
261
        this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.properties.searchLinkToOrganizations);
262
        //this.errorMessage = 'No organization found';
263
        this.showLoading = false;
264
      }
265
    );
266
  }
267

    
268
  /*
269
      private handleClick(funder: string) {
270
           if(this.emptyFundersSet) {
271
               this.fundersSet.clear();
272
               this.emptyFundersSet = false;
273
           }
274

    
275
           if(this.fundersSet.has(funder)) {
276
               this.fundersSet.delete(funder);
277

    
278
               if(this.fundersSet.size == 0) {
279
                   this.organizationInfo.projects.forEach(function (value, key, map) {
280
                       this.fundersSet.add(key);
281
                   }.bind(this));
282
                   this.emptyFundersSet = true;
283
               }
284
               console.info(funder+" funder deleted");
285
           } else {
286
               this.fundersSet.add(funder);
287
               console.info(funder+" funder added");
288
           }
289
       }
290
  */
291
  //private getProjectsData(key: string): any {
292
  //return this.projectsData;
293
  //}
294

    
295
  private searchPublications() {
296
    this.fetchPublications.getResultsForEntity("publication", "organization", this.organizationId, 1, 10, this.properties);
297
    this.linkToSearchPublications = this.properties.searchLinkToAdvancedPublications;
298
    //if(this.fetchPublications.searchUtils.totalResults > 0) {
299
    this.reloadPublications = false;
300
    //this.activeTab = "Publications";
301
    //} else {
302
    //this.projectsClicked = true;
303
    //}
304
  }
305

    
306
  // private searchDatasets() {
307
  //   this.fetchDatasets.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
308
  //   this.linkToSearchPublications = this.properties.searchLinkToAdvancedDatasets;
309
  //   this.reloadDatasets = false;
310
  // }
311

    
312
  private searchDataproviders() {
313
    this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10, this.properties);
314
    this.linkToSearchDataproviders = this.properties.searchLinkToAdvancedDataProviders;
315

    
316
    //if(this.fetchDataproviders.searchUtils.totalResults > 0) {
317
    this.reloadDataproviders = false;
318
    //this.activeTab = "Content Providers";
319
    //} else {
320

    
321
    //}
322
  }
323

    
324
  public searchPublicationsInit() {
325
    if (this.reloadPublications && this.fetchPublications.searchUtils.totalResults > 0) {
326
      this.searchPublications();
327
    }
328
  }
329

    
330
  // public searchDatasetsInit() {
331
  //   if(this.reloadDatasets && this.fetchDatasets.searchUtils.totalResults > 0) {
332
  //     this.searchDatasets();
333
  //   }
334
  // }
335

    
336
  public searchDataprovidersInit() {
337
    if (this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
338
      this.searchDataproviders();
339
    }
340
  }
341

    
342
  public downloadFile(url: string, filename: string) {
343

    
344
    this.openLoading();
345
    this.setMessageLoading("Downloading CSV file");
346

    
347
    this.downloadFileSub = this._reportsService.downloadCSVFile(url).subscribe(
348
      data => {
349
        this.closeLoading();
350

    
351
        var url = window.URL.createObjectURL(data);
352
        var a = window.document.createElement('a');
353
        window.document.body.appendChild(a);
354
        a.setAttribute('style', 'display: none');
355
        a.href = url;
356
        a.download = filename + ".csv";
357
        a.click();
358
        window.URL.revokeObjectURL(url);
359
        a.remove(); // remove the element
360

    
361
        //window.open(window.URL.createObjectURL(data));
362
        if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
363
          this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url, this.piwikSiteId).subscribe();
364
        }
365
      },
366
      err => {
367
        //console.log("Error downloading the file.");
368
        this.handleError("Error downloading file: " + filename + ".csv", err);
369

    
370
        this.closeLoading();
371
        this.confirmOpenCsvError();
372
      }/*,
373
           () => console.log('Completed file download.')*/
374
    );
375
  }
376

    
377
  private downloadPublicationsFile(funder: string, funderId: string, count: number) {
378

    
379
    this.openLoading();
380
    this.setMessageLoading("Downloading CSV file");
381

    
382
    let response: string[] = [];
383
    let totalResponse: string = "";
384
    let projects = [];
385
    let counter: number = count;
386
    let title: boolean = false;
387
    let title_index: number = 0;
388

    
389
    let filename: string = 'funder-project-publications-report';
390

    
391
    this.countProjectsSub = this._searchProjectsService.getProjectsForOrganizations(this.organizationId, ' and (funder exact "' + funderId + '" ) ', 1, count, [], this.properties).subscribe(
392
      data => {
393
        projects = data[1];
394
        for (let index = 0; index < projects.length; index++) {
395
          this.countPublSub = this._searchResearchResultsService.numOfEntityResults("publication", projects[index].id, "project", this.properties).subscribe(
396
            data => {
397
              //if(data == 0 && title) {   // if no publications for this project
398
              if (data == 0 && (counter > 1 || title)) {   // if no publications for this project
399
                counter--;
400
                response[index] = "";
401
                //console.info("index: "+index, "counter: "+counter, "id:"+projects[index].id, response[index]);
402

    
403
                if (counter == 0) {
404
                  //for(let i=count-1; i>=0; i--) {
405
                  for (let i = 0; i < projects.length; i++) {
406
                    if (response[i] != "") {
407
                      if (i == title_index) {
408
                        totalResponse = response[i] + totalResponse;
409
                      } else {
410
                        totalResponse += response[i];
411
                      }
412
                    }
413
                  }
414
                  this.closeLoading();
415

    
416
                  var csvurl = window.URL.createObjectURL(new Blob([totalResponse], {type: 'text/csv'}));
417
                  var a = window.document.createElement('a');
418
                  window.document.body.appendChild(a);
419
                  a.setAttribute('style', 'display: none');
420
                  a.href = csvurl;
421
                  a.download = filename + ".csv";
422
                  a.click();
423
                  window.URL.revokeObjectURL(csvurl);
424
                  a.remove(); // remove the element
425
                }
426
              } else {
427
                let url: string;
428
                if (!title) {
429
                  title_index = index;
430
                  //console.info(title_index);
431
                  url = this.downloadURLAPI + "?format=csv-special&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact \"" + projects[index].id + "\"))"
432
                } else {
433
                  url = this.downloadURLAPI + "?format=csv-special-notitle&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact \"" + projects[index].id + "\"))"
434
                }
435
                title = true;
436

    
437
                this.downloadProjectPublSub = this._reportsService.getCSVResponse(url).subscribe(
438
                  data => {
439
                    counter--;
440
                    response[index] = data;
441
                    //console.info("index: "+index, "counter: "+counter, "id:"+projects[index].id, response[index]);
442

    
443
                    if (counter == 0) {
444
                      //for(let i=count-1; i>=0; i--) {
445
                      for (let i = 0; i < projects.length; i++) {
446
                        if (response[i] != "") {
447
                          if (i == title_index) {
448
                            totalResponse = response[i] + totalResponse;
449
                          } else {
450
                            totalResponse += response[i];
451
                          }
452
                        }
453
                      }
454
                      this.closeLoading();
455

    
456
                      var csvurl = window.URL.createObjectURL(new Blob([totalResponse], {type: 'text/csv'}));
457
                      var a = window.document.createElement('a');
458
                      window.document.body.appendChild(a);
459
                      a.setAttribute('style', 'display: none');
460
                      a.href = csvurl;
461
                      a.download = filename + ".csv";
462
                      a.click();
463
                      window.URL.revokeObjectURL(csvurl);
464
                      a.remove(); // remove the element
465
                    }
466
                  },
467
                  err => {
468
                    this.handleError("Error downloading file: " + filename, err);
469

    
470
                    this.closeLoading();
471
                    this.confirmOpenCsvError();
472
                  }/*,
473
                            () => console.log('Completed file download.')*/
474
                );
475
              }
476
            },
477
            err => {
478
              this.handleError("Error getting number of publications for project with id: " + projects[index].id, err);
479
            });
480
        }
481
      },
482
      err => {
483
        this.handleError("Error getting projects for organization with id: " + this.organizationId, err);
484

    
485
        this.closeLoading();
486
        this.confirmOpenCsvError();
487
      }
488
    );
489
  }
490

    
491
  private updateDescription(description: string) {
492
    this._meta.updateTag({content: description}, "name='description'");
493
    this._meta.updateTag({content: description}, "property='og:description'");
494
  }
495

    
496
  private updateTitle(title: string) {
497
    var _prefix = "";
498
    if(!this.communityId) {
499
      _prefix = "OpenAIRE | ";
500
    }
501
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
502
    this._title.setTitle(_title);
503
    this._meta.updateTag({content: _title}, "property='og:title'");
504
  }
505

    
506
  private updateUrl(url: string) {
507
    this._meta.updateTag({content: url}, "property='og:url'");
508
  }
509

    
510
  private openLoading() {
511
    if (this.loading) {
512
      this.loading.open();
513
    }
514
  }
515

    
516
  private closeLoading() {
517
    if (this.loading) {
518
      this.loading.close();
519
    }
520
  }
521

    
522
  private setMessageLoading(message: string) {
523
    if (this.loading) {
524
      this.loading.message = message;
525
    }
526
  }
527

    
528
  public confirmOpenApplyAll(funder: string, funderId: string, funderCountPublications: number) {
529
    this.alertApplyAll.cancelButton = true;
530
    this.alertApplyAll.okButton = true;
531
    this.alertApplyAll.alertTitle = "CSV FILE";
532
    this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
533
    this.alertApplyAll.okButtonText = "Yes";
534
    this.alertApplyAll.cancelButtonText = "No";
535
    this.alertApplyAll.open();
536

    
537
    this.funder = funder;
538
    this.funderId = funderId;
539
    this.funderCountPublications = funderCountPublications;
540
  }
541

    
542
  public confirmCloseApplyAll(data) {
543
    this.downloadPublicationsFile(this.funder, this.funderId, this.funderCountPublications);
544
  }
545

    
546
  public confirmOpenCsvError() {
547
    this.alertCsvError.cancelButton = false;
548
    this.alertCsvError.okButton = true;
549
    this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
550
    this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
551
    this.alertCsvError.okButtonText = "OK";
552
    this.alertCsvError.open();
553
  }
554

    
555
  encodeURI(input: string): string {
556
    return StringUtils.URIEncode(input);
557
  }
558

    
559
  private handleError(message: string, error) {
560
    console.error("Organizaton Landing Page: " + message, error);
561
  }
562

    
563
  openDeletedByInference() {
564
    this.deleteByInferenceOpened = true;
565
    this.alertModalDeletedByInference.cancelButton = false;
566
    this.alertModalDeletedByInference.okButton = false;
567
    this.alertModalDeletedByInference.alertTitle = "Original sources";
568
    this.alertModalDeletedByInference.open();
569
  }
570
}
(3-3/4)