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 publications and content providers only the one time (first time tab is clicked)
78
    private reloadPublications: boolean = true;
79
    private reloadDataproviders: boolean = true;
80

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

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

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

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

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

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

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

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

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

    
143
        });
144

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

    
150

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

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

    
181
    private getOrganizationInfo ()  {
182

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

    
187
        this.organizationInfo = null;
188

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

    
203
                    //this.searchPublications();
204
                    this.fetchPublications.getNumForEntity("organization", this.organizationId, this.properties);
205
                     this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields,this.properties);
206

    
207
                    this.fetchDataproviders.getNumForEntity("organization", this.organizationId,this.properties);
208

    
209
                    this.showLoading = false;
210

    
211
                    /*let projectsNum = 0;
212

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

    
221
                    this.projectsNum = projectsNum;*/
222
                }
223
            },
224
            err => {
225
                console.log(err)
226

    
227
                this.errorMessage = 'No organization found';
228
                this.showLoading = false;
229
            }
230
        );
231
    }
232

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

    
240
         if(this.fundersSet.has(funder)) {
241
             this.fundersSet.delete(funder);
242

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

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

    
271
     private searchDataproviders() {
272
       this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
273
       this.linkToSearchDataproviders = this.properties.searchLinkToAdvancedDataProviders;
274

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

    
280
       //}
281
     }
282

    
283
     public searchPublicationsInit() {
284
         if(this.reloadPublications && this.fetchPublications.searchUtils.totalResults > 0) {
285
             this.searchPublications();
286
         }
287
     }
288

    
289
     public searchDataprovidersInit() {
290
         if(this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
291
             this.searchDataproviders();
292
         }
293
     }
294

    
295
     public downloadFile(url:string){
296
       console.log("Downloading file: "+ url);
297

    
298
       this.openLoading();
299
       this.setMessageLoading("Downloading CSV file");
300

    
301
       this.downloadFileSub = this._reportsService.downloadCSVFile(url).subscribe(
302
           data => {
303
               this.closeLoading();
304
               window.open(window.URL.createObjectURL(data));
305
                if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
306
                  this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url, this.piwikSiteId).subscribe();
307
                }
308
           },
309
           err => {
310
             console.log("Error downloading the file.");
311
             this.closeLoading();
312
             this.confirmOpenCsvError();
313
           },
314
           () => console.log('Completed file download.'));
315
     }
316

    
317
     private downloadPublicationsFile(funder: string, funderId:string, count:number){
318
       console.log("Downloading publications file");
319

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

    
323
       let response: string[] = [];
324
       let totalResponse: string = "";
325
       let projects = [];
326
       let counter: number = count;
327
       let title: boolean = false;
328

    
329
       this.countProjectsSub = this._searchProjectsService.getProjectsForOrganizations(this.organizationId,' and (funder exact "'+ funderId + '" ) ',1,count,[], this.properties).subscribe(
330
           data =>
331
               {
332
                 projects = data[1];
333
                  for(let index=0; index < projects.length; index++) {
334
                      this.countPublSub = this._searchPublicationsService.numOfEntityPublications(projects[index].id, "project", this.properties).subscribe(
335
                          data =>
336
                              {
337
                                  // let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
338

    
339
                                  let url: string;
340
                                  if(!title) {
341
                                      //url = this.downloadURLAPI+"projects/"+projects[index].id+"?type=publications&format=csv-special";//&size="+data;
342
                                      url = this.downloadURLAPI+"?format=csv-special&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact '"+projects[index].id+"'))"
343
                                      console.info(url);
344
                                  } else {
345
                                      //url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle";//&size="+data;
346
                                      url = this.downloadURLAPI+"?format=csv-special-notitle&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact '"+projects[index].id+"'))"
347
                                  }
348

    
349
                                  if(data == 0 && (counter > 1 || title)) {   // if no publications for this project
350
                                      counter--;
351
                                      response[index] = "";
352
                                      if(counter == 0) {
353
                                          for(let i=0; i<count; i++) {
354
                                              if(response[i] != "") {
355
                                                  totalResponse += response[i];
356
                                              }
357
                                          }
358
                                          this.closeLoading();
359
                                          window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
360
                                          // if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
361
                                          //   this._piwikService.trackDownload(this.properties, url).subscribe();
362
                                          // }
363
                                      }
364
                                  } else {
365
                                      title = true;
366

    
367
                                      this.downloadProjectPublSub = this._reportsService.getCSVResponse(url).subscribe(
368
                                          data =>
369
                                              {
370
                                                  counter--;
371
                                                  response[index] = data;
372

    
373
                                                  if(counter == 0) {
374
                                                      for(let i=0; i<count; i++) {
375
                                                          if(response[i] != "") {
376
                                                              totalResponse += response[i];
377
                                                          }
378
                                                      }
379
                                                      this.closeLoading();
380
                                                      window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
381
                                                      // if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
382
                                                      //   this._piwikService.trackDownload(this.properties, url).subscribe();
383
                                                      // }
384
                                                  }
385
                                              },
386
                                          err => {
387
                                            console.log("Error downloading the file.");
388
                                            this.closeLoading();
389
                                            this.confirmOpenCsvError();
390
                                          },
391
                                          () => console.log('Completed file download.')
392
                                      );
393
                                  }
394
                              },
395
                          err => console.log("Error getting number of publications for project."));
396
                  }//);
397

    
398
               },
399
           err => {
400
            console.log("Error getting projects project.");
401
            this.closeLoading();
402
            this.confirmOpenCsvError();
403
          }
404
        );
405

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

    
442
    private updateDescription(description:string) {
443
      this._meta.updateTag({content:description},"name='description'");
444
      this._meta.updateTag({content:description},"property='og:description'");
445
    }
446
    private updateTitle(title:string){
447
      var _prefix ="OpenAIRE | ";
448
      var _title = _prefix + ((title.length> 50 ) ?title.substring(0,50):title);
449
      this._title.setTitle(_title);
450
      this._meta.updateTag({content:_title},"property='og:title'");
451
    }
452
    private updateUrl(url:string){
453
      this._meta.updateTag({content:url},"property='og:url'");
454
    }
455

    
456
    private openLoading(){
457
      if(this.loading){
458
        this.loading.open();
459
      }
460
    }
461
    private closeLoading(){
462
      if(this.loading){
463
        this.loading.close();
464
      }
465
    }
466
    private setMessageLoading(message: string){
467
      if(this.loading){
468
        this.loading.message = message;
469
      }
470
    }
471

    
472
    public confirmOpenApplyAll(funder: string, funderId:string, funderCountPublications:number){
473
      this.alertApplyAll.cancelButton = true;
474
      this.alertApplyAll.okButton = true;
475
      this.alertApplyAll.alertTitle = "CSV FILE";
476
      this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
477
      this.alertApplyAll.okButtonText = "Yes";
478
      this.alertApplyAll.cancelButtonText = "No";
479
      this.alertApplyAll.open();
480

    
481
      this.funder = funder;
482
      this.funderId = funderId;
483
      this.funderCountPublications = funderCountPublications;
484
    }
485
    public confirmCloseApplyAll(data){
486
         this.downloadPublicationsFile(this.funder, this.funderId, this.funderCountPublications);
487
    }
488

    
489
    public confirmOpenCsvError(){
490
      this.alertCsvError.cancelButton = false;
491
      this.alertCsvError.okButton = true;
492
      this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
493
      this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
494
      this.alertCsvError.okButtonText = "OK";
495
      this.alertCsvError.open();
496
    }
497

    
498
    encodeURI(input: string): string {
499
      return StringUtils.URIEncode(input);
500
    }
501
}
(3-3/4)