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

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

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

    
207
                    this.showLoading = false;
208

    
209
                    /*let projectsNum = 0;
210

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

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

    
225
                this.errorMessage = 'No organization found';
226
                this.showLoading = false;
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,this.properties);
260
       this.linkToSearchPublications = this.properties.searchLinkToAdvancedPublications;
261
       //if(this.fetchPublications.searchUtils.totalResults > 0) {
262
         this.reloadPublications = false;
263
         //this.activeTab = "Publications";
264
       //} else {
265
         //this.projectsClicked = true;
266
       //}
267
     }
268

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

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

    
278
       //}
279
     }
280

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

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

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

    
296
       this.openLoading();
297
       this.setMessageLoading("Downloading CSV file");
298

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

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

    
318
       this.openLoading();
319
       this.setMessageLoading("Downloading CSV file");
320

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

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

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

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

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

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

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

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

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

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

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

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

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

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