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

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

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

    
45
    sub: any;
46
    piwiksub: any;
47

    
48
    public activeTab: string = "Publications";
49
    public reloadDataproviders: boolean = true;
50
    public projectsClicked: boolean = false;
51

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

    
60
    public routerHelper:RouterHelper = new RouterHelper();
61

    
62
    @ViewChild (ModalLoading) loading : ModalLoading ;
63
    @ViewChild('AlertModalApplyAll') alertApplyAll;
64
    @ViewChild('AlertModalCsvError') alertCsvError;
65

    
66
    public funder: string;
67
    public funderId: string;
68
    public count: number;
69

    
70
    public errorCodes:ErrorCodes = new ErrorCodes();
71

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

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

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

    
96
            this.organizationId = params['organizationId'];
97
            console.info("Id is :"+this.organizationId);
98

    
99
            if(this.organizationId){
100
                this.getOrganizationInfo();
101
            }else{
102
                this.showLoading = false;
103
                this.warningMessage="No valid organization id";
104
            }
105

    
106
            if (typeof document !== 'undefined') {
107
               this.element.nativeElement.scrollIntoView();
108
            }
109

    
110
            this.csvParamsTail = '" and relorganizationid exact "'+this.organizationId+'" ))';
111

    
112
        });
113

    
114
        this.downloadURLAPI = OpenaireProperties.getCsvAPIURL();
115
        this.csvProjectParamsHead = 'format=csv&type=projects&page=0&query=( (oaftype exact project)and (funder exact "';
116
        //this.csvPublicationParamsHead = 'format=csv-special&type=publications&page=0&query=((((oaftype exact result) and (resulttypeid exact publication)) and (funderid exact ';
117
    }
118

    
119

    
120
    ngOnDestroy() {
121
      this.sub.unsubscribe();
122
      if(this.piwiksub){
123
  this.piwiksub.unsubscribe();
124
}
125
    }
126

    
127
    private getOrganizationInfo ()  {
128

    
129
        this.warningMessage = '';
130
        this.errorMessage=""
131
        this.showLoading = true;
132

    
133
        this._organizationService.getOrganizationInfo(this.organizationId).subscribe(
134
            data => {
135
                if(data == null) {
136
                    this.showLoading = false;
137
                    this.errorMessage = 'No organization found';
138
                } else {
139
                    this.organizationInfo = data;
140
                    this.updateTitle(this.organizationInfo.title.name);
141
                    this.updateDescription("Organization, country, projects,  search, repositories, open access"+this.organizationInfo.title.name);
142
                    if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
143
                      this.piwiksub = this._piwikService.trackView(this.organizationInfo.title.name).subscribe();
144
                    }
145
                    var refineFields:string [] = ["funder"];
146

    
147
                    this.searchPublications();
148

    
149
                     this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields);
150

    
151
                    this.fetchDataproviders.getNumForEntity("organization", this.organizationId);
152

    
153
                    this.showLoading = false;
154

    
155
                    /*let projectsNum = 0;
156

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

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

    
171
                this.errorMessage = 'No organization found';
172
                this.showLoading = false;
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 searchPublications() {
216
       this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10);
217
       this.linkToSearchPublications = OpenaireProperties.getLinkToAdvancedSearchPublications();// + "?project=" + this.projectId+"&pr=and";
218
       if(this.fetchPublications.searchUtils.totalResults > 0) {
219
         //this.activeTab = "Publications";
220
       } else {
221
         //this.projectsClicked = true;
222
       }
223
     }
224

    
225
     private searchDataproviders() {
226
       this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10);
227
       this.linkToSearchDataproviders = OpenaireProperties.getLinkToAdvancedSearchDataProviders();
228

    
229
       if(this.fetchDataproviders.searchUtils.totalResults > 0) {
230
         this.reloadDataproviders = false;
231
         //this.activeTab = "Content Providers";
232
       } else {
233

    
234
       }
235
     }
236

    
237
     private searchDataprovidersInit() {
238
         if(this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
239
             this.searchDataproviders();
240
         }
241
     }
242

    
243
     downloadFile(url:string){
244
       console.log("Downloading file: "+ url);
245

    
246
       this.openLoading();
247
       this.setMessageLoading("Downloading CSV file");
248

    
249
       this._reportsService.downloadCSVFile(url).subscribe(
250
           data => {
251
               this.closeLoading();
252
               window.open(window.URL.createObjectURL(data));
253
              //  if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
254
              //    this._piwikService.trackDownload(url).subscribe();
255
              //  }
256
           },
257
           error => {
258
             console.log("Error downloading the file.");
259
             this.closeLoading();
260
             this.confirmOpenCsvError();
261
           },
262
           () => console.log('Completed file download.'));
263
     }
264

    
265
     downloadPublicationsFile(funder: string, funderId:string, count:number){
266
       console.log("Downloading publications file");
267

    
268
       this.openLoading();
269
       this.setMessageLoading("Downloading CSV file");
270

    
271
       let response: string[] = [];
272
       let totalResponse: string = "";
273
       let projects = [];
274
       let counter: number = count;
275
       let title: boolean = false;
276
       this._searchProjectsService.getProjectsForOrganizations(this.organizationId,' and (funderid exact '+ funderId + ' ) ',1,count,[]).subscribe(
277
           data =>
278
               {
279
                 projects = data[1];
280
                  for(let index=0; index < projects.length; index++) {
281
                      this._searchPublicationsService.numOfEntityPublications(projects[index].id, "project").subscribe(
282
                          data =>
283
                              {
284
                                  // let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
285

    
286
                                  let url: string;
287
                                  if(index == 0 || !title) {
288
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special&size="+data;
289
                                  } else {
290
                                      url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle&size="+data;
291
                                  }
292

    
293
                                  if(data == 0) {   // if no publications for this project
294
                                      counter--;
295
                                      response[index] = "";
296
                                      if(counter == 0) {
297
                                          for(let i=0; i<count; i++) {
298
                                              if(response[i] != "") {
299
                                                  totalResponse += response[i];
300
                                              }
301
                                          }
302
                                          this.closeLoading();
303
                                          window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
304
                                          // if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
305
                                          //   this._piwikService.trackDownload(url).subscribe();
306
                                          // }
307
                                      }
308
                                  } else {
309
                                      title = true;
310

    
311
                                      this._reportsService.getCSVResponse(url).subscribe(
312
                                          data =>
313
                                              {
314
                                                  counter--;
315
                                                  response[index] = data;
316

    
317
                                                  if(counter == 0) {
318
                                                      for(let i=0; i<count; i++) {
319
                                                          if(response[i] != "") {
320
                                                              totalResponse += response[i];
321
                                                          }
322
                                                      }
323
                                                      this.closeLoading();
324
                                                      window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
325
                                                      // if(OpenaireProperties.isPiwikTrackEnabled() && (typeof document !== 'undefined')){
326
                                                      //   this._piwikService.trackDownload(url).subscribe();
327
                                                      // }
328
                                                  }
329
                                              },
330
                                          error => {
331
                                            console.log("Error downloading the file.");
332
                                            this.closeLoading();
333
                                            this.confirmOpenCsvError();
334
                                          },
335
                                          () => console.log('Completed file download.')
336
                                      );
337
                                  }
338
                              },
339
                          error => console.log("Error getting number of publications for project."));
340
                  }//);
341

    
342
               },
343
           error => {
344
            console.log("Error getting projects project.");
345
            this.closeLoading();
346
            this.confirmOpenCsvError();
347
          }
348
        );
349

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

    
399
    public openLoading(){
400
      if(this.loading){
401
        this.loading.open();
402
      }
403
    }
404
    public closeLoading(){
405
      if(this.loading){
406
        this.loading.close();
407
      }
408
    }
409
    public setMessageLoading(message: string){
410
      if(this.loading){
411
        this.loading.message = message;
412
      }
413
    }
414

    
415
    confirmOpenApplyAll(funder: string, funderId:string, count:number){
416
      this.alertApplyAll.cancelButton = true;
417
      this.alertApplyAll.okButton = true;
418
      this.alertApplyAll.alertTitle = "CSV FILE";
419
      this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
420
      this.alertApplyAll.okButtonText = "Yes";
421
      this.alertApplyAll.cancelButtonText = "No";
422
      this.alertApplyAll.open();
423

    
424
      this.funder = funder;
425
      this.funderId = funderId;
426
      this.count = count;
427
    }
428
    confirmCloseApplyAll(data){
429
         this.downloadPublicationsFile(this.funder, this.funderId, this.count);
430
    }
431

    
432
    confirmOpenCsvError(){
433
      this.alertCsvError.cancelButton = false;
434
      this.alertCsvError.okButton = true;
435
      this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
436
      this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
437
      this.alertCsvError.okButtonText = "OK";
438
      this.alertCsvError.open();
439
    }
440
}
(3-3/4)