Project

General

Profile

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

    
5
import {OrganizationService} from '../../services/organization.service';
6
import {OrganizationInfo} from '../../utils/entities/organizationInfo';
7
import {ReportsService} from '../../services/reports.service';
8
import {FetchPublications} from '../../utils/fetchEntitiesClasses/fetchPublications.class';
9
import {FetchProjects} from '../../utils/fetchEntitiesClasses/fetchProjects.class';
10
import {FetchDataproviders} from '../../utils/fetchEntitiesClasses/fetchDataproviders.class';
11
import {SearchPublicationsService} from '../../services/searchPublications.service';
12
import {SearchDataprovidersService} from '../../services/searchDataproviders.service';
13
import {SearchProjectsService} from '../../services/searchProjects.service';
14
import { Meta} from '../../../angular2-meta';
15
import {OpenaireProperties, ErrorCodes} from '../../utils/properties/openaireProperties';
16
import {SearchingProjectsTabComponent} from '../searchingProjectsInTab.component';
17
import {RouterHelper} from '../../utils/routerHelper.class';
18

    
19
import {ModalLoading} from '../../utils/modal/loading.component';
20
import {AlertModal} from '../../utils/modal/alert';
21
import {PiwikService} from '../../utils/piwik/piwik.service';
22

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

    
28
export class OrganizationComponent {
29
    public organizationInfo: OrganizationInfo;
30
    public organizationId: string;
31

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

    
37
    // CSV variables
38
    public downloadURLAPI: string;
39
    public csvProjectParamsHead: string;
40
    public csvPublicationParamsHead: string;
41
    public csvParamsTail: string;
42

    
43
    // Active tab variable for responsiveness
44
    public activeTab: string = "Publications";
45

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

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

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

    
64
    public routerHelper:RouterHelper = new RouterHelper();
65
    public errorCodes:ErrorCodes = new ErrorCodes();
66

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

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

    
74
    // Helper variables to specify funder in downloadPublicationsFile function
75
    private funder: string;
76
    private funderId: string;
77
    private funderCountPublications: number;
78
    sub: any;
79
    piwiksub: any;
80

    
81
    constructor (private element: ElementRef,
82
                 private _organizationService: OrganizationService,
83
                 private _piwikService:PiwikService,
84
                 private  route: ActivatedRoute,
85
                 private _searchDataprovidersService: SearchDataprovidersService,
86
                 private _reportsService: ReportsService,
87
                 private _searchPublicationsService: SearchPublicationsService,
88
                 private _searchProjectsService: SearchProjectsService, private _meta: Meta,
89
                 private _router: Router) {
90

    
91
            this.fetchPublications = new FetchPublications(this._searchPublicationsService);
92
            this.fetchProjects = new FetchProjects(this._searchProjectsService);
93
            this.fetchDataproviders = new FetchDataproviders(this._searchDataprovidersService);
94
            this.updateUrl(OpenaireProperties.getBaseLink()+this._router.url);
95
    }
96

    
97
    ngOnInit() {
98
        console.info('organization init');
99
        this.sub =  this.route.queryParams.subscribe(params => {
100
            this.organizationInfo=null;
101
            this.updateTitle("Organization");
102
            this.updateDescription("Organization, country, projects,  search, repositories, open access");
103
            this.projectsClicked = false;
104

    
105
            this.organizationId = params['organizationId'];
106
            console.info("Id is :"+this.organizationId);
107

    
108
            if(this.organizationId){
109
                this.getOrganizationInfo();
110
            }else{
111
                this.showLoading = false;
112
                this.warningMessage="No valid organization id";
113
            }
114

    
115
            if (typeof document !== 'undefined') {
116
               this.element.nativeElement.scrollIntoView();
117
            }
118

    
119
            this.csvParamsTail = '" and relorganizationid exact "'+this.organizationId+'" ))';
120

    
121
        });
122

    
123
        this.downloadURLAPI = OpenaireProperties.getCsvAPIURL();
124
        this.csvProjectParamsHead = 'format=csv&type=projects&page=0&query=( (oaftype exact project)and (funder exact "';
125
        //this.csvPublicationParamsHead = 'format=csv-special&type=publications&page=0&query=((((oaftype exact result) and (resulttypeid exact publication)) and (funderid exact ';
126
    }
127

    
128

    
129
    ngOnDestroy() {
130
      this.sub.unsubscribe();
131
      if(this.piwiksub){
132
        this.piwiksub.unsubscribe();
133
      }
134
    }
135

    
136
    private getOrganizationInfo ()  {
137

    
138
        this.warningMessage = '';
139
        this.errorMessage=""
140
        this.showLoading = true;
141

    
142
        this._organizationService.getOrganizationInfo(this.organizationId).subscribe(
143
            data => {
144
                if(data == null) {
145
                    this.showLoading = false;
146
                    this.errorMessage = 'No organization found';
147
                } else {
148
                    this.organizationInfo = data;
149
                    this.updateTitle(this.organizationInfo.title.name);
150
                    this.updateDescription("Organization, country, projects,  search, repositories, open access"+this.organizationInfo.title.name);
151
                    if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
152
                      this.piwiksub = this._piwikService.trackView(this.organizationInfo.title.name).subscribe();
153
                    }
154
                    var refineFields:string [] = ["funder"];
155

    
156
                    this.searchPublications();
157

    
158
                     this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields);
159

    
160
                    this.fetchDataproviders.getNumForEntity("organization", this.organizationId);
161

    
162
                    this.showLoading = false;
163

    
164
                    /*let projectsNum = 0;
165

    
166
                    if(this.organizationInfo.projects != undefined) {
167
                         this.fundersSet = new Set<string>();
168
                        this.organizationInfo.projects.forEach(function (value, key, map) {
169
                            projectsNum += value.length;
170
                            this.fundersSet.add(key);
171
                        }.bind(this));
172
                    }
173

    
174
                    this.projectsNum = projectsNum;*/
175
                }
176
            },
177
            err => {
178
                console.log(err)
179

    
180
                this.errorMessage = 'No organization found';
181
                this.showLoading = false;
182
            }
183
        );
184
    }
185
/*
186
    private getMetrics() {
187
        console.info("getOrganizationMetrics: component");
188
        this._organizationService.getMetrics(this.organizationId).subscribe(
189
         data => {
190
             this.metrics = data;
191
         },
192
         err => {
193
           console.log(err);
194
         }
195
       );
196
    }
197
*/
198
/*
199
    private handleClick(funder: string) {
200
         if(this.emptyFundersSet) {
201
             this.fundersSet.clear();
202
             this.emptyFundersSet = false;
203
         }
204

    
205
         if(this.fundersSet.has(funder)) {
206
             this.fundersSet.delete(funder);
207

    
208
             if(this.fundersSet.size == 0) {
209
                 this.organizationInfo.projects.forEach(function (value, key, map) {
210
                     this.fundersSet.add(key);
211
                 }.bind(this));
212
                 this.emptyFundersSet = true;
213
             }
214
             console.info(funder+" funder deleted");
215
         } else {
216
             this.fundersSet.add(funder);
217
             console.info(funder+" funder added");
218
         }
219
     }
220
*/
221
     //private getProjectsData(key: string): any {
222
         //return this.projectsData;
223
     //}
224

    
225
     private searchPublications() {
226
       this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10);
227
       this.linkToSearchPublications = OpenaireProperties.getLinkToAdvancedSearchPublications();// + "?project=" + this.projectId+"&pr=and";
228
       if(this.fetchPublications.searchUtils.totalResults > 0) {
229
         //this.activeTab = "Publications";
230
       } else {
231
         //this.projectsClicked = true;
232
       }
233
     }
234

    
235
     private searchDataproviders() {
236
       this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10);
237
       this.linkToSearchDataproviders = OpenaireProperties.getLinkToAdvancedSearchDataProviders();
238

    
239
       if(this.fetchDataproviders.searchUtils.totalResults > 0) {
240
         this.reloadDataproviders = false;
241
         //this.activeTab = "Content Providers";
242
       } else {
243

    
244
       }
245
     }
246

    
247
     public searchDataprovidersInit() {
248
         if(this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
249
             this.searchDataproviders();
250
         }
251
     }
252

    
253
     public downloadFile(url:string){
254
       console.log("Downloading file: "+ url);
255

    
256
       this.openLoading();
257
       this.setMessageLoading("Downloading CSV file");
258

    
259
       this._reportsService.downloadCSVFile(url).subscribe(
260
           data => {
261
               this.closeLoading();
262
               window.open(window.URL.createObjectURL(data));
263
              //  if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
264
              //    this._piwikService.trackDownload(url).subscribe();
265
              //  }
266
           },
267
           error => {
268
             console.log("Error downloading the file.");
269
             this.closeLoading();
270
             this.confirmOpenCsvError();
271
           },
272
           () => console.log('Completed file download.'));
273
     }
274

    
275
     private downloadPublicationsFile(funder: string, funderId:string, count:number){
276
       console.log("Downloading publications file");
277

    
278
       this.openLoading();
279
       this.setMessageLoading("Downloading CSV file");
280

    
281
       let response: string[] = [];
282
       let totalResponse: string = "";
283
       let projects = [];
284
       let counter: number = count;
285
       let title: boolean = false;
286
       this._searchProjectsService.getProjectsForOrganizations(this.organizationId,' and (funder exact '+ funderId + ' ) ',1,count,[]).subscribe(
287
           data =>
288
               {
289
                 projects = data[1];
290
                  for(let index=0; index < projects.length; index++) {
291
                      this._searchPublicationsService.numOfEntityPublications(projects[index].id, "project").subscribe(
292
                          data =>
293
                              {
294
                                  // let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
295

    
296
                                  let url: string;
297
                                  if(index == 0 || !title) {
298
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special&size="+data;
299
                                  } else {
300
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle&size="+data;
301
                                  }
302

    
303
                                  if(data == 0) {   // if no publications for this project
304
                                      counter--;
305
                                      response[index] = "";
306
                                      if(counter == 0) {
307
                                          for(let i=0; i<count; i++) {
308
                                              if(response[i] != "") {
309
                                                  totalResponse += response[i];
310
                                              }
311
                                          }
312
                                          this.closeLoading();
313
                                          window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
314
                                          // if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
315
                                          //   this._piwikService.trackDownload(url).subscribe();
316
                                          // }
317
                                      }
318
                                  } else {
319
                                      title = true;
320

    
321
                                      this._reportsService.getCSVResponse(url).subscribe(
322
                                          data =>
323
                                              {
324
                                                  counter--;
325
                                                  response[index] = data;
326

    
327
                                                  if(counter == 0) {
328
                                                      for(let i=0; i<count; i++) {
329
                                                          if(response[i] != "") {
330
                                                              totalResponse += response[i];
331
                                                          }
332
                                                      }
333
                                                      this.closeLoading();
334
                                                      window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
335
                                                      // if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
336
                                                      //   this._piwikService.trackDownload(url).subscribe();
337
                                                      // }
338
                                                  }
339
                                              },
340
                                          error => {
341
                                            console.log("Error downloading the file.");
342
                                            this.closeLoading();
343
                                            this.confirmOpenCsvError();
344
                                          },
345
                                          () => console.log('Completed file download.')
346
                                      );
347
                                  }
348
                              },
349
                          error => console.log("Error getting number of publications for project."));
350
                  }//);
351

    
352
               },
353
           error => {
354
            console.log("Error getting projects project.");
355
            this.closeLoading();
356
            this.confirmOpenCsvError();
357
          }
358
        );
359

    
360
      //  let counter: number = this.organizationInfo.projects.get(funder).length;
361
       //
362
      //  for(let project of this.organizationInfo.projects.get(funder)) {
363
      //       this._searchPublicationsService.numOfEntityPublications(project.id, "projects/").subscribe(
364
      //           data =>
365
      //               {
366
      //                   let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
367
       //
368
      //                   let url: string;
369
      //                   if(index == 0) {
370
      //                       url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special&size="+data;
371
      //                   } else {
372
      //                       url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special-notitle&size="+data;
373
      //                   }
374
       //
375
      //                   this._reportsService.getCSVResponse(url).subscribe(
376
      //                       data =>
377
      //                           {
378
      //                               counter--;
379
       //
380
      //                               response[index] = data;
381
       //
382
      //                               if(counter == 0) {
383
      //                                   for(let i=0; i<this.organizationInfo.projects.get(funder).length; i++) {
384
      //                                       totalResponse += response[i]+"\n";
385
      //                                   }
386
      //                                   window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
387
      //                               }
388
      //                           },
389
      //                       error => console.log("Error downloading the file."),
390
      //                       () => console.log('Completed file download.'));
391
      //               },
392
      //           error => console.log("Error getting number of publications for project."));
393
        // }//);
394
    }
395

    
396
    private updateDescription(description:string){
397
      this._meta.updateMeta("description", description);
398
      this._meta.updateProperty("og:description", description);
399
    }
400
    private updateTitle(title:string){
401
      var _prefix ="OpenAIRE | ";
402
      var _title = _prefix + ((title.length> 50 ) ?title.substring(0,50):title);
403
      this._meta.setTitle(_title );
404
      this._meta.updateProperty("og:title",_title);
405
    }
406
    private updateUrl(url:string){
407
      this._meta.updateProperty("og:url", url);
408
    }
409

    
410
    private openLoading(){
411
      if(this.loading){
412
        this.loading.open();
413
      }
414
    }
415
    private closeLoading(){
416
      if(this.loading){
417
        this.loading.close();
418
      }
419
    }
420
    private setMessageLoading(message: string){
421
      if(this.loading){
422
        this.loading.message = message;
423
      }
424
    }
425

    
426
    public confirmOpenApplyAll(funder: string, funderId:string, funderCountPublications:number){
427
      this.alertApplyAll.cancelButton = true;
428
      this.alertApplyAll.okButton = true;
429
      this.alertApplyAll.alertTitle = "CSV FILE";
430
      this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
431
      this.alertApplyAll.okButtonText = "Yes";
432
      this.alertApplyAll.cancelButtonText = "No";
433
      this.alertApplyAll.open();
434

    
435
      this.funder = funder;
436
      this.funderId = funderId;
437
      this.funderCountPublications = funderCountPublications;
438
    }
439
    public confirmCloseApplyAll(data){
440
         this.downloadPublicationsFile(this.funder, this.funderId, this.funderCountPublications);
441
    }
442

    
443
    public confirmOpenCsvError(){
444
      this.alertCsvError.cancelButton = false;
445
      this.alertCsvError.okButton = true;
446
      this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
447
      this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
448
      this.alertCsvError.okButtonText = "OK";
449
      this.alertCsvError.open();
450
    }
451
}
(3-3/4)