Project

General

Profile

1
import {Component, ViewChild, ElementRef} from '@angular/core';
2
import {Observable}       from 'rxjs/Observable';
3
import {Subject} from 'rxjs/Subject';
4
import {ActivatedRoute, Router} from '@angular/router';
5

    
6
import {OrganizationService} from '../../services/organization.service';
7
import {OrganizationInfo} from '../../utils/entities/organizationInfo';
8
import {ReportsService} from '../../services/reports.service';
9
import {FetchPublications} from '../../utils/fetchEntitiesClasses/fetchPublications.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 {SearchDataprovidersService} from '../../services/searchDataproviders.service';
14
import {SearchProjectsService} from '../../services/searchProjects.service';
15
import { Meta} from '../../../angular2-meta';
16
import {OpenaireProperties, ErrorCodes} from '../../utils/properties/openaireProperties';
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 {AlertModal} from '../../utils/modal/alert';
22
import {PiwikService} from '../../utils/piwik/piwik.service';
23
import {StringUtils} from '../../utils/string-utils.class';
24

    
25
@Component({
26
    selector: 'organization',
27
    templateUrl: 'organization.component.html',
28
})
29

    
30
export class OrganizationComponent {
31
    public organizationInfo: OrganizationInfo;
32
    public organizationId: string;
33

    
34
    // Message variables
35
    public warningMessage = "";
36
    public errorMessage = "";
37
    public showLoading: boolean = true;
38

    
39
    // CSV variables
40
    public downloadURLAPI: string;
41
    public csvProjectParamsHead: string;
42
    public csvPublicationParamsHead: string;
43
    public csvParamsTail: string;
44

    
45
    // Active tab variable for responsiveness
46
    public activeTab: string = "Publications";
47

    
48
    // Variables for publications, projects, dataproviders tabs
49
    public fetchPublications: FetchPublications;
50
    public linkToSearchPublications: string = "";
51
    public fetchProjects: FetchProjects;
52
    public fetchDataproviders : FetchDataproviders;
53
    public linkToSearchDataproviders:string = "";
54
    //public projectFunders:string[] = [];
55

    
56
    // Variables for projects query (query results only if projects tab is clicked)
57
    public projectsClicked: boolean = false;
58
    @ViewChild (SearchingProjectsTabComponent) searchingProjectsTabComponent : SearchingProjectsTabComponent ;
59

    
60
    @ViewChild (ModalLoading) loading : ModalLoading ;
61
    // Alert box when CSV: Project Publications for a funder is requested
62
    @ViewChild('AlertModalApplyAll') alertApplyAll;
63
    // Alert box when something is wrong with CSV requests
64
    @ViewChild('AlertModalCsvError') alertCsvError;
65

    
66
    public routerHelper:RouterHelper = new RouterHelper();
67
    public errorCodes:ErrorCodes = new ErrorCodes();
68

    
69
    //private projectsNum: number = 0;
70
    //private fundersSet: Set<string>;
71
    //private emptyFundersSet: boolean = true;
72

    
73
    // Request results for content providers only the one time (first time tab is clicked)
74
    private reloadDataproviders: boolean = true;
75

    
76
    // Helper variables to specify funder in downloadPublicationsFile function
77
    private funder: string;
78
    private funderId: string;
79
    private funderCountPublications: number;
80
    sub: any;
81
    infoSub: any;
82
    piwiksub: any;
83
    downloadFileSub: any;
84
    downloadFilePiwikSub: any;
85
    countProjectsSub: any;
86
    countPublSub: any;
87
    downloadProjectPublSub: any;
88

    
89
    //private ngUnsubscribe: Subject<void> = new Subject<void>();
90

    
91
    constructor (private element: ElementRef,
92
                 private _organizationService: OrganizationService,
93
                 private _piwikService:PiwikService,
94
                 private  route: ActivatedRoute,
95
                 private _searchDataprovidersService: SearchDataprovidersService,
96
                 private _reportsService: ReportsService,
97
                 private _searchPublicationsService: SearchPublicationsService,
98
                 private _searchProjectsService: SearchProjectsService, private _meta: Meta,
99
                 private _router: Router) {
100

    
101
            this.fetchPublications = new FetchPublications(this._searchPublicationsService);
102
            this.fetchProjects = new FetchProjects(this._searchProjectsService);
103
            this.fetchDataproviders = new FetchDataproviders(this._searchDataprovidersService);
104
            this.updateUrl(OpenaireProperties.getBaseLink()+this._router.url);
105
    }
106

    
107
    ngOnInit() {
108
        console.info('organization init');
109
        this.sub =  this.route.queryParams.subscribe(params => {
110
            this.organizationInfo=null;
111
            this.updateTitle("Organization");
112
            this.updateDescription("Organization, country, projects,  search, repositories, open access");
113
            this.projectsClicked = false;
114

    
115
            this.organizationId = params['organizationId'];
116
            console.info("Id is :"+this.organizationId);
117

    
118
            if(this.organizationId){
119
                this.getOrganizationInfo();
120
            }else{
121
                this.showLoading = false;
122
                this.warningMessage="No valid organization id";
123
            }
124

    
125
            if (typeof document !== 'undefined') {
126
               this.element.nativeElement.scrollIntoView();
127
            }
128

    
129
            this.csvParamsTail = '" and relorganizationid exact "'+this.organizationId+'" ))';
130

    
131
        });
132

    
133
        this.downloadURLAPI = OpenaireProperties.getCsvAPIURL();
134
        this.csvProjectParamsHead = 'format=csv&type=projects&page=0&query=( (oaftype exact project)and (funder exact "';
135
        //this.csvPublicationParamsHead = 'format=csv-special&type=publications&page=0&query=((((oaftype exact result) and (resulttypeid exact publication)) and (funderid exact ';
136
    }
137

    
138

    
139
    ngOnDestroy() {
140
      this.sub.unsubscribe();
141
      if(this.piwiksub){
142
        this.piwiksub.unsubscribe();
143
      }
144
      if(this.infoSub) {
145
        this.infoSub.unsubscribe();
146
      }
147
      if(this.downloadFileSub) {
148
        this.downloadFileSub.unsubscribe();
149
      }
150
      if(this.downloadFilePiwikSub) {
151
        this.downloadFilePiwikSub.unsubscribe();
152
      }
153
      if(this.countProjectsSub) {
154
        this.countProjectsSub.unsubscribe();
155
      }
156
      if(this.countPublSub) {
157
        this.countPublSub.unsubscribe();
158
      }
159
      if(this.downloadProjectPublSub) {
160
        this.downloadProjectPublSub.unsubscribe();
161
      }
162

    
163
      /*
164
      this.ngUnsubscribe.next();
165
      this.ngUnsubscribe.complete();
166
      */
167
    }
168

    
169
    private getOrganizationInfo ()  {
170

    
171
        this.warningMessage = '';
172
        this.errorMessage=""
173
        this.showLoading = true;
174

    
175
        this.infoSub = this._organizationService.getOrganizationInfo(this.organizationId).subscribe(
176
            data => {
177
                if(data == null) {
178
                    this.showLoading = false;
179
                    this.errorMessage = 'No organization found';
180
                } else {
181
                    this.organizationInfo = data;
182
                    this.updateTitle(this.organizationInfo.title.name);
183
                    this.updateDescription("Organization, country, projects,  search, repositories, open access"+this.organizationInfo.title.name);
184
                    if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
185
                      this.piwiksub = this._piwikService.trackView(this.organizationInfo.title.name).subscribe();
186
                    }
187
                    var refineFields:string [] = ["funder"];
188

    
189
                    this.searchPublications();
190

    
191
                     this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields);
192

    
193
                    this.fetchDataproviders.getNumForEntity("organization", this.organizationId);
194

    
195
                    this.showLoading = false;
196

    
197
                    /*let projectsNum = 0;
198

    
199
                    if(this.organizationInfo.projects != undefined) {
200
                         this.fundersSet = new Set<string>();
201
                        this.organizationInfo.projects.forEach(function (value, key, map) {
202
                            projectsNum += value.length;
203
                            this.fundersSet.add(key);
204
                        }.bind(this));
205
                    }
206

    
207
                    this.projectsNum = projectsNum;*/
208
                }
209
            },
210
            err => {
211
                console.log(err)
212

    
213
                this.errorMessage = 'No organization found';
214
                this.showLoading = false;
215
            }
216
        );
217
    }
218
/*
219
    private getMetrics() {
220
        console.info("getOrganizationMetrics: component");
221
        this._organizationService.getMetrics(this.organizationId).subscribe(
222
         data => {
223
             this.metrics = data;
224
         },
225
         err => {
226
           console.log(err);
227
         }
228
       );
229
    }
230
*/
231
/*
232
    private handleClick(funder: string) {
233
         if(this.emptyFundersSet) {
234
             this.fundersSet.clear();
235
             this.emptyFundersSet = false;
236
         }
237

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

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

    
258
     private searchPublications() {
259
       this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10);
260
       this.linkToSearchPublications = OpenaireProperties.getLinkToAdvancedSearchPublications();// + "?project=" + this.projectId+"&pr=and";
261
       if(this.fetchPublications.searchUtils.totalResults > 0) {
262
         //this.activeTab = "Publications";
263
       } else {
264
         //this.projectsClicked = true;
265
       }
266
     }
267

    
268
     private searchDataproviders() {
269
       this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10);
270
       this.linkToSearchDataproviders = OpenaireProperties.getLinkToAdvancedSearchDataProviders();
271

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

    
277
       }
278
     }
279

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

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

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

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

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

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

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

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

    
330
                                  let url: string;
331
                                  if(index == 0 || !title) {
332
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special&size="+data;
333
                                  } else {
334
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle&size="+data;
335
                                  }
336

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

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

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

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

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

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

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

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

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

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

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