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}                     from 'rxjs/Observable';
7
import {Subject}                        from 'rxjs/Subject';
8

    
9
import {OrganizationService}            from '../../services/organization.service';
10
import {OrganizationInfo}               from '../../utils/entities/organizationInfo';
11
import {ReportsService}                 from '../../services/reports.service';
12
import {FetchPublications}              from '../../utils/fetchEntitiesClasses/fetchPublications.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 {SearchDataprovidersService}     from '../../services/searchDataproviders.service';
17
import {SearchProjectsService}          from '../../services/searchProjects.service';
18
import {ErrorCodes}                     from '../../utils/properties/errorCodes';
19
import {SearchingProjectsTabComponent}  from '../landing-utils/searchingProjectsInTab.component';
20
import {RouterHelper}                   from '../../utils/routerHelper.class';
21

    
22
import {ModalLoading}                   from '../../utils/modal/loading.component';
23
import {AlertModal}                     from '../../utils/modal/alert';
24
import {PiwikService}                   from '../../utils/piwik/piwik.service';
25
import {StringUtils}                    from '../../utils/string-utils.class';
26
import {EnvProperties}                  from '../../utils/properties/env-properties';
27

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

    
33
export class OrganizationComponent {
34
  @Input() piwikSiteId = null;
35
    public organizationInfo: OrganizationInfo;
36
    public organizationId: string;
37

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

    
43
    // CSV variables
44
    public downloadURLAPI: string;
45
    public csvProjectParamsHead: string;
46
    public csvPublicationParamsHead: string;
47
    public csvParamsTail: string;
48

    
49
    // Active tab variable for responsiveness
50
    public activeTab: string = "Publications";
51

    
52
    // Variables for publications, projects, dataproviders tabs
53
    public fetchPublications: FetchPublications;
54
    public linkToSearchPublications: string = "";
55
    public fetchProjects: FetchProjects;
56
    public fetchDataproviders : FetchDataproviders;
57
    public linkToSearchDataproviders:string = "";
58
    //public projectFunders:string[] = [];
59

    
60
    // Variables for projects query (query results only if projects tab is clicked)
61
    public projectsClicked: boolean = false;
62
    @ViewChild (SearchingProjectsTabComponent) searchingProjectsTabComponent : SearchingProjectsTabComponent ;
63

    
64
    @ViewChild (ModalLoading) loading : ModalLoading ;
65
    // Alert box when CSV: Project Publications for a funder is requested
66
    @ViewChild('AlertModalApplyAll') alertApplyAll;
67
    // Alert box when something is wrong with CSV requests
68
    @ViewChild('AlertModalCsvError') alertCsvError;
69

    
70
    public routerHelper:RouterHelper = new RouterHelper();
71
    public errorCodes:ErrorCodes = new ErrorCodes();
72

    
73
    //private projectsNum: number = 0;
74
    //private fundersSet: Set<string>;
75
    //private emptyFundersSet: boolean = true;
76

    
77
    // Request results for content providers only the one time (first time tab is clicked)
78
    private reloadDataproviders: boolean = true;
79

    
80
    // Helper variables to specify funder in downloadPublicationsFile function
81
    private funder: string;
82
    private funderId: string;
83
    private funderCountPublications: number;
84
    sub: any;
85
    infoSub: any;
86
    piwiksub: any;
87
    downloadFileSub: any;
88
    downloadFilePiwikSub: any;
89
    countProjectsSub: any;
90
    countPublSub: any;
91
    downloadProjectPublSub: any;
92
    properties:EnvProperties;
93
    //private ngUnsubscribe: Subject<void> = new Subject<void>();
94

    
95
    constructor (private element: ElementRef,
96
                 private _organizationService: OrganizationService,
97
                 private _piwikService:PiwikService,
98
                 private  route: ActivatedRoute,
99
                 private _searchDataprovidersService: SearchDataprovidersService,
100
                 private _reportsService: ReportsService,
101
                 private _searchPublicationsService: SearchPublicationsService,
102
                 private _searchProjectsService: SearchProjectsService,
103
                 private _meta: Meta,
104
                 private _title: Title,
105
                 private _router: Router) {
106

    
107
            this.fetchPublications = new FetchPublications(this._searchPublicationsService);
108
            this.fetchProjects = new FetchProjects(this._searchProjectsService);
109
            this.fetchDataproviders = new FetchDataproviders(this._searchDataprovidersService);
110
    }
111

    
112
    ngOnInit() {
113
      this.route.data
114
        .subscribe((data: { envSpecific: EnvProperties }) => {
115
           this.properties = data.envSpecific;
116
           this.updateUrl(data.envSpecific.baseLink+this._router.url);
117

    
118
        });
119
        console.info('organization init');
120
        this.sub =  this.route.queryParams.subscribe(params => {
121
            this.organizationInfo=null;
122
            this.updateTitle("Organization");
123
            this.updateDescription("Organization, country, projects,  search, repositories, open access");
124
            this.projectsClicked = false;
125

    
126
            this.organizationId = params['organizationId'];
127
            console.info("Id is :"+this.organizationId);
128

    
129
            if(this.organizationId){
130
                this.getOrganizationInfo();
131
            }else{
132
                this.showLoading = false;
133
                this.warningMessage="No valid organization id";
134
            }
135

    
136
            if (typeof document !== 'undefined') {
137
               this.element.nativeElement.scrollIntoView();
138
            }
139

    
140
            this.csvParamsTail = '" and relorganizationid exact "'+this.organizationId+'" ))';
141

    
142
        });
143

    
144
        this.downloadURLAPI =this.properties.csvAPIURL;
145
        this.csvProjectParamsHead = 'format=csv&type=projects&fq=( (oaftype exact project)and (funder exact "';
146
        //this.csvPublicationParamsHead = 'format=csv-special&type=publications&page=0&query=((((oaftype exact result) and (resulttypeid exact publication)) and (funderid exact ';
147
    }
148

    
149

    
150
    ngOnDestroy() {
151
      this.sub.unsubscribe();
152
      if(this.piwiksub){
153
        this.piwiksub.unsubscribe();
154
      }
155
      if(this.infoSub) {
156
        this.infoSub.unsubscribe();
157
      }
158
      if(this.downloadFileSub) {
159
        this.downloadFileSub.unsubscribe();
160
      }
161
      if(this.downloadFilePiwikSub) {
162
        this.downloadFilePiwikSub.unsubscribe();
163
      }
164
      if(this.countProjectsSub) {
165
        this.countProjectsSub.unsubscribe();
166
      }
167
      if(this.countPublSub) {
168
        this.countPublSub.unsubscribe();
169
      }
170
      if(this.downloadProjectPublSub) {
171
        this.downloadProjectPublSub.unsubscribe();
172
      }
173

    
174
      /*
175
      this.ngUnsubscribe.next();
176
      this.ngUnsubscribe.complete();
177
      */
178
    }
179

    
180
    private getOrganizationInfo ()  {
181

    
182
        this.warningMessage = '';
183
        this.errorMessage=""
184
        this.showLoading = true;
185

    
186
        this.infoSub = this._organizationService.getOrganizationInfo(this.organizationId, this.properties).subscribe(
187
            data => {
188
                if(data == null) {
189
                    this.showLoading = false;
190
                    this.errorMessage = 'No organization found';
191
                } else {
192
                    this.organizationInfo = data;
193
                    this.updateTitle(this.organizationInfo.title.name);
194
                    this.updateDescription("Organization, country, projects,  search, repositories, open access"+this.organizationInfo.title.name);
195
                    if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
196
                      this.piwiksub = this._piwikService.trackView(this.properties, this.organizationInfo.title.name, this.piwikSiteId).subscribe();
197
                    }
198
                    var refineFields:string [] = ["funder"];
199

    
200
                    this.searchPublications();
201

    
202
                     this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields,this.properties);
203

    
204
                    this.fetchDataproviders.getNumForEntity("organization", this.organizationId,this.properties);
205

    
206
                    this.showLoading = false;
207

    
208
                    /*let projectsNum = 0;
209

    
210
                    if(this.organizationInfo.projects != undefined) {
211
                         this.fundersSet = new Set<string>();
212
                        this.organizationInfo.projects.forEach(function (value, key, map) {
213
                            projectsNum += value.length;
214
                            this.fundersSet.add(key);
215
                        }.bind(this));
216
                    }
217

    
218
                    this.projectsNum = projectsNum;*/
219
                }
220
            },
221
            err => {
222
                console.log(err)
223

    
224
                this.errorMessage = 'No organization found';
225
                this.showLoading = false;
226
            }
227
        );
228
    }
229

    
230
/*
231
    private handleClick(funder: string) {
232
         if(this.emptyFundersSet) {
233
             this.fundersSet.clear();
234
             this.emptyFundersSet = false;
235
         }
236

    
237
         if(this.fundersSet.has(funder)) {
238
             this.fundersSet.delete(funder);
239

    
240
             if(this.fundersSet.size == 0) {
241
                 this.organizationInfo.projects.forEach(function (value, key, map) {
242
                     this.fundersSet.add(key);
243
                 }.bind(this));
244
                 this.emptyFundersSet = true;
245
             }
246
             console.info(funder+" funder deleted");
247
         } else {
248
             this.fundersSet.add(funder);
249
             console.info(funder+" funder added");
250
         }
251
     }
252
*/
253
     //private getProjectsData(key: string): any {
254
         //return this.projectsData;
255
     //}
256

    
257
     private searchPublications() {
258
       this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
259
       this.linkToSearchPublications = this.properties.searchLinkToAdvancedPublications;
260
       if(this.fetchPublications.searchUtils.totalResults > 0) {
261
         //this.activeTab = "Publications";
262
       } else {
263
         //this.projectsClicked = true;
264
       }
265
     }
266

    
267
     private searchDataproviders() {
268
       this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
269
       this.linkToSearchDataproviders = this.properties.searchLinkToAdvancedDataProviders;
270

    
271
       if(this.fetchDataproviders.searchUtils.totalResults > 0) {
272
         this.reloadDataproviders = false;
273
         //this.activeTab = "Content Providers";
274
       } else {
275

    
276
       }
277
     }
278

    
279
     public searchDataprovidersInit() {
280
         if(this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
281
             this.searchDataproviders();
282
         }
283
     }
284

    
285
     public downloadFile(url:string){
286
       console.log("Downloading file: "+ url);
287

    
288
       this.openLoading();
289
       this.setMessageLoading("Downloading CSV file");
290

    
291
       this.downloadFileSub = this._reportsService.downloadCSVFile(url).subscribe(
292
           data => {
293
               this.closeLoading();
294
               window.open(window.URL.createObjectURL(data));
295
                if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
296
                  this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url, this.piwikSiteId).subscribe();
297
                }
298
           },
299
           err => {
300
             console.log("Error downloading the file.");
301
             this.closeLoading();
302
             this.confirmOpenCsvError();
303
           },
304
           () => console.log('Completed file download.'));
305
     }
306

    
307
     private downloadPublicationsFile(funder: string, funderId:string, count:number){
308
       console.log("Downloading publications file");
309

    
310
       this.openLoading();
311
       this.setMessageLoading("Downloading CSV file");
312

    
313
       let response: string[] = [];
314
       let totalResponse: string = "";
315
       let projects = [];
316
       let counter: number = count;
317
       let title: boolean = false;
318

    
319
       this.countProjectsSub = this._searchProjectsService.getProjectsForOrganizations(this.organizationId,' and (funder exact "'+ funderId + '" ) ',1,count,[], this.properties).subscribe(
320
           data =>
321
               {
322
                 projects = data[1];
323
                  for(let index=0; index < projects.length; index++) {
324
                      this.countPublSub = this._searchPublicationsService.numOfEntityPublications(projects[index].id, "project", this.properties).subscribe(
325
                          data =>
326
                              {
327
                                  // let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
328

    
329
                                  let url: string;
330
                                  if(!title) {
331
                                      //url = this.downloadURLAPI+"projects/"+projects[index].id+"?type=publications&format=csv-special";//&size="+data;
332
                                      url = this.downloadURLAPI+"?format=csv-special&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact '"+projects[index].id+"'))"
333
                                      console.info(url);
334
                                  } else {
335
                                      //url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle";//&size="+data;
336
                                      url = this.downloadURLAPI+"?format=csv-special-notitle&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact '"+projects[index].id+"'))"
337
                                  }
338

    
339
                                  if(data == 0 && (counter > 1 || title)) {   // if no publications for this project
340
                                      counter--;
341
                                      response[index] = "";
342
                                      if(counter == 0) {
343
                                          for(let i=0; i<count; i++) {
344
                                              if(response[i] != "") {
345
                                                  totalResponse += response[i];
346
                                              }
347
                                          }
348
                                          this.closeLoading();
349
                                          window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
350
                                          // if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
351
                                          //   this._piwikService.trackDownload(this.properties, url).subscribe();
352
                                          // }
353
                                      }
354
                                  } else {
355
                                      title = true;
356

    
357
                                      this.downloadProjectPublSub = this._reportsService.getCSVResponse(url).subscribe(
358
                                          data =>
359
                                              {
360
                                                  counter--;
361
                                                  response[index] = data;
362

    
363
                                                  if(counter == 0) {
364
                                                      for(let i=0; i<count; i++) {
365
                                                          if(response[i] != "") {
366
                                                              totalResponse += response[i];
367
                                                          }
368
                                                      }
369
                                                      this.closeLoading();
370
                                                      window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
371
                                                      // if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
372
                                                      //   this._piwikService.trackDownload(this.properties, url).subscribe();
373
                                                      // }
374
                                                  }
375
                                              },
376
                                          err => {
377
                                            console.log("Error downloading the file.");
378
                                            this.closeLoading();
379
                                            this.confirmOpenCsvError();
380
                                          },
381
                                          () => console.log('Completed file download.')
382
                                      );
383
                                  }
384
                              },
385
                          err => console.log("Error getting number of publications for project."));
386
                  }//);
387

    
388
               },
389
           err => {
390
            console.log("Error getting projects project.");
391
            this.closeLoading();
392
            this.confirmOpenCsvError();
393
          }
394
        );
395

    
396
      //  let counter: number = this.organizationInfo.projects.get(funder).length;
397
       //
398
      //  for(let project of this.organizationInfo.projects.get(funder)) {
399
      //       this._searchPublicationsService.numOfEntityPublications(project.id, "projects/").subscribe(
400
      //           data =>
401
      //               {
402
      //                   let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
403
       //
404
      //                   let url: string;
405
      //                   if(index == 0) {
406
      //                       url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special&size="+data;
407
      //                   } else {
408
      //                       url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special-notitle&size="+data;
409
      //                   }
410
       //
411
      //                   this._reportsService.getCSVResponse(url).subscribe(
412
      //                       data =>
413
      //                           {
414
      //                               counter--;
415
       //
416
      //                               response[index] = data;
417
       //
418
      //                               if(counter == 0) {
419
      //                                   for(let i=0; i<this.organizationInfo.projects.get(funder).length; i++) {
420
      //                                       totalResponse += response[i]+"\n";
421
      //                                   }
422
      //                                   window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
423
      //                               }
424
      //                           },
425
      //                       error => console.log("Error downloading the file."),
426
      //                       () => console.log('Completed file download.'));
427
      //               },
428
      //           error => console.log("Error getting number of publications for project."));
429
        // }//);
430
    }
431

    
432
    private updateDescription(description:string) {
433
      this._meta.updateTag({content:description},"name='description'");
434
      this._meta.updateTag({content:description},"property='og:description'");
435
    }
436
    private updateTitle(title:string){
437
      var _prefix ="OpenAIRE | ";
438
      var _title = _prefix + ((title.length> 50 ) ?title.substring(0,50):title);
439
      this._title.setTitle(_title);
440
      this._meta.updateTag({content:_title},"property='og:title'");
441
    }
442
    private updateUrl(url:string){
443
      this._meta.updateTag({content:url},"property='og:url'");
444
    }
445

    
446
    private openLoading(){
447
      if(this.loading){
448
        this.loading.open();
449
      }
450
    }
451
    private closeLoading(){
452
      if(this.loading){
453
        this.loading.close();
454
      }
455
    }
456
    private setMessageLoading(message: string){
457
      if(this.loading){
458
        this.loading.message = message;
459
      }
460
    }
461

    
462
    public confirmOpenApplyAll(funder: string, funderId:string, funderCountPublications:number){
463
      this.alertApplyAll.cancelButton = true;
464
      this.alertApplyAll.okButton = true;
465
      this.alertApplyAll.alertTitle = "CSV FILE";
466
      this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
467
      this.alertApplyAll.okButtonText = "Yes";
468
      this.alertApplyAll.cancelButtonText = "No";
469
      this.alertApplyAll.open();
470

    
471
      this.funder = funder;
472
      this.funderId = funderId;
473
      this.funderCountPublications = funderCountPublications;
474
    }
475
    public confirmCloseApplyAll(data){
476
         this.downloadPublicationsFile(this.funder, this.funderId, this.funderCountPublications);
477
    }
478

    
479
    public confirmOpenCsvError(){
480
      this.alertCsvError.cancelButton = false;
481
      this.alertCsvError.okButton = true;
482
      this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
483
      this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
484
      this.alertCsvError.okButtonText = "OK";
485
      this.alertCsvError.open();
486
    }
487

    
488
    encodeURI(input: string): string {
489
      return StringUtils.URIEncode(input);
490
    }
491
}
(3-3/4)