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

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

    
43
    sub: any;
44
    subDataproviders: any;
45
    subDataprovidersCount: any;
46

    
47
    public projectsClicked: boolean = false;
48

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

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

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

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

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

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

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

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

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

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

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

    
104
            this.csvParamsTail = '" and relorganizationid exact "'+this.organizationId+'" ))';
105

    
106
        });
107

    
108
        this.downloadURLAPI = OpenaireProperties.getCsvAPIURL();
109
        this.csvProjectParamsHead = 'format=csv&type=projects&page=0&query=( (oaftype exact project)and (funderid exact "';
110
        //this.csvPublicationParamsHead = 'format=csv-special&type=publications&page=0&query=((((oaftype exact result) and (resulttypeid exact publication)) and (funderid exact ';
111
/*
112
        this.subDataprovidersCount = this.route.queryParams.subscribe(params => {
113
            this._searchDataprovidersService.numOfDataproviders("organizations/"+this.organizationId+"/datasources/count").subscribe(
114
              data => {
115
                  this.fetchDataproviders.searchUtils.totalResults = data;
116
                  console.info("this.fetchDataproviders.searchUtils.totalResults = "+this.fetchDataproviders.searchUtils.totalResults);
117
              },
118
              err => {
119
        		    console.log(err);
120
        		 }
121
            );
122
        })
123
*/
124
    }
125

    
126

    
127
    ngOnDestroy() {
128
      this.sub.unsubscribe();
129
      if(this.subDataproviders != undefined) {
130
          this.subDataproviders.unsubscribe();
131
      }
132
      //this.subDataprovidersCount.unsubscribe();
133
    }
134

    
135
    private getOrganizationInfo ()  {
136

    
137
        this.warningMessage = '';
138
        this.errorMessage=""
139

    
140
        this._organizationService.getOrganizationInfo(this.organizationId).subscribe(
141
            data => {
142
                if(data == null) {
143
                    this.errorMessage = 'No organization found';
144
                } else {
145
                    this.organizationInfo = data;
146
                    this.updateTitle(this.organizationInfo.title.name);
147
                    this.updateDescription("Organization, country, projects,  search, repositories, open access"+this.organizationInfo.title.name);
148

    
149
                    this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10);
150
                    this.linkToSearchPublications = OpenaireProperties.getLinkToAdvancedSearchPublications();
151
                    //this.fetchProjects.getNumForEntity("organization", this.organizationId);
152
                    var refineFields:string [] = ["funderid"];
153
                    this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields);
154
                    this.fetchDataproviders.getNumForEntity("organization", this.organizationId);
155

    
156
                    /*let projectsNum = 0;
157

    
158
                    if(this.organizationInfo.projects != undefined) {
159
                         this.fundersSet = new Set<string>();
160
                        this.organizationInfo.projects.forEach(function (value, key, map) {
161
                            projectsNum += value.length;
162
                            this.fundersSet.add(key);
163
                        }.bind(this));
164
                    }
165

    
166
                    this.projectsNum = projectsNum;*/
167
                }
168
            },
169
            err => {
170
                console.log(err)
171

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

    
195
         if(this.fundersSet.has(funder)) {
196
             this.fundersSet.delete(funder);
197

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

    
211
     //private getProjectsData(key: string): any {
212
         //return this.projectsData;
213
     //}
214

    
215
     private searchDataproviders() {
216
       this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10);
217
       this.linkToSearchDataproviders = OpenaireProperties.getLinkToAdvancedSearchDataProviders();
218
     }
219

    
220
     private searchDataprovidersInit() {
221
         if(this.subDataproviders == undefined && this.fetchDataproviders.searchUtils.totalResults > 0) {
222
             this.subDataproviders =  this.route.queryParams.subscribe(params => {
223
                 this.searchDataproviders();
224
             });
225
         }
226
     }
227

    
228
     downloadFile(url:string){
229
       console.log("Downloading file: "+ url);
230

    
231
       this.openLoading();
232
       this.setMessageLoading("Downloading CSV file");
233

    
234
       this._reportsService.downloadCSVFile(url).subscribe(
235
           data => {
236
               this.closeLoading();
237
               window.open(window.URL.createObjectURL(data));
238
           },
239
           error => {
240
             console.log("Error downloading the file.");
241
             this.closeLoading();
242
             this.confirmOpenCsvError();
243
           },
244
           () => console.log('Completed file download.'));
245
     }
246

    
247
     downloadPublicationsFile(funder: string, funderId:string, count:number){
248
       console.log("Downloading publications file");
249

    
250
       this.openLoading();
251
       this.setMessageLoading("Downloading CSV file");
252

    
253
       let response: string[] = [];
254
       let totalResponse: string = "";
255
       let projects = [];
256
       let counter: number = count;
257
       let title: boolean = false;
258
       this._searchProjectsService.getProjectsForOrganizations(this.organizationId,' and (funderid exact '+ funderId + ' ) ',1,count,[]).subscribe(
259
           data =>
260
               {
261
                 projects = data[1];
262
                  for(let index=0; index < projects.length; index++) {
263
                      this._searchPublicationsService.numOfEntityPublications(projects[index].id, "projects/").subscribe(
264
                          data =>
265
                              {
266
                                  // let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
267

    
268
                                  let url: string;
269
                                  if(index == 0 || !title) {
270
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special&size="+data;
271
                                  } else {
272
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle&size="+data;
273
                                  }
274

    
275
                                  if(data == 0) {   // if no publications for this project
276
                                      counter--;
277
                                      response[index] = "";
278
                                      if(counter == 0) {
279
                                          for(let i=0; i<count; i++) {
280
                                              if(response[i] != "") {
281
                                                  totalResponse += response[i];
282
                                              }
283
                                          }
284
                                          this.closeLoading();
285
                                          window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
286
                                      }
287
                                  } else if(counter == 1 && !title) {
288
                                      title = true;
289
                                      this._reportsService.getCSVResponse(url).subscribe(
290
                                          data =>
291
                                              {
292
                                                  counter--;
293

    
294
                                                  response[index] = data;
295

    
296
                                                  if(counter == 0) {
297
                                                      for(let i=0; i<count; i++) {
298
                                                          if(response[i] != "") {
299
                                                              totalResponse += response[i];
300
                                                          }
301

    
302
                                                          console.info("2response "+i+": "+response[i]);
303
                                                      }
304
                                                      console.info(totalResponse);
305
                                                      this.closeLoading();
306
                                                      window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
307
                                                  }
308
                                              },
309
                                          error => {
310
                                            console.log("Error downloading the file.");
311
                                            this.closeLoading();
312
                                            this.confirmOpenCsvError();
313
                                          },
314
                                          () => console.log('Completed file download.')
315
                                      );
316
                                  }
317
                              },
318
                          error => console.log("Error getting number of publications for project."));
319
                  }//);
320

    
321
               },
322
           error => {
323
            console.log("Error getting projects project.");
324
            this.closeLoading();
325
            this.confirmOpenCsvError();
326
          }
327
        );
328

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

    
378
    public openLoading(){
379
      if(this.loading){
380
        this.loading.open();
381
      }
382
    }
383
    public closeLoading(){
384
      if(this.loading){
385
        this.loading.close();
386
      }
387
    }
388
    public setMessageLoading(message: string){
389
      if(this.loading){
390
        this.loading.message = message;
391
      }
392
    }
393

    
394
    confirmOpenApplyAll(funder: string, funderId:string, count:number){
395
      this.alertApplyAll.cancelButton = true;
396
      this.alertApplyAll.okButton = true;
397
      this.alertApplyAll.alertTitle = "CSV FILE";
398
      this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
399
      this.alertApplyAll.okButtonText = "Yes";
400
      this.alertApplyAll.cancelButtonText = "No";
401
      this.alertApplyAll.open();
402

    
403
      this.funder = funder;
404
      this.funderId = funderId;
405
      this.count = count;
406
    }
407
    confirmCloseApplyAll(data){
408
         this.downloadPublicationsFile(this.funder, this.funderId, this.count);
409
    }
410

    
411
    confirmOpenCsvError(){
412
      this.alertCsvError.cancelButton = false;
413
      this.alertCsvError.okButton = true;
414
      this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
415
      this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
416
      this.alertCsvError.okButtonText = "OK";
417
      this.alertCsvError.open();
418
    }
419
}
(3-3/4)