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

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

    
27
export class OrganizationComponent {
28

    
29
    organizationInfo: OrganizationInfo;
30
    //private metrics: string;
31
    private organizationId: string;
32
    private projectsNum: number = 0;
33
    private fundersSet: Set<string>;
34
    private emptyFundersSet: boolean = true;
35
    public warningMessage = "";
36
    public errorMessage = "";
37
    public showLoading: boolean = true;
38

    
39
    public downloadURLAPI: string;
40
    public csvProjectParamsHead: string;
41
    public csvPublicationParamsHead: string;
42
    public csvParamsTail: string;
43

    
44
    sub: any;
45

    
46
    public activeTab: string = "Publications";
47
    public reloadDataproviders: boolean = true;
48
    public projectsClicked: boolean = false;
49

    
50
    public fetchPublications: FetchPublications;
51
    public linkToSearchPublications: string = "";
52
    public fetchProjects: FetchProjects;
53
    public fetchDataproviders : FetchDataproviders;
54
    public linkToSearchDataproviders:string = "";
55
    @ViewChild (SearchingProjectsTabComponent) searchingProjectsTabComponent : SearchingProjectsTabComponent ;
56
    public projectFunders:string[] = [];
57

    
58
    public routerHelper:RouterHelper = new RouterHelper();
59

    
60
    @ViewChild (ModalLoading) loading : ModalLoading ;
61
    @ViewChild('AlertModalApplyAll') alertApplyAll;
62
    @ViewChild('AlertModalCsvError') alertCsvError;
63

    
64
    public funder: string;
65
    public funderId: string;
66
    public count: number;
67

    
68
    public errorCodes:ErrorCodes = new ErrorCodes();
69

    
70
    constructor (private element: ElementRef,
71
                 private _organizationService: OrganizationService,
72
                 private  route: ActivatedRoute,
73
                 private _searchDataprovidersService: SearchDataprovidersService,
74
                 private _reportsService: ReportsService,
75
                 private _searchPublicationsService: SearchPublicationsService,
76
                 private _searchProjectsService: SearchProjectsService, private _meta: Meta,
77
                 private _router: Router) {
78

    
79
            this.fetchPublications = new FetchPublications(this._searchPublicationsService);
80
            this.fetchProjects = new FetchProjects(this._searchProjectsService);
81
            this.fetchDataproviders = new FetchDataproviders(this._searchDataprovidersService);
82
            this.updateUrl(OpenaireProperties.getBaseLink()+this._router.url);
83
    }
84

    
85
    ngOnInit() {
86
        console.info('organization init');
87
        this.sub =  this.route.queryParams.subscribe(params => {
88
            this.organizationInfo=null;
89
            this.updateTitle("Organization");
90
            this.updateDescription("Organization, country, projects,  search, repositories, open access");
91

    
92
            this.organizationId = params['organizationId'];
93
            console.info("Id is :"+this.organizationId);
94

    
95
            if(this.organizationId){
96
                this.getOrganizationInfo();
97
            }else{
98
                this.showLoading = false;
99
                this.warningMessage="No valid organization id";
100
            }
101

    
102
            if (typeof document !== 'undefined') {
103
               this.element.nativeElement.scrollIntoView();
104
            }
105

    
106
            this.csvParamsTail = '" and relorganizationid exact "'+this.organizationId+'" ))';
107

    
108
        });
109

    
110
        this.downloadURLAPI = OpenaireProperties.getCsvAPIURL();
111
        this.csvProjectParamsHead = 'format=csv&type=projects&page=0&query=( (oaftype exact project)and (funderid exact "';
112
        //this.csvPublicationParamsHead = 'format=csv-special&type=publications&page=0&query=((((oaftype exact result) and (resulttypeid exact publication)) and (funderid exact ';
113
    }
114

    
115

    
116
    ngOnDestroy() {
117
      this.sub.unsubscribe();
118
    }
119

    
120
    private getOrganizationInfo ()  {
121

    
122
        this.warningMessage = '';
123
        this.errorMessage=""
124
        this.showLoading = true;
125

    
126
        this._organizationService.getOrganizationInfo(this.organizationId).subscribe(
127
            data => {
128
                if(data == null) {
129
                    this.errorMessage = 'No organization found';
130
                } else {
131
                    this.organizationInfo = data;
132
                    this.updateTitle(this.organizationInfo.title.name);
133
                    this.updateDescription("Organization, country, projects,  search, repositories, open access"+this.organizationInfo.title.name);
134

    
135
                    var refineFields:string [] = ["funderid"];
136

    
137
                    this.searchPublications();
138
                    //this.fetchProjects.getNumForEntity("organization", this.organizationId);
139
                    this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields);
140
                    if(this.fetchProjects.searchUtils.totalResults > 0) {
141
                      //this.activeTab = "Projects";
142
                    } else {
143
                      //this.searchDataprovidersInit();
144
                    }
145

    
146
                    this.fetchDataproviders.getNumForEntity("organization", this.organizationId);
147

    
148
                    this.showLoading = false;
149

    
150
                    /*let projectsNum = 0;
151

    
152
                    if(this.organizationInfo.projects != undefined) {
153
                         this.fundersSet = new Set<string>();
154
                        this.organizationInfo.projects.forEach(function (value, key, map) {
155
                            projectsNum += value.length;
156
                            this.fundersSet.add(key);
157
                        }.bind(this));
158
                    }
159

    
160
                    this.projectsNum = projectsNum;*/
161
                }
162
            },
163
            err => {
164
                console.log(err)
165

    
166
                this.errorMessage = 'No organization found';
167
                this.showLoading = false;
168
            }
169
        );
170
    }
171
/*
172
    private getMetrics() {
173
        console.info("getOrganizationMetrics: component");
174
        this._organizationService.getMetrics(this.organizationId).subscribe(
175
         data => {
176
             this.metrics = data;
177
         },
178
         err => {
179
           console.log(err);
180
         }
181
       );
182
    }
183
*/
184
    private handleClick(funder: string) {
185
         if(this.emptyFundersSet) {
186
             this.fundersSet.clear();
187
             this.emptyFundersSet = false;
188
         }
189

    
190
         if(this.fundersSet.has(funder)) {
191
             this.fundersSet.delete(funder);
192

    
193
             if(this.fundersSet.size == 0) {
194
                 this.organizationInfo.projects.forEach(function (value, key, map) {
195
                     this.fundersSet.add(key);
196
                 }.bind(this));
197
                 this.emptyFundersSet = true;
198
             }
199
             console.info(funder+" funder deleted");
200
         } else {
201
             this.fundersSet.add(funder);
202
             console.info(funder+" funder added");
203
         }
204
     }
205

    
206
     //private getProjectsData(key: string): any {
207
         //return this.projectsData;
208
     //}
209

    
210
     private searchPublications() {
211
       this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10);
212
       this.linkToSearchPublications = OpenaireProperties.getLinkToAdvancedSearchPublications();// + "?project=" + this.projectId+"&pr=and";
213
       if(this.fetchPublications.searchUtils.totalResults > 0) {
214
         //this.activeTab = "Publications";
215
       } else {
216
         //this.projectsClicked = true;
217
       }
218
     }
219

    
220
     private searchDataproviders() {
221
       this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10);
222
       this.linkToSearchDataproviders = OpenaireProperties.getLinkToAdvancedSearchDataProviders();
223

    
224
       if(this.fetchDataproviders.searchUtils.totalResults > 0) {
225
         this.reloadDataproviders = false;
226
         //this.activeTab = "Data Providers";
227
       } else {
228

    
229
       }
230
     }
231

    
232
     private searchDataprovidersInit() {
233
         if(this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
234
             this.searchDataproviders();
235
         }
236
     }
237

    
238
     downloadFile(url:string){
239
       console.log("Downloading file: "+ url);
240

    
241
       this.openLoading();
242
       this.setMessageLoading("Downloading CSV file");
243

    
244
       this._reportsService.downloadCSVFile(url).subscribe(
245
           data => {
246
               this.closeLoading();
247
               window.open(window.URL.createObjectURL(data));
248
           },
249
           error => {
250
             console.log("Error downloading the file.");
251
             this.closeLoading();
252
             this.confirmOpenCsvError();
253
           },
254
           () => console.log('Completed file download.'));
255
     }
256

    
257
     downloadPublicationsFile(funder: string, funderId:string, count:number){
258
       console.log("Downloading publications file");
259

    
260
       this.openLoading();
261
       this.setMessageLoading("Downloading CSV file");
262

    
263
       let response: string[] = [];
264
       let totalResponse: string = "";
265
       let projects = [];
266
       let counter: number = count;
267
       let title: boolean = false;
268
       this._searchProjectsService.getProjectsForOrganizations(this.organizationId,' and (funderid exact '+ funderId + ' ) ',1,count,[]).subscribe(
269
           data =>
270
               {
271
                 projects = data[1];
272
                  for(let index=0; index < projects.length; index++) {
273
                      this._searchPublicationsService.numOfEntityPublications(projects[index].id, "project").subscribe(
274
                          data =>
275
                              {
276
                                  // let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
277

    
278
                                  let url: string;
279
                                  if(index == 0 || !title) {
280
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special&size="+data;
281
                                  } else {
282
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle&size="+data;
283
                                  }
284

    
285
                                  if(data == 0) {   // if no publications for this project
286
                                      counter--;
287
                                      response[index] = "";
288
                                      if(counter == 0) {
289
                                          for(let i=0; i<count; i++) {
290
                                              if(response[i] != "") {
291
                                                  totalResponse += response[i];
292
                                              }
293
                                          }
294
                                          this.closeLoading();
295
                                          window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
296
                                      }
297
                                  } else {
298
                                      title = true;
299
                                      
300
                                      this._reportsService.getCSVResponse(url).subscribe(
301
                                          data =>
302
                                              {
303
                                                  counter--;
304
                                                  response[index] = data;
305

    
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
                                                  }
315
                                              },
316
                                          error => {
317
                                            console.log("Error downloading the file.");
318
                                            this.closeLoading();
319
                                            this.confirmOpenCsvError();
320
                                          },
321
                                          () => console.log('Completed file download.')
322
                                      );
323
                                  }
324
                              },
325
                          error => console.log("Error getting number of publications for project."));
326
                  }//);
327

    
328
               },
329
           error => {
330
            console.log("Error getting projects project.");
331
            this.closeLoading();
332
            this.confirmOpenCsvError();
333
          }
334
        );
335

    
336
      //  let counter: number = this.organizationInfo.projects.get(funder).length;
337
       //
338
      //  for(let project of this.organizationInfo.projects.get(funder)) {
339
      //       this._searchPublicationsService.numOfEntityPublications(project.id, "projects/").subscribe(
340
      //           data =>
341
      //               {
342
      //                   let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
343
       //
344
      //                   let url: string;
345
      //                   if(index == 0) {
346
      //                       url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special&size="+data;
347
      //                   } else {
348
      //                       url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special-notitle&size="+data;
349
      //                   }
350
       //
351
      //                   this._reportsService.getCSVResponse(url).subscribe(
352
      //                       data =>
353
      //                           {
354
      //                               counter--;
355
       //
356
      //                               response[index] = data;
357
       //
358
      //                               if(counter == 0) {
359
      //                                   for(let i=0; i<this.organizationInfo.projects.get(funder).length; i++) {
360
      //                                       totalResponse += response[i]+"\n";
361
      //                                   }
362
      //                                   window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
363
      //                               }
364
      //                           },
365
      //                       error => console.log("Error downloading the file."),
366
      //                       () => console.log('Completed file download.'));
367
      //               },
368
      //           error => console.log("Error getting number of publications for project."));
369
        // }//);
370
    }
371
    updateDescription(description:string){
372
      this._meta.updateMeta("description", description);
373
      this._meta.updateProperty("og:description", description);
374
    }
375
    updateTitle(title:string){
376
      var _suffix ="| OpenAIRE";
377
      var _title = ((title.length> 50 ) ?title.substring(0,50):title) + _suffix;
378
      this._meta.setTitle(_title );
379
      this._meta.updateProperty("og:title",_title);
380
    }
381
    updateUrl(url:string){
382
      this._meta.updateProperty("og:url", url);
383
    }
384

    
385
    public openLoading(){
386
      if(this.loading){
387
        this.loading.open();
388
      }
389
    }
390
    public closeLoading(){
391
      if(this.loading){
392
        this.loading.close();
393
      }
394
    }
395
    public setMessageLoading(message: string){
396
      if(this.loading){
397
        this.loading.message = message;
398
      }
399
    }
400

    
401
    confirmOpenApplyAll(funder: string, funderId:string, count:number){
402
      this.alertApplyAll.cancelButton = true;
403
      this.alertApplyAll.okButton = true;
404
      this.alertApplyAll.alertTitle = "CSV FILE";
405
      this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
406
      this.alertApplyAll.okButtonText = "Yes";
407
      this.alertApplyAll.cancelButtonText = "No";
408
      this.alertApplyAll.open();
409

    
410
      this.funder = funder;
411
      this.funderId = funderId;
412
      this.count = count;
413
    }
414
    confirmCloseApplyAll(data){
415
         this.downloadPublicationsFile(this.funder, this.funderId, this.count);
416
    }
417

    
418
    confirmOpenCsvError(){
419
      this.alertCsvError.cancelButton = false;
420
      this.alertCsvError.okButton = true;
421
      this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
422
      this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
423
      this.alertCsvError.okButtonText = "OK";
424
      this.alertCsvError.open();
425
    }
426
}
(3-3/4)