Project

General

Profile

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

    
6
import {Observable, Subject}                     from 'rxjs';
7

    
8
import {OrganizationService}            from '../../services/organization.service';
9
import {OrganizationInfo}               from '../../utils/entities/organizationInfo';
10
import {ReportsService}                 from '../../services/reports.service';
11
import {FetchPublications}              from '../../utils/fetchEntitiesClasses/fetchPublications.class';
12
// import {FetchDatasets}                  from '../../utils/fetchEntitiesClasses/fetchDatasets.class';
13
import {FetchProjects}                  from '../../utils/fetchEntitiesClasses/fetchProjects.class';
14
import {FetchDataproviders}             from '../../utils/fetchEntitiesClasses/fetchDataproviders.class';
15
import {SearchPublicationsService}      from '../../services/searchPublications.service';
16
// import {SearchDatasetsService}      from '../../services/searchDatasets.service';
17
import {SearchDataprovidersService}     from '../../services/searchDataproviders.service';
18
import {SearchProjectsService}          from '../../services/searchProjects.service';
19
import {ErrorCodes}                     from '../../utils/properties/errorCodes';
20
import {SearchingProjectsTabComponent}  from '../landing-utils/searchingProjectsInTab.component';
21
import {RouterHelper}                   from '../../utils/routerHelper.class';
22

    
23
import {ModalLoading}                   from '../../utils/modal/loading.component';
24
import {AlertModal}                     from '../../utils/modal/alert';
25
import {PiwikService}                   from '../../utils/piwik/piwik.service';
26
import {StringUtils}                    from '../../utils/string-utils.class';
27
import {EnvProperties}                  from '../../utils/properties/env-properties';
28
import { SEOService } from '../../sharedComponents/SEO/SEO.service';
29
import {HelperFunctions} from "../../utils/HelperFunctions.class";
30

    
31
@Component({
32
    selector: 'organization',
33
    templateUrl: 'organization.component.html',
34
})
35

    
36
export class OrganizationComponent {
37
  @Input() piwikSiteId = null;
38
    public organizationInfo: OrganizationInfo;
39
    public organizationId: string;
40

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

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

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

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

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

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

    
76
    public routerHelper:RouterHelper = new RouterHelper();
77
    public errorCodes:ErrorCodes = new ErrorCodes();
78

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

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

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

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

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

    
123
    ngOnInit() {
124
      this.route.data
125
        .subscribe((data: { envSpecific: EnvProperties }) => {
126
           this.properties = data.envSpecific;
127
           this.updateUrl(data.envSpecific.baseLink+this._router.url);
128
        });
129
        this.sub =  this.route.queryParams.subscribe(params => {
130
            this.organizationInfo=null;
131
            this.updateTitle("Organization");
132
            this.updateDescription("");
133
            this.projectsClicked = false;
134

    
135
            this.organizationId = params['organizationId'];
136

    
137
            if(this.organizationId){
138
                this.getOrganizationInfo();
139
            }else{
140
                this.showLoading = false;
141
                this.warningMessage="No valid organization id";
142
            }
143

    
144
          HelperFunctions.scroll();
145

    
146
          this.csvParamsTail = '" and relorganizationid exact "'+this.organizationId+'" ))';
147

    
148
        });
149

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

    
156

    
157
    ngOnDestroy() {
158
      if(this.sub){
159
        this.sub.unsubscribe();
160
      }
161
      if(this.piwiksub){
162
        this.piwiksub.unsubscribe();
163
      }
164
      if(this.infoSub) {
165
        this.infoSub.unsubscribe();
166
      }
167
      if(this.downloadFileSub) {
168
        this.downloadFileSub.unsubscribe();
169
      }
170
      if(this.downloadFilePiwikSub) {
171
        this.downloadFilePiwikSub.unsubscribe();
172
      }
173
      if(this.countProjectsSub) {
174
        this.countProjectsSub.unsubscribe();
175
      }
176
      if(this.countPublSub) {
177
        this.countPublSub.unsubscribe();
178
      }
179
      if(this.downloadProjectPublSub) {
180
        this.downloadProjectPublSub.unsubscribe();
181
      }
182

    
183
      /*
184
      this.ngUnsubscribe.next();
185
      this.ngUnsubscribe.complete();
186
      */
187
    }
188

    
189
    private getOrganizationInfo ()  {
190

    
191
        this.warningMessage = '';
192
        this.errorMessage=""
193
        this.showLoading = true;
194

    
195
        this.organizationInfo = null;
196

    
197
        this.infoSub = this._organizationService.getOrganizationInfo(this.organizationId, this.properties).subscribe(
198
            data => {
199
                if(data == null) {
200
                    this.showLoading = false;
201
                    this.errorMessage = 'No organization found';
202
                } else {
203
                    this.organizationInfo = data;
204
                  this.seoService.createLinkForCanonicalURL(this.properties.baseLink+this._router.url);
205
                  this.updateTitle(this.organizationInfo.title.name);
206
                    this.updateDescription("Organization, country, "+this.organizationInfo.title.name +((this.organizationInfo.title.name && this.organizationInfo.title.name != this.organizationInfo.name)?(", "+this.organizationInfo.name):"") );
207
                    if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
208
                      this.piwiksub = this._piwikService.trackView(this.properties, this.organizationInfo.title.name, this.piwikSiteId).subscribe();
209
                    }
210
                    var refineFields:string [] = ["funder"];
211

    
212
                    //this.searchPublications();
213
                    this.fetchPublications.getNumForEntity("organization", this.organizationId, this.properties);
214
                    // this.fetchDatasets.getNumForEntity("organization", this.organizationId, this.properties);
215
                    this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields,this.properties);
216

    
217
                    this.fetchDataproviders.getNumForEntity("organization", this.organizationId,this.properties);
218

    
219
                    this.showLoading = false;
220

    
221
                    /*let projectsNum = 0;
222

    
223
                    if(this.organizationInfo.projects != undefined) {
224
                         this.fundersSet = new Set<string>();
225
                        this.organizationInfo.projects.forEach(function (value, key, map) {
226
                            projectsNum += value.length;
227
                            this.fundersSet.add(key);
228
                        }.bind(this));
229
                    }
230

    
231
                    this.projectsNum = projectsNum;*/
232
                }
233
            },
234
            err => {
235
                //console.log(err)
236
                this.handleError("Error getting organization for id: "+this.organizationId, err);
237
                this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.properties.searchLinkToOrganizations);
238
                this.errorMessage = 'No organization found';
239
                this.showLoading = false;
240
            }
241
        );
242
    }
243

    
244
/*
245
    private handleClick(funder: string) {
246
         if(this.emptyFundersSet) {
247
             this.fundersSet.clear();
248
             this.emptyFundersSet = false;
249
         }
250

    
251
         if(this.fundersSet.has(funder)) {
252
             this.fundersSet.delete(funder);
253

    
254
             if(this.fundersSet.size == 0) {
255
                 this.organizationInfo.projects.forEach(function (value, key, map) {
256
                     this.fundersSet.add(key);
257
                 }.bind(this));
258
                 this.emptyFundersSet = true;
259
             }
260
             console.info(funder+" funder deleted");
261
         } else {
262
             this.fundersSet.add(funder);
263
             console.info(funder+" funder added");
264
         }
265
     }
266
*/
267
     //private getProjectsData(key: string): any {
268
         //return this.projectsData;
269
     //}
270

    
271
     private searchPublications() {
272
       this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
273
       this.linkToSearchPublications = this.properties.searchLinkToAdvancedPublications;
274
       //if(this.fetchPublications.searchUtils.totalResults > 0) {
275
         this.reloadPublications = false;
276
         //this.activeTab = "Publications";
277
       //} else {
278
         //this.projectsClicked = true;
279
       //}
280
     }
281

    
282
     // private searchDatasets() {
283
     //   this.fetchDatasets.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
284
     //   this.linkToSearchPublications = this.properties.searchLinkToAdvancedDatasets;
285
     //   this.reloadDatasets = false;
286
     // }
287

    
288
     private searchDataproviders() {
289
       this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
290
       this.linkToSearchDataproviders = this.properties.searchLinkToAdvancedDataProviders;
291

    
292
       //if(this.fetchDataproviders.searchUtils.totalResults > 0) {
293
         this.reloadDataproviders = false;
294
         //this.activeTab = "Content Providers";
295
       //} else {
296

    
297
       //}
298
     }
299

    
300
     public searchPublicationsInit() {
301
         if(this.reloadPublications && this.fetchPublications.searchUtils.totalResults > 0) {
302
             this.searchPublications();
303
         }
304
     }
305

    
306
     // public searchDatasetsInit() {
307
     //   if(this.reloadDatasets && this.fetchDatasets.searchUtils.totalResults > 0) {
308
     //     this.searchDatasets();
309
     //   }
310
     // }
311

    
312
     public searchDataprovidersInit() {
313
         if(this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
314
             this.searchDataproviders();
315
         }
316
     }
317

    
318
     public downloadFile(url:string, filename: string){
319

    
320
       this.openLoading();
321
       this.setMessageLoading("Downloading CSV file");
322

    
323
       this.downloadFileSub = this._reportsService.downloadCSVFile(url).subscribe(
324
           data => {
325
               this.closeLoading();
326

    
327
               var url = window.URL.createObjectURL(data);
328
               var a = window.document.createElement('a');
329
               window.document.body.appendChild(a);
330
               a.setAttribute('style', 'display: none');
331
               a.href = url;
332
               a.download = filename+".csv";
333
               a.click();
334
               window.URL.revokeObjectURL(url);
335
               a.remove(); // remove the element
336

    
337
               //window.open(window.URL.createObjectURL(data));
338
                if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
339
                  this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url, this.piwikSiteId).subscribe();
340
                }
341
           },
342
           err => {
343
             //console.log("Error downloading the file.");
344
             this.handleError("Error downloading file: "+filename+".csv", err);
345

    
346
             this.closeLoading();
347
             this.confirmOpenCsvError();
348
           }/*,
349
           () => console.log('Completed file download.')*/
350
         );
351
     }
352

    
353
     private downloadPublicationsFile(funder: string, funderId:string, count:number){
354

    
355
       this.openLoading();
356
       this.setMessageLoading("Downloading CSV file");
357

    
358
       let response: string[] = [];
359
       let totalResponse: string = "";
360
       let projects = [];
361
       let counter: number = count;
362
       let title: boolean = false;
363

    
364
       let filename: string = 'funder-project-publications-report';
365

    
366
       this.countProjectsSub = this._searchProjectsService.getProjectsForOrganizations(this.organizationId,' and (funder exact "'+ funderId + '" ) ',1,count,[], this.properties).subscribe(
367
           data =>
368
               {
369
                 projects = data[1];
370
                  for(let index=0; index < projects.length; index++) {
371
                      this.countPublSub = this._searchPublicationsService.numOfEntityPublications(projects[index].id, "project", this.properties).subscribe(
372
                          data =>
373
                              {
374
                                  // let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
375

    
376
                                  let url: string;
377
                                  if(!title) {
378
                                      //url = this.downloadURLAPI+"projects/"+projects[index].id+"?type=publications&format=csv-special";//&size="+data;
379
                                      url = this.downloadURLAPI+"?format=csv-special&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact \""+projects[index].id+"\"))"
380
                                  } else {
381
                                      //url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle";//&size="+data;
382
                                      url = this.downloadURLAPI+"?format=csv-special-notitle&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact \""+projects[index].id+"\"))"
383
                                  }
384

    
385
                                  if(data == 0 && (counter > 1 || title)) {   // if no publications for this project
386
                                      counter--;
387
                                      response[index] = "";
388
                                      if(counter == 0) {
389
                                          for(let i=0; i<count; i++) {
390
                                              if(response[i] != "") {
391
                                                  totalResponse += response[i];
392
                                              }
393
                                          }
394
                                          this.closeLoading();
395

    
396
                                          var csvurl = window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' }));
397
                                          var a = window.document.createElement('a');
398
                                          window.document.body.appendChild(a);
399
                                          a.setAttribute('style', 'display: none');
400
                                          a.href = csvurl;
401
                                          a.download = filename+".csv";
402
                                          a.click();
403
                                          window.URL.revokeObjectURL(csvurl);
404
                                          a.remove(); // remove the element
405

    
406
                                          //window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
407
                                          // if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
408
                                          //   this._piwikService.trackDownload(this.properties, url).subscribe();
409
                                          // }
410
                                      }
411
                                  } else {
412
                                      title = true;
413

    
414
                                      this.downloadProjectPublSub = this._reportsService.getCSVResponse(url).subscribe(
415
                                          data =>
416
                                              {
417
                                                  counter--;
418
                                                  response[index] = data;
419

    
420
                                                  if(counter == 0) {
421
                                                      for(let i=0; i<count; i++) {
422
                                                          if(response[i] != "") {
423
                                                              totalResponse += response[i];
424
                                                          }
425
                                                      }
426
                                                      this.closeLoading();
427

    
428
                                                      var csvurl = window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' }));
429
                                                      var a = window.document.createElement('a');
430
                                                      window.document.body.appendChild(a);
431
                                                      a.setAttribute('style', 'display: none');
432
                                                      a.href = csvurl;
433
                                                      a.download = filename+".csv";
434
                                                      a.click();
435
                                                      window.URL.revokeObjectURL(csvurl);
436
                                                      a.remove(); // remove the element
437

    
438
                                                      //window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
439
                                                      // if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
440
                                                      //   this._piwikService.trackDownload(this.properties, url).subscribe();
441
                                                      // }
442
                                                  }
443
                                              },
444
                                          err => {
445
                                            //console.log("Error downloading the file.");
446
                                            this.handleError("Error downloading file: "+filename, err);
447

    
448
                                            this.closeLoading();
449
                                            this.confirmOpenCsvError();
450
                                          }/*,
451
                                          () => console.log('Completed file download.')*/
452
                                      );
453
                                  }
454
                              },
455
                          err => {
456
                            //console.log("Error getting number of publications for project.")
457
                            this.handleError("Error getting number of publications for project with id: "+projects[index].id, err);
458
                          });
459
                  }//);
460

    
461
               },
462
          err => {
463
            //console.log("Error getting projects project.");
464
            this.handleError("Error getting projects for organization with id: "+this.organizationId, err);
465

    
466
            this.closeLoading();
467
            this.confirmOpenCsvError();
468
          }
469
        );
470

    
471
      //  let counter: number = this.organizationInfo.projects.get(funder).length;
472
       //
473
      //  for(let project of this.organizationInfo.projects.get(funder)) {
474
      //       this._searchPublicationsService.numOfEntityPublications(project.id, "projects/").subscribe(
475
      //           data =>
476
      //               {
477
      //                   let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
478
       //
479
      //                   let url: string;
480
      //                   if(index == 0) {
481
      //                       url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special&size="+data;
482
      //                   } else {
483
      //                       url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special-notitle&size="+data;
484
      //                   }
485
       //
486
      //                   this._reportsService.getCSVResponse(url).subscribe(
487
      //                       data =>
488
      //                           {
489
      //                               counter--;
490
       //
491
      //                               response[index] = data;
492
       //
493
      //                               if(counter == 0) {
494
      //                                   for(let i=0; i<this.organizationInfo.projects.get(funder).length; i++) {
495
      //                                       totalResponse += response[i]+"\n";
496
      //                                   }
497
      //                                   window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
498
      //                               }
499
      //                           },
500
      //                       error => console.log("Error downloading the file."),
501
      //                       () => console.log('Completed file download.'));
502
      //               },
503
      //           error => console.log("Error getting number of publications for project."));
504
        // }//);
505
    }
506

    
507
    private updateDescription(description:string) {
508
      this._meta.updateTag({content:description},"name='description'");
509
      this._meta.updateTag({content:description},"property='og:description'");
510
    }
511
    private updateTitle(title:string){
512
      var _prefix ="OpenAIRE | ";
513
      var _title = _prefix + ((title.length> 50 ) ?title.substring(0,50):title);
514
      this._title.setTitle(_title);
515
      this._meta.updateTag({content:_title},"property='og:title'");
516
    }
517
    private updateUrl(url:string){
518
      this._meta.updateTag({content:url},"property='og:url'");
519
    }
520

    
521
    private openLoading(){
522
      if(this.loading){
523
        this.loading.open();
524
      }
525
    }
526
    private closeLoading(){
527
      if(this.loading){
528
        this.loading.close();
529
      }
530
    }
531
    private setMessageLoading(message: string){
532
      if(this.loading){
533
        this.loading.message = message;
534
      }
535
    }
536

    
537
    public confirmOpenApplyAll(funder: string, funderId:string, funderCountPublications:number){
538
      this.alertApplyAll.cancelButton = true;
539
      this.alertApplyAll.okButton = true;
540
      this.alertApplyAll.alertTitle = "CSV FILE";
541
      this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
542
      this.alertApplyAll.okButtonText = "Yes";
543
      this.alertApplyAll.cancelButtonText = "No";
544
      this.alertApplyAll.open();
545

    
546
      this.funder = funder;
547
      this.funderId = funderId;
548
      this.funderCountPublications = funderCountPublications;
549
    }
550
    public confirmCloseApplyAll(data){
551
         this.downloadPublicationsFile(this.funder, this.funderId, this.funderCountPublications);
552
    }
553

    
554
    public confirmOpenCsvError(){
555
      this.alertCsvError.cancelButton = false;
556
      this.alertCsvError.okButton = true;
557
      this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
558
      this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
559
      this.alertCsvError.okButtonText = "OK";
560
      this.alertCsvError.open();
561
    }
562

    
563
    encodeURI(input: string): string {
564
      return StringUtils.URIEncode(input);
565
    }
566

    
567
    private handleError(message: string, error) {
568
        console.error("Organizaton Landing Page: "+message, error);
569
    }
570
}
(3-3/4)