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 {FetchPublications} from '../../utils/fetchEntitiesClasses/fetchPublications.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 {SearchPublicationsService} from '../../services/searchPublications.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: FetchPublications;
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
  //private ngUnsubscribe: Subject<void> = new Subject<void>();
104

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

    
120
    this.fetchPublications = new FetchPublications(this._searchPublicationsService);
121
    // this.fetchDatasets = new FetchDatasets(this._searchDatasetsService);
122
    this.fetchProjects = new FetchProjects(this._searchProjectsService);
123
    this.fetchDataproviders = new FetchDataproviders(this._searchDataprovidersService);
124
  }
125

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

    
140
      this.organizationId = params['organizationId'];
141

    
142
      if (this.organizationId) {
143
        this.getOrganizationInfo();
144
      } else {
145
        this.showLoading = false;
146
        this.warningMessage = "No valid organization id";
147
      }
148

    
149
      HelperFunctions.scroll();
150

    
151
      this.csvParamsTail = '" and relorganizationid exact "' + this.organizationId + '" ))';
152

    
153
    });
154

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

    
161
  private getPageContents() {
162
    this.helper.getPageHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
163
      this.pageContents = contents;
164
    })
165
  }
166

    
167
  private getDivContents() {
168
    this.helper.getDivHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
169
      this.divContents = contents;
170
    })
171
  }
172

    
173

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

    
200
    /*
201
    this.ngUnsubscribe.next();
202
    this.ngUnsubscribe.complete();
203
    */
204
  }
205

    
206
  private getOrganizationInfo() {
207

    
208
    this.warningMessage = '';
209
    this.errorMessage = ""
210
    this.showLoading = true;
211

    
212
    this.organizationInfo = null;
213

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

    
229
          //this.searchPublications();
230
          this.fetchPublications.getNumForEntity("organization", this.organizationId, this.properties);
231
          // this.fetchDatasets.getNumForEntity("organization", this.organizationId, this.properties);
232
          this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0, refineFields, this.properties);
233

    
234
          this.fetchDataproviders.getNumForEntity("organization", this.organizationId, this.properties);
235

    
236
          this.showLoading = false;
237

    
238
          /*let projectsNum = 0;
239

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

    
248
          this.projectsNum = projectsNum;*/
249
        }
250
      },
251
      err => {
252
        //console.log(err)
253
        this.handleError("Error getting organization for id: " + this.organizationId, err);
254
        this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.properties.searchLinkToOrganizations);
255
        this.errorMessage = 'No organization found';
256
        this.showLoading = false;
257
      }
258
    );
259
  }
260

    
261
  /*
262
      private handleClick(funder: string) {
263
           if(this.emptyFundersSet) {
264
               this.fundersSet.clear();
265
               this.emptyFundersSet = false;
266
           }
267

    
268
           if(this.fundersSet.has(funder)) {
269
               this.fundersSet.delete(funder);
270

    
271
               if(this.fundersSet.size == 0) {
272
                   this.organizationInfo.projects.forEach(function (value, key, map) {
273
                       this.fundersSet.add(key);
274
                   }.bind(this));
275
                   this.emptyFundersSet = true;
276
               }
277
               console.info(funder+" funder deleted");
278
           } else {
279
               this.fundersSet.add(funder);
280
               console.info(funder+" funder added");
281
           }
282
       }
283
  */
284
  //private getProjectsData(key: string): any {
285
  //return this.projectsData;
286
  //}
287

    
288
  private searchPublications() {
289
    this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10, this.properties);
290
    this.linkToSearchPublications = this.properties.searchLinkToAdvancedPublications;
291
    //if(this.fetchPublications.searchUtils.totalResults > 0) {
292
    this.reloadPublications = false;
293
    //this.activeTab = "Publications";
294
    //} else {
295
    //this.projectsClicked = true;
296
    //}
297
  }
298

    
299
  // private searchDatasets() {
300
  //   this.fetchDatasets.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
301
  //   this.linkToSearchPublications = this.properties.searchLinkToAdvancedDatasets;
302
  //   this.reloadDatasets = false;
303
  // }
304

    
305
  private searchDataproviders() {
306
    this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10, this.properties);
307
    this.linkToSearchDataproviders = this.properties.searchLinkToAdvancedDataProviders;
308

    
309
    //if(this.fetchDataproviders.searchUtils.totalResults > 0) {
310
    this.reloadDataproviders = false;
311
    //this.activeTab = "Content Providers";
312
    //} else {
313

    
314
    //}
315
  }
316

    
317
  public searchPublicationsInit() {
318
    if (this.reloadPublications && this.fetchPublications.searchUtils.totalResults > 0) {
319
      this.searchPublications();
320
    }
321
  }
322

    
323
  // public searchDatasetsInit() {
324
  //   if(this.reloadDatasets && this.fetchDatasets.searchUtils.totalResults > 0) {
325
  //     this.searchDatasets();
326
  //   }
327
  // }
328

    
329
  public searchDataprovidersInit() {
330
    if (this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
331
      this.searchDataproviders();
332
    }
333
  }
334

    
335
  public downloadFile(url: string, filename: string) {
336

    
337
    this.openLoading();
338
    this.setMessageLoading("Downloading CSV file");
339

    
340
    this.downloadFileSub = this._reportsService.downloadCSVFile(url).subscribe(
341
      data => {
342
        this.closeLoading();
343

    
344
        var url = window.URL.createObjectURL(data);
345
        var a = window.document.createElement('a');
346
        window.document.body.appendChild(a);
347
        a.setAttribute('style', 'display: none');
348
        a.href = url;
349
        a.download = filename + ".csv";
350
        a.click();
351
        window.URL.revokeObjectURL(url);
352
        a.remove(); // remove the element
353

    
354
        //window.open(window.URL.createObjectURL(data));
355
        if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
356
          this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url, this.piwikSiteId).subscribe();
357
        }
358
      },
359
      err => {
360
        //console.log("Error downloading the file.");
361
        this.handleError("Error downloading file: " + filename + ".csv", err);
362

    
363
        this.closeLoading();
364
        this.confirmOpenCsvError();
365
      }/*,
366
           () => console.log('Completed file download.')*/
367
    );
368
  }
369

    
370
  private downloadPublicationsFile(funder: string, funderId: string, count: number) {
371

    
372
    this.openLoading();
373
    this.setMessageLoading("Downloading CSV file");
374

    
375
    let response: string[] = [];
376
    let totalResponse: string = "";
377
    let projects = [];
378
    let counter: number = count;
379
    let title: boolean = false;
380
    let title_index: number = 0;
381

    
382
    let filename: string = 'funder-project-publications-report';
383

    
384
    this.countProjectsSub = this._searchProjectsService.getProjectsForOrganizations(this.organizationId, ' and (funder exact "' + funderId + '" ) ', 1, count, [], this.properties).subscribe(
385
      data => {
386
        projects = data[1];
387
        for (let index = 0; index < projects.length; index++) {
388
          this.countPublSub = this._searchPublicationsService.numOfEntityPublications(projects[index].id, "project", this.properties).subscribe(
389
            data => {
390
              //if(data == 0 && title) {   // if no publications for this project
391
              if (data == 0 && (counter > 1 || title)) {   // if no publications for this project
392
                counter--;
393
                response[index] = "";
394
                //console.info("index: "+index, "counter: "+counter, "id:"+projects[index].id, response[index]);
395

    
396
                if (counter == 0) {
397
                  //for(let i=count-1; i>=0; i--) {
398
                  for (let i = 0; i < projects.length; i++) {
399
                    if (response[i] != "") {
400
                      if (i == title_index) {
401
                        totalResponse = response[i] + totalResponse;
402
                      } else {
403
                        totalResponse += response[i];
404
                      }
405
                    }
406
                  }
407
                  this.closeLoading();
408

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

    
430
                this.downloadProjectPublSub = this._reportsService.getCSVResponse(url).subscribe(
431
                  data => {
432
                    counter--;
433
                    response[index] = data;
434
                    //console.info("index: "+index, "counter: "+counter, "id:"+projects[index].id, response[index]);
435

    
436
                    if (counter == 0) {
437
                      //for(let i=count-1; i>=0; i--) {
438
                      for (let i = 0; i < projects.length; i++) {
439
                        if (response[i] != "") {
440
                          if (i == title_index) {
441
                            totalResponse = response[i] + totalResponse;
442
                          } else {
443
                            totalResponse += response[i];
444
                          }
445
                        }
446
                      }
447
                      this.closeLoading();
448

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

    
463
                    this.closeLoading();
464
                    this.confirmOpenCsvError();
465
                  }/*,
466
                            () => console.log('Completed file download.')*/
467
                );
468
              }
469
            },
470
            err => {
471
              this.handleError("Error getting number of publications for project with id: " + projects[index].id, err);
472
            });
473
        }
474
      },
475
      err => {
476
        this.handleError("Error getting projects for organization with id: " + this.organizationId, err);
477

    
478
        this.closeLoading();
479
        this.confirmOpenCsvError();
480
      }
481
    );
482
  }
483

    
484
  private updateDescription(description: string) {
485
    this._meta.updateTag({content: description}, "name='description'");
486
    this._meta.updateTag({content: description}, "property='og:description'");
487
  }
488

    
489
  private updateTitle(title: string) {
490
    var _prefix = "OpenAIRE | ";
491
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
492
    this._title.setTitle(_title);
493
    this._meta.updateTag({content: _title}, "property='og:title'");
494
  }
495

    
496
  private updateUrl(url: string) {
497
    this._meta.updateTag({content: url}, "property='og:url'");
498
  }
499

    
500
  private openLoading() {
501
    if (this.loading) {
502
      this.loading.open();
503
    }
504
  }
505

    
506
  private closeLoading() {
507
    if (this.loading) {
508
      this.loading.close();
509
    }
510
  }
511

    
512
  private setMessageLoading(message: string) {
513
    if (this.loading) {
514
      this.loading.message = message;
515
    }
516
  }
517

    
518
  public confirmOpenApplyAll(funder: string, funderId: string, funderCountPublications: number) {
519
    this.alertApplyAll.cancelButton = true;
520
    this.alertApplyAll.okButton = true;
521
    this.alertApplyAll.alertTitle = "CSV FILE";
522
    this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
523
    this.alertApplyAll.okButtonText = "Yes";
524
    this.alertApplyAll.cancelButtonText = "No";
525
    this.alertApplyAll.open();
526

    
527
    this.funder = funder;
528
    this.funderId = funderId;
529
    this.funderCountPublications = funderCountPublications;
530
  }
531

    
532
  public confirmCloseApplyAll(data) {
533
    this.downloadPublicationsFile(this.funder, this.funderId, this.funderCountPublications);
534
  }
535

    
536
  public confirmOpenCsvError() {
537
    this.alertCsvError.cancelButton = false;
538
    this.alertCsvError.okButton = true;
539
    this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
540
    this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
541
    this.alertCsvError.okButtonText = "OK";
542
    this.alertCsvError.open();
543
  }
544

    
545
  encodeURI(input: string): string {
546
    return StringUtils.URIEncode(input);
547
  }
548

    
549
  private handleError(message: string, error) {
550
    console.error("Organizaton Landing Page: " + message, error);
551
  }
552
}
(3-3/4)