Project

General

Profile

1
import {Component, Input, ViewChild} from '@angular/core';
2
import {ActivatedRoute, Router} from '@angular/router';
3
import {Meta, Title} from '@angular/platform-browser';
4

    
5
import {ProjectService} from './project.service';
6
import {ProjectInfo} from '../../utils/entities/projectInfo';
7
import {RouterHelper} from '../../utils/routerHelper.class';
8

    
9
import {FetchResearchResults} from '../../utils/fetchEntitiesClasses/fetchResearchResults.class';
10
import {SearchResearchResultsService} from '../../services/searchResearchResults.service';
11

    
12
import {ModalLoading} from '../../utils/modal/loading.component';
13

    
14
import {ReportsService} from '../../services/reports.service';
15
import {ErrorCodes} from '../../utils/properties/errorCodes'
16

    
17
import {PiwikService} from '../../utils/piwik/piwik.service';
18
import {EnvProperties} from '../../utils/properties/env-properties';
19
import {SEOService} from '../../sharedComponents/SEO/SEO.service';
20
import {HelperFunctions} from "../../utils/HelperFunctions.class";
21
import {HelperService} from "../../utils/helper/helper.service";
22
import {Location} from "@angular/common";
23
import {HtmlProjectReportService} from "../htmlProjectReport/htmlProjectReport.service";
24
import {StringUtils} from "../../utils/string-utils.class";
25
import {ResultPreview} from "../../utils/result-preview/result-preview";
26
import {SearchResult} from "../../utils/entities/searchResult";
27
import {IndexInfoService} from "../../utils/indexInfo.service";
28
import {Subscriber} from "rxjs";
29

    
30
@Component({
31
  selector: 'project',
32
  templateUrl: 'project.component.html',
33
})
34

    
35
export class ProjectComponent {
36
  @Input() piwikSiteId = null;
37
  @Input() communityId = null;
38
  public projectInfo: ProjectInfo;
39
  public projectId: string;
40
  public projectName: string;
41

    
42
  // Metrics tab variables
43
  public metricsClicked: boolean;
44
  public viewsFrameUrl: string;
45
  public downloadsFrameUrl: string;
46
  private totalViews: number;
47
  private totalDownloads: number;
48
  private pageViews: number;
49

    
50
  // Statistics tab variables
51
  public statsClicked: boolean;
52
  public chartScientificResultsUrl: string;
53
  public chartAccessModeUrl: string;
54
  public chartDatasourcesUrl: string;
55

    
56
  // Clipboard variable for HTML dynamic content
57
  public clipboard;
58

    
59
  public project;
60

    
61
  // CSV variables
62
  public downloadURLAPI: string;
63
  public csvParams: string;
64

    
65
  // HTML (download) variables
66
  public header1: string = "";
67
  public header2: string = "";
68
  public htmlResultDownload: string = "";
69

    
70
  // Message variables
71
  public warningMessage = "";
72
  public errorMessage = "";
73
  public showLoading: boolean = true;
74

    
75
  // Active tab variable for responsiveness
76
  public activeTab: string = "";
77

    
78
  @ViewChild('statisticsModal') statisticsModal;
79
  @ViewChild('linkProjectModal') linkProjectModal;
80
  @ViewChild('shareResultsModal') shareResultsModal;
81
  @ViewChild('downloadReportModal') downloadReportModal;
82

    
83
  // Request results for publications, research data and software only the one time (first time tab is clicked)
84
  private reloadPublications: boolean = true;
85
  private reloadDatasets: boolean = true;
86
  private reloadSoftware: boolean = true;
87
  private reloadOrps: boolean = true;
88

    
89
  // Variables for entity selections on the right column
90
  public share_research_results_type: string = "results";
91
  public download_research_results_type: string = "";
92

    
93
  // Variables for publications, research data, software tabs
94
  public fetchPublications: FetchResearchResults;
95
  public fetchDatasets: FetchResearchResults;
96
  public fetchSoftware: FetchResearchResults;
97
  public fetchOrps: FetchResearchResults;
98
  public searchNumber: number = 5;
99

    
100
  public routerHelper: RouterHelper = new RouterHelper();
101
  public errorCodes: ErrorCodes = new ErrorCodes();
102
  public pageContents = null;
103
  public divContents = null;
104

    
105
  public indexUpdateDate: Date;
106
  public showFeedback: boolean;
107
  public feedbackFields: string [] = [
108
    'Title', 'Funding Information', 'Duration',
109
    'Organizations', 'Other'];
110

    
111
  @ViewChild(ModalLoading) loading: ModalLoading;
112
  // Alert box when something is wrong with CSV requests
113
  @ViewChild('AlertModalCsvError') alertCsvError;
114

    
115
  // Description variables for view more/less functionality
116
  public thresholdDescription: number = 670;
117
  public showNumDescription: number = 670;
118

    
119
  // Organizations variables for view more/less functionality
120
  public thresholdOrganizations: number = 20;
121
  public showNumOrganizations: number = 20;
122

    
123
  subscriptions = [];
124
  properties: EnvProperties;
125

    
126
  constructor(private  route: ActivatedRoute,
127
              private _router: Router,
128
              private _location: Location,
129
              private _meta: Meta,
130
              private _title: Title,
131
              private seoService: SEOService,
132
              private _piwikService: PiwikService,
133
              private helper: HelperService,
134
              private _projectService: ProjectService,
135
              private _searchResearchResultsService: SearchResearchResultsService,
136
              private _reportsService: ReportsService,
137
              private htmlService: HtmlProjectReportService,
138
              private indexInfoService: IndexInfoService) {}
139

    
140
  ngOnInit() {
141
    this.subscriptions.push(this.route.data
142
      .subscribe((data: { envSpecific: EnvProperties }) => {
143
        this.properties = data.envSpecific;
144
        if (typeof document !== 'undefined') {
145
          this.subscriptions.push(this.indexInfoService.getLastIndexDate(this.properties).subscribe(lastIndexUpdate => {
146
            if (lastIndexUpdate) {
147
              this.indexUpdateDate = new Date(lastIndexUpdate);
148
            }
149
          }));
150
        }
151
        //this.getDivContents();
152
        this.getPageContents();
153
        this.updateUrl(this.properties.domain + this.properties.baseLink + this._router.url);
154

    
155
      }));
156
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
157
      this.metricsClicked = false;
158
      this.statsClicked = false;
159
      this.fetchPublications = new FetchResearchResults(this._searchResearchResultsService);
160
      this.fetchDatasets = new FetchResearchResults(this._searchResearchResultsService);
161
      this.fetchSoftware = new FetchResearchResults(this._searchResearchResultsService);
162
      this.fetchOrps = new FetchResearchResults(this._searchResearchResultsService);
163

    
164
      var title = "Project";
165
      var description = "";
166

    
167
      this.header1 = "";
168

    
169
      this.updateTitle(title);
170
      this.updateDescription(description);
171
      this.projectId = params['projectId'];
172
      var grantId = params['grantId'];
173
      var funder = params['funder'];
174

    
175

    
176
      if (this.projectId  && StringUtils.isOpenAIREID(this.projectId)) {
177
        this.getProjectInfo(this.projectId);
178
        this.actionsAfterLoadId();
179
      } else if (grantId && funder) {
180
        this.getProjectInfoByGrantId(grantId, funder);
181
      } else {
182

    
183
        this.showLoading = false;
184
        this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
185
        //this.warningMessage = "No valid project id";
186
      }
187

    
188
      this.downloadURLAPI = this.properties.csvAPIURL;
189

    
190
      this.createClipboard();
191
      HelperFunctions.scroll();
192
    }));
193
  }
194

    
195
  public getFileNameType(type: string) {
196
    if(type == "results") {
197
      return "research-outcomes";
198
    } else if(type == "publications") {
199
      return "publications";
200
    } else if(type == "datasets") {
201
      return "research-data";
202
    } else if(type == "software") {
203
      return "software";
204
    } else if(type == "other") {
205
      return "other-research-products";
206
    }
207
    return "results";
208
  }
209

    
210
  public getCsvParams(type: string) {
211
    // if(type == "results") {
212
    //   type = "publications&type=datasets&type=software&type=other";
213
    // }
214
    return "?format=csv-special&type="+type+"&fq=(relprojectid exact \"" + this.projectId + "\")";
215
  }
216

    
217
  private getPageContents() {
218
    if(this.communityId) {
219
      this.subscriptions.push(this.helper.getPageHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
220
        this.pageContents = contents;
221
      }));
222
    }
223
  }
224

    
225
  private getDivContents() {
226
    if(this.communityId) {
227
      this.subscriptions.push(this.helper.getDivHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
228
        this.divContents = contents;
229
      }));
230
    }
231
  }
232

    
233
  getDynamicContent(type: string) {
234
    return  "<script type=\"text/javascript\">"
235
      + "\n<!--"
236
      + "\ndocument.write('<div id=\"oa_widget\"></div>');"
237
      + "\ndocument.write('<script type=\"text/javascript\""
238
      + " src=\"" + this.properties.widgetLink
239
      + this.projectId + "&type="
240
      + type
241
      + "\"></script>');"
242
      + "\n-->"
243
      + "\n</script>";
244
  }
245

    
246
  actionsAfterLoadId() {
247
    //this.getProjectInfo(this.projectId);
248
    //this.searchPublications();
249

    
250
    if (typeof document !== 'undefined') {
251
      this.fetchPublications.getNumForEntity("publication", "project", this.projectId, this.properties);
252
      this.fetchDatasets.getNumForEntity("dataset", "project", this.projectId, this.properties);
253
      this.fetchSoftware.getNumForEntity("software", "project", this.projectId, this.properties);
254
      this.fetchOrps.getNumForEntity("other", "project", this.projectId, this.properties);
255
    }
256
  }
257

    
258
  ngOnDestroy() {
259
    this.subscriptions.forEach(subscription => {
260
      if (subscription instanceof Subscriber) {
261
        subscription.unsubscribe();
262
      }
263
    });
264
    this.fetchDatasets.clearSubscriptions();
265
    this.fetchPublications.clearSubscriptions();
266
    this.fetchSoftware.clearSubscriptions();
267
    this.fetchPublications.clearSubscriptions();
268
  }
269

    
270
  private createClipboard() {
271
    if (typeof window !== 'undefined') {
272
      delete this.clipboard;
273
      let Clipboard;
274
      Clipboard = require('clipboard');
275
      this.clipboard = new Clipboard('.clipboard_btn');
276
    }
277
  }
278

    
279
  public searchPublications(page: number, size: number) {
280
    if (this.reloadPublications &&
281
      (this.fetchPublications.searchUtils.status == this.errorCodes.LOADING ||
282
        (this.fetchPublications.searchUtils.status == this.errorCodes.DONE && this.fetchPublications.searchUtils.totalResults > 0)
283
      )
284
    ) {
285
      this.fetchPublications.getResultsForEntity("publication", "project", this.projectId, page, size, this.properties);
286
    }
287
    this.reloadPublications = false;
288
  }
289

    
290
  public searchDatasets(page: number, size: number) {
291
    if (this.reloadDatasets &&
292
      (this.fetchDatasets.searchUtils.status == this.errorCodes.LOADING ||
293
        (this.fetchDatasets.searchUtils.status == this.errorCodes.DONE && this.fetchDatasets.searchUtils.totalResults > 0)
294
      )
295
    ) {
296
      this.fetchDatasets.getResultsForEntity("dataset", "project", this.projectId, page, size, this.properties);
297
    }
298
    this.reloadDatasets = false;
299
  }
300

    
301
  private searchSoftware(page: number, size: number) {
302
    if (this.reloadSoftware &&
303
      (this.fetchSoftware.searchUtils.status == this.errorCodes.LOADING ||
304
        (this.fetchSoftware.searchUtils.status == this.errorCodes.DONE && this.fetchSoftware.searchUtils.totalResults > 0)
305
      )
306
    ) {
307
      this.fetchSoftware.getResultsForEntity("software", "project", this.projectId, page, size, this.properties);
308
    }
309
    this.reloadSoftware = false;
310
  }
311

    
312
  private searchOrps(page: number, size: number) {
313
    if (this.reloadOrps &&
314
      (this.fetchOrps.searchUtils.status == this.errorCodes.LOADING ||
315
        (this.fetchOrps.searchUtils.status == this.errorCodes.DONE && this.fetchOrps.searchUtils.totalResults > 0)
316
      )
317
    ) {
318
      this.fetchOrps.getResultsForEntity("other", "project", this.projectId, page, size, this.properties);
319
    }
320
    this.reloadOrps = false;
321
  }
322

    
323
  private getProjectInfo(id: string) {
324
    this.warningMessage = '';
325
    this.errorMessage = "";
326
    this.showLoading = true;
327

    
328
    this.projectInfo = null;
329

    
330
    this.subscriptions.push(this._projectService.getProjectInfo(id, this.properties).subscribe(
331
      data => {
332
        this.projectInfo = data;
333

    
334
        this.actionsAfterGettingProjectInfo();
335
      },
336
      err => {
337
        //console.log(err);
338
        this.handleError("Error getting project for id: " + this.projectId, err);
339
        if(err.status == 404) {
340
          this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
341
        }
342
        this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.properties.searchLinkToProjects);
343
        this.errorMessage = 'No project found';
344
        this.showLoading = false;
345
      }
346
    ));
347
  }
348

    
349
  private getProjectInfoByGrantId(grantId: string, funder: string) {
350
    this.warningMessage = '';
351
    this.errorMessage = "";
352
    this.showLoading = true;
353

    
354
    this.projectInfo = null;
355

    
356
    this.subscriptions.push(this._projectService.getProjectInfoByGrantId(grantId, funder, this.properties).subscribe(
357
      data => {
358

    
359
        this.projectInfo = data;
360

    
361
        this.actionsAfterGettingProjectInfo();
362
        this.projectId = this.projectInfo.id;
363
        this.actionsAfterLoadId();
364
      },
365
      err => {
366
        //console.log(err);
367
        this.handleError("Error getting project for grant id: " + grantId + " and funder: " + funder, err);
368
        if(err.status == 404) {
369
          this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
370
        }
371
        this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.properties.searchLinkToProjects);
372
        this.errorMessage = 'No project found';
373
        this.showLoading = false;
374
      }
375
    ));
376
  }
377

    
378
  actionsAfterGettingProjectInfo() {
379
    this.projectName = this.projectInfo.acronym;
380
    if (this.projectName == undefined || this.projectName == '') {
381
      this.projectName = this.projectInfo.title;
382
    }
383
    this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this._router.url);
384
    this.updateTitle(this.projectName);
385
    this.updateDescription(this.projectInfo.description?this.projectInfo.description: ("project" + (this.projectInfo.title?"," + this.projectInfo.title:"") + (this.projectInfo.funding && this.projectInfo.funding.funderName?", funder: " + this.projectInfo.funding.funderName:"") + (this.projectInfo.acronym?"," + this.projectInfo.acronym:"")));
386
    if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
387
      this.subscriptions.push(this._piwikService.trackView(this.properties, this.projectName, this.piwikSiteId).subscribe());
388
    }
389

    
390
    this.project = {
391
      funderId: "",
392
      funderName: ((this.projectInfo.funding) ? this.projectInfo.funding.funderShortName: ''),
393
      projectId: this.projectId,
394
      projectName: this.projectInfo.title,
395
      projectAcronym: this.projectInfo.acronym,
396
      startDate: this.projectInfo.startDate,
397
      endDate: this.projectInfo.endDate
398
    };
399

    
400
    this.viewsFrameUrl = this.properties.framesAPIURL + 'merge.php?com=query&data=[{"query":"projRepoViews","projTitle":"' + this.projectId + '","table":"","fields":[{"fld":"sum","agg":"sum","type":"column","yaxis":1,"c":false}],"xaxis":{"name":"month","agg":"sum"},"group":"","color":"","type":"chart","size":200,"sort":"xaxis","xStyle":{"r":-30,"s":"6","l":"-","ft":"-","wt":"-"},"title":"","subtitle":"","xaxistitle":"","yaxisheaders":["Monthly views"],"generalxaxis":"","theme":0,"in":[]}]&info_types=["column"]&stacking=&steps=false&fontFamily=Courier&spacing=[5,0,0,0]&style=[{"color":"rgba(0, 0, 0, 1)","size":"18"},{"color":"rgba(0, 0, 0, 1)","size":"18"},{"color":"000000","size":""},{"color":"000000","size":""}]&backgroundColor=rgba(255,255,255,1)&colors[]=rgba(124, 181, 236, 1)&colors[]=rgba(67, 67, 72, 1)&colors[]=rgba(144, 237, 125, 1)&colors[]=rgba(247, 163, 92, 1)&colors[]=rgba(128, 133, 233, 1)&colors[]=rgba(241, 92, 128, 1)&colors[]=rgba(228, 211, 84, 1)&colors[]=rgba(43, 144, 143, 1)&colors[]=rgba(244, 91, 91, 1)&colors[]=rgba(145, 232, 225, 1)&xlinew=0&ylinew=1&legends=true&tooltips=true&persistent=false';
401

    
402
    this.downloadsFrameUrl = this.properties.framesAPIURL + 'merge.php?com=query&data=[{"query":"projRepoDownloads","projTitle":"' + this.projectId + '","table":"","fields":[{"fld":"sum","agg":"sum","type":"column","yaxis":1,"c":false}],"xaxis":{"name":"month","agg":"sum"},"group":"","color":"","type":"chart","size":200,"sort":"xaxis","xStyle":{"r":-30,"s":"6","l":"-","ft":"-","wt":"-"},"title":"","subtitle":"","xaxistitle":"","yaxisheaders":["Monthly downloads"],"generalxaxis":"","theme":0,"in":[]}]&info_types=["column"]&stacking=&steps=false&fontFamily=Courier&spacing=[5,0,0,0]&style=[{"color":"rgba(0, 0, 0, 1)","size":"18"},{"color":"rgba(0, 0, 0, 1)","size":"18"},{"color":"000000","size":""},{"color":"000000","size":""}]&backgroundColor=rgba(255,255,255,1)&colors[]=rgba(124, 181, 236, 1)&colors[]=rgba(67, 67, 72, 1)&colors[]=rgba(144, 237, 125, 1)&colors[]=rgba(247, 163, 92, 1)&colors[]=rgba(128, 133, 233, 1)&colors[]=rgba(241, 92, 128, 1)&colors[]=rgba(228, 211, 84, 1)&colors[]=rgba(43, 144, 143, 1)&colors[]=rgba(244, 91, 91, 1)&colors[]=rgba(145, 232, 225, 1)&xlinew=0&ylinew=1&legends=true&tooltips=true&persistent=false';
403

    
404
    //stats tab charts
405
    if (this.properties.useNewStatistisTool) {
406
      this.chartScientificResultsUrl = this.properties.statisticsFrameNewAPIURL +
407
        'chart?json='+StringUtils.URIEncode('{"library":"HighCharts","chartDescription":{"queries":[{"name":"Research outcomes","type":"column","query":{"name":"projScient","parameters":["'+this.projectId+'"]}}],"chart":{"backgroundColor":"#FFFFFFFF","borderColor":"#335cadff","borderRadius":0,"borderWidth":0,"plotBorderColor":"#ccccccff","plotBorderWidth":0},"title":{"text":"Produced research outcomes per year"},"subtitle":{},"yAxis":{"title":{"text":"Research outcomes"}},"xAxis":{"title":{"text":"Year"}},"lang":{"noData":"No Data available for the Query"},"exporting":{"enabled":false},"plotOptions":{"series":{"dataLabels":{"enabled":false}}},"legend":{"enabled":true,"align":"center","verticalAlign":"bottom","layout":"horizontal"},"credits":{"href":null,"enabled":true,"text":"Created by OpenAIRE via HighCharts"}}}');
408
      this.chartAccessModeUrl =  this.properties.statisticsFrameNewAPIURL +
409
        'chart?json='+StringUtils.URIEncode(
410
        '{"library":"HighCharts","chartDescription":{"queries":[{"name":"Research outcomes","type":"pie","query":{"name":"projOA","parameters":["'+this.projectId+'"]}}],"chart":{"backgroundColor":"#FFFFFFFF","borderColor":"#335cadff","borderRadius":0,"borderWidth":0,"plotBorderColor":"#ccccccff","plotBorderWidth":0},"title":{"text":"Access mode of research outcomes"},"subtitle":{},"yAxis":{"title":{"text":"Research outcomes"}},"xAxis":{"title":{"text":"Access mode"}},"lang":{"noData":"No Data available for the Query"},"exporting":{"enabled":false},"plotOptions":{"series":{"dataLabels":{"enabled":false}}},"legend":{"enabled":true,"align":"center","verticalAlign":"bottom","layout":"horizontal"},"credits":{"href":null,"enabled":true,"text":"Created by OpenAIRE via HighCharts"}}}');
411
      this.chartDatasourcesUrl =  this.properties.statisticsFrameNewAPIURL +
412
        'chart?json='+StringUtils.URIEncode(
413
        '{"library":"HighCharts","chartDescription":{"queries":[{"name":"Research outcomes","type":"bar","query":{"name":"projPubsRepos","parameters":["'+this.projectId+'"]}}],"chart":{"backgroundColor":"#FFFFFFFF","borderColor":"#335cadff","borderRadius":0,"borderWidth":0,"plotBorderColor":"#ccccccff","plotBorderWidth":0},"title":{"text":"Research outcomes per datasource"},"subtitle":{},"yAxis":{"title":{"text":"Research outcomes"}},"xAxis":{"title":{"text":"Datasource"}},"lang":{"noData":"No Data available for the Query"},"exporting":{"enabled":false},"plotOptions":{"series":{"dataLabels":{"enabled":true}}},"legend":{"enabled":true,"align":"center","verticalAlign":"bottom","layout":"horizontal"},"credits":{"href":null,"enabled":true,"text":"Created by OpenAIRE via HighCharts"}}}');
414
    } else {
415
      this.chartScientificResultsUrl = this.properties.statisticsFrameAPIURL + 'chart.php?com=query&persistent=false&data={"query":"projScient","projTitle":"' + this.projectId + '", "table": "result", "fields": [{"fld": "number", "agg": "count", "type": "spline", "yaxis":1, "c":false}], "xaxis":{"name": "result_classifications-type", "agg": "avg"}, "group": "", "color": "", "type": "chart", "size":30, "sort": "xaxis", "xStyle":{"r": "-", "s": "-", "l": "-", "ft": "-", "wt": "-"}, "yaxisheaders": [""], "fieldsheaders": ["Research Outcomes"], "in": [], "filters": [{"name": "result_datasources-datasource-name", "values": [" "], "to": "-1"}], "having": [], "incfilters": [], "inchaving": [], "title": "", "subtitle": "", "xaxistitle": ""}&w=90%&h=90%';
416
      this.chartAccessModeUrl = this.properties.statisticsFrameAPIURL + 'chart.php?com=query&persistent=false&data={"query":"projOA","projTitle":"' + this.projectId + '", "table": "result", "fields": [{"fld": "number", "agg": "count", "type": "pie", "yaxis":1, "c":false}], "xaxis":{"name": "result_classifications-type", "agg": "avg"}, "group": "", "color": "", "type": "chart", "size":30, "sort": "xaxis", "xStyle":{"r": "-", "s": "-", "l": "-", "ft": "-", "wt": "-"}, "yaxisheaders": [""], "fieldsheaders": ["Research Outcomes"], "in": [], "filters": [{"name": "result_datasources-datasource-name", "values": [" "], "to": "-1"}], "having": [], "incfilters": [], "inchaving": [], "title": "", "subtitle": "", "xaxistitle": ""}&w=90%&h=90%';
417
      this.chartDatasourcesUrl = this.properties.statisticsFrameAPIURL + 'chart.php?com=query&persistent=false&data={"query":"projPubsRepos","projTitle":"' + this.projectId + '", "table": "result", "fields": [{"fld": "number", "agg": "count", "type": "bar", "yaxis":1, "c":false}], "xaxis":{"name": "result_classifications-type", "agg": "avg"}, "group": "", "color": "", "type": "chart", "size":30, "sort": "xaxis", "xStyle":{"r": "-", "s": "-", "l": "-", "ft": "-", "wt": "-"}, "yaxisheaders": [""], "fieldsheaders": ["Research Outcomes"], "in": [], "filters": [{"name": "result_datasources-datasource-name", "values": [" "], "to": "-1"}], "having": [], "incfilters": [], "inchaving": [], "title": "", "subtitle": "", "xaxistitle": ""}&w=90%&h=90%';
418
    }
419

    
420
    this.showLoading = false;
421
  }
422

    
423
  public downloadCsvFile(url: string, filename: string) {
424
    this.openLoading();
425
    this.setMessageLoading("Downloading CSV file");
426

    
427
    this.subscriptions.push(this._reportsService.downloadCSVFile(url).subscribe(
428
      data => {
429
        this.closeLoading();
430

    
431
        let url = window.URL.createObjectURL(data);
432
        this.download(url, filename+".csv");
433

    
434
        if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
435
          this.subscriptions.push(this._piwikService.trackDownload(this.properties, url).subscribe());
436
        }
437
      },
438
      error => {
439
        //console.log("Error downloading the file.");
440
        this.handleError("Error downloading file: " + filename, error);
441

    
442
        this.closeLoading();
443
        this.confirmOpenFileDownloadError("CSV");
444
      }/*,
445
            () => console.log('Completed file download.')*/
446
    ));
447
  }
448

    
449
  public metricsResults($event) {
450
    this.totalViews = $event.totalViews;
451
    this.totalDownloads = $event.totalDownloads;
452
    this.pageViews = $event.pageViews;
453
  }
454
  
455
  public get hasMetrics(): boolean {
456
    return !(this.totalViews && this.totalDownloads && this.pageViews) || this.totalViews > 0 || this.totalDownloads > 0||this.pageViews > 0;
457
  }
458

    
459
  public openStatistics() {
460
    this.statsClicked = true;
461
    this.statisticsModal.cancelButton = false;
462
    this.statisticsModal.okButton = false;
463
    this.statisticsModal.alertTitle = "Statistics of";
464
    this.statisticsModal.open();
465
  }
466

    
467
  public openLinkProjectModal() {
468
    this.linkProjectModal.cancelButton = false;
469
    this.linkProjectModal.okButton = false;
470
    this.linkProjectModal.alertTitle = "Link this project to";
471
    //this.linkProjectModal.alertHeader = false;
472
    this.linkProjectModal.open();
473
  }
474

    
475
  public openShareResultsModal() {
476
    this.shareResultsModal.cancelButton = false;
477
    this.shareResultsModal.okButton = false;
478
    this.shareResultsModal.alertTitle = "Share results";
479
    this.shareResultsModal.open();
480
  }
481

    
482
  public openDownloadReportModal() {
483
    if(this.fetchPublications.searchUtils.totalResults > 0 || this.fetchDatasets.searchUtils.totalResults > 0 ||
484
       this.fetchSoftware.searchUtils.totalResults > 0 || this.fetchOrps.searchUtils.totalResults > 0) {
485
      this.download_research_results_type = "results";
486
    }
487
    this.downloadReportModal.cancelButton = false;
488
    this.downloadReportModal.okButton = false;
489
    this.downloadReportModal.alertTitle = "Download report";
490
    this.downloadReportModal.open();
491
  }
492

    
493
  private createHeaders(type: string) {
494
    this.openLoading();
495
    this.setMessageLoading("Downloading HTML file");
496

    
497
    if(!this.header1) {
498
      this.createHeader1();
499
    }
500

    
501
    if (type == "publications") {
502
      this.header2 = this.fetchPublications.searchUtils.totalResults.toLocaleString('en-US') + " publications";
503
    } else if (type == "datasets") {
504
      this.header2 = this.fetchDatasets.searchUtils.totalResults.toLocaleString('en-US') + " research data";
505
    } else if (type == "software") {
506
      this.header2 = this.fetchSoftware.searchUtils.totalResults.toLocaleString('en-US') + " software";
507
    } else if (type == "other") {
508
      this.header2 = this.fetchOrps.searchUtils.totalResults.toLocaleString('en-US') + " other research products";
509
    } else if (type == "results") {
510
      let totalResults: number = (+this.fetchPublications.searchUtils.totalResults) +
511
        (+this.fetchDatasets.searchUtils.totalResults) +
512
        (+this.fetchSoftware.searchUtils.totalResults) +
513
        (+this.fetchOrps.searchUtils.totalResults);
514

    
515
      this.header2 = totalResults.toLocaleString('en-US') + " research outcomes";
516
    }
517
  }
518

    
519
  private createHtmlFile(type: string, filename: string) {
520
    let intro: string = '<!doctype html>';
521
    intro += '<html lang="en-gb" dir="ltr" vocab="http://schema.org/">';
522
    intro += '<head>';
523
    intro += '<title>' + this.header1 + '</title>';
524
    intro += '</head>';
525

    
526
    if (typeof window !== 'undefined') {
527
      this.subscriptions.push(this.htmlService.getHTML(this.projectId, type, this.properties.csvAPIURL).subscribe(
528
        data => {
529
          //console.info(data);
530
          this.htmlResultDownload = intro + '<body><div>' + this.header1 + '</div><div><h4>' + this.header2 + '</h4></div>';
531
          this.htmlResultDownload += "<table><thead><tr> <th>Type</th><th>Title</th><th>Authors</th><th>Publication Year</th><th>DOI</th><th>Permanent Identifier</th><th>Publication type</th><th>Journal</th><th>Project Name (GA Number)</th><th>Access Mode</th></tr></thead><tbody>" + data + "</tbody></table>";
532
          this.htmlResultDownload += '</body></html>';
533

    
534
          //console.info(this.htmlResultDownload);
535
          this.closeLoading();
536

    
537
          let url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' }));
538
          this.download(url, filename+".html");
539

    
540
          if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
541
            this.subscriptions.push(this._piwikService.trackDownload(this.properties, url).subscribe());
542
          }
543
        },
544
        err => {
545
          this.handleError("Error getting html for id: " + this.projectId, err);
546
          //this.errorMessage = 'Service not available';
547
          this.closeLoading();
548
          this.confirmOpenFileDownloadError("HTML");
549
        }
550
      ));
551
    } else {
552
      this.closeLoading();
553
      this.confirmOpenFileDownloadError("HTML");
554
    }
555
  }
556

    
557
  downloadHtmlFile(type: string, filename: string) {
558
    this.createHeaders(type);
559
    this.createHtmlFile(type, filename);
560
  }
561

    
562
  createHeader1() {
563
    // if (title != undefined && title != "") {
564
    //   this.header1 += title;
565
    // }
566
    // if ((title != undefined && title != "") &&
567
    //   ((acronym != undefined && acronym != "") ||
568
    //     (code != undefined && code != ""))) {
569
    //   this.header1 += "(";
570
    // }
571
    // if (acronym != undefined && acronym != "") {
572
    //   this.header1 += acronym + " - ";
573
    // }
574
    // if (code != undefined && code != "") {
575
    //   this.header1 += code;
576
    // }
577
    // if ((title != undefined && title != "") &&
578
    //   ((acronym != undefined && acronym != "") ||
579
    //     (code != undefined && code != ""))) {
580
    //   this.header1 += ")";
581
    // }
582

    
583
    this.header1 = "<div style=\"font-size:12px;\"><span>Project</span>";
584

    
585
    if(this.projectInfo.startDate || this.projectInfo.endDate) {
586
      this.header1 += "<span> . "
587
    }
588
    if(this.projectInfo.startDate && !this.projectInfo.endDate) {
589
      this.header1 += "from ";
590
    }
591
    if(!this.projectInfo.startDate && this.projectInfo.endDate) {
592
      this.header1 += "until ";
593
    }
594
    if(this.projectInfo.startDate) {
595
      let startYear = (new Date(this.projectInfo.startDate)).getFullYear();
596
      this.header1 += startYear;
597
    }
598
    if(this.projectInfo.startDate && this.projectInfo.endDate) {
599
      this.header1 += " - ";
600
    }
601
    if(this.projectInfo.endDate) {
602
      let endYear = (new Date(this.projectInfo.endDate)).getFullYear();
603
      this.header1 += endYear;
604
    }
605
    if(this.projectInfo.startDate || this.projectInfo.endDate) {
606
      this.header1 += "</span>"
607
    }
608

    
609
    if(this.projectInfo.status) {
610
      this.header1 += "<span> . "+this.projectInfo.status+"</span>";
611
    }
612

    
613
    if(this.projectInfo.funding && this.projectInfo.funding.code) {
614
      this.header1 += "<span> . "+this.projectInfo.funding.code+"</span>";
615
    }
616
    this.header1 += "</div>";
617

    
618
    this.header1 += "<h1 style=\"margin:0;\"><div><a href=\""+window.location.href +"\">";
619
    if(this.projectInfo.acronym) {
620
      this.header1 += this.projectInfo.acronym;
621
    } else {
622
      this.header1 += "[no title available]";
623
    }
624
    this.header1 += "</a></div></h2>";
625
    //<showTitle [titleName]="title" classNames="uk-margin-remove-bottom"></showTitle>
626
    if(this.projectInfo.title) {
627
      this.header1 += "<div><span>"+this.projectInfo.title+"</span></div>";
628
    }
629
  }
630

    
631
  public download(url, filename) {
632
    //var url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' }));
633
    var a = window.document.createElement('a');
634
    window.document.body.appendChild(a);
635
    a.setAttribute('style', 'display: none');
636
    a.href = url;
637
    a.download = filename;
638
    a.click();
639
    window.URL.revokeObjectURL(url);
640
    a.remove(); // remove the element
641
  }
642

    
643

    
644
  public onSelectActiveTab(activeTabId) {
645
    if(this.activeTab != activeTabId) {   // tab really changed
646
      if (activeTabId == 'summary') {
647
        this.activeTab = 'summary';
648
      } else if (activeTabId == 'publications') {
649
        this.activeTab = 'publications';
650
        this.searchPublications(1, this.searchNumber);
651
      } else if (activeTabId == 'datasets') {
652
        this.activeTab = 'datasets';
653
        this.searchDatasets(1, this.searchNumber);
654
      } else if (activeTabId == 'software') {
655
        this.activeTab = 'software';
656
        this.searchSoftware(1, this.searchNumber);
657
      } else if (activeTabId == 'other') {
658
        this.activeTab = "other";
659
        this.searchOrps(1, this.searchNumber);
660
      } else if (activeTabId == 'statistics') {
661
        this.activeTab = 'statistics';
662
        this.statsClicked = true;
663
      }
664
    }
665
  }
666

    
667
  private updateDescription(description: string) {
668
    this._meta.updateTag({content: description.substring(0, 160)}, "name='description'");
669
    this._meta.updateTag({content: description.substring(0, 160)}, "property='og:description'");
670
  }
671

    
672
  private updateTitle(title: string) {
673
    var _prefix = "";
674
    // if(!this.communityId) {
675
    //   _prefix = "OpenAIRE | ";
676
    // }
677
    // var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
678
    this._title.setTitle(title);
679
    this._meta.updateTag({content: title}, "property='og:title'");
680
  }
681

    
682
  private updateUrl(url: string) {
683
    this._meta.updateTag({content: url}, "property='og:url'");
684
  }
685

    
686
  private openLoading() {
687
    if (this.loading) {
688
      this.loading.open();
689
    }
690
  }
691

    
692
  private closeLoading() {
693
    if (this.loading) {
694
      this.loading.close();
695
    }
696
  }
697

    
698
  private setMessageLoading(message: string) {
699
    if (this.loading) {
700
      this.loading.message = message;
701
    }
702
  }
703

    
704
  public confirmOpenFileDownloadError(fileType: string) {
705
    this.alertCsvError.cancelButton = false;
706
    this.alertCsvError.okButton = true;
707
    this.alertCsvError.alertTitle = "ERROR DOWNLOADING "+fileType+" FILE";
708
    this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
709
    this.alertCsvError.okButtonText = "OK";
710
    this.alertCsvError.open();
711
  }
712

    
713
  private handleError(message: string, error) {
714
    console.error("Project Landing Page: " + message, error);
715
  }
716

    
717
  isRouteAvailable(routeToCheck: string) {
718
    for (let i = 0; i < this._router.config.length; i++) {
719
      let routePath: string = this._router.config[i].path;
720
      if (routePath == routeToCheck) {
721
        return true;
722
      }
723
    }
724
    return false;
725
  }
726

    
727
  private getEntityName (entityType:string, plural:boolean, full:boolean): string {
728
    if(entityType == "publication") {
729
      return "publication" + (plural ? "s" : "");
730
    } else if(entityType == "dataset") {
731
      return (full ? "research data" : ("dataset" + (plural ? "s" : "")));
732
    } else if(entityType == "software") {
733
      return "software";
734
    } else if(entityType == "other") {
735
      return (full ? ("other research product" + (plural ? "s" : "")) : "other");
736
    } else if(entityType == "dataprovider") {
737
      return (full ? ("content provider" + (plural ? "s" : "")) : "dataprovider" + (plural ? "s" : ""));
738
    } else {
739
      return entityType + (plural ? "s" : "");
740
    }
741
  }
742

    
743
  public getResultPreview(result: SearchResult, type: string): ResultPreview {
744
    return ResultPreview.searchResultConvert(result, type);
745
  }
746
  
747
  public scroll() {
748
    HelperFunctions.scroll();
749
  }
750

    
751
  public getParamsForSearchLink(type: string = "") {
752
    if(type) {
753
      return this.routerHelper.createQueryParams(['f0', 'fv0', 'type', 'qf', 'sortBy'], ['relprojectid', this.projectId, type, 'false', 'resultdateofacceptance,descending']);
754
    } else {
755
      return this.routerHelper.createQueryParams(['f0', 'fv0'], ['relprojectid', this.projectId]);
756
    }
757
  }
758

    
759
  public get hasPrimaryInfo(): boolean {
760
    return !!this.projectInfo && (
761
      !!this.projectInfo.description
762
    );
763
  }
764

    
765
  public get hasSecondaryInfo(): boolean {
766
    return !!this.projectInfo && (
767
      (!!this.projectInfo.organizations && this.projectInfo.organizations.length > 0)
768
    );
769
  }
770

    
771
  // public get numberOfTabs(): number {
772
  //   if(this.tabsAreInitialized) {
773
  //     return this._numberOfTabs;
774
  //   }
775
  //
776
  //   if(!this.projectInfo
777
  //     || this.fetchPublications.searchUtils.status == this.errorCodes.LOADING
778
  //     || this.fetchDatasets.searchUtils.status == this.errorCodes.LOADING
779
  //     || this.fetchSoftware.searchUtils.status == this.errorCodes.LOADING
780
  //     || this.fetchOrps.searchUtils.status == this.errorCodes.LOADING) {
781
  //     return 0;
782
  //   }
783
  //
784
  //   if (this.hasPrimaryInfo || this.hasSecondaryInfo) {
785
  //     this.firstTab = "summary";
786
  //     this._numberOfTabs++;
787
  //   }
788
  //   if(this.fetchPublications.searchUtils.totalResults > 0 || this.fetchDatasets.searchUtils.totalResults > 0
789
  //     || this.fetchSoftware.searchUtils.totalResults > 0 || this.fetchOrps.searchUtils.totalResults > 0) {
790
  //     if(this.fetchPublications.searchUtils.totalResults > 0) {
791
  //       if(this._numberOfTabs == 0) {
792
  //         this.firstTab = 'publications';
793
  //         this.searchPublicationsInit();
794
  //       }
795
  //       this._numberOfTabs++;
796
  //     }
797
  //     if(this.fetchDatasets.searchUtils.totalResults > 0) {
798
  //       if(this._numberOfTabs == 0) {
799
  //         this.firstTab = 'datasets';
800
  //         this.searchDatasetsInit();
801
  //       }
802
  //       this._numberOfTabs++;
803
  //     }
804
  //     if(this.fetchSoftware.searchUtils.totalResults > 0) {
805
  //       if(this._numberOfTabs == 0) {
806
  //         this.firstTab = 'software';
807
  //         this.searchSoftwareInit();
808
  //       }
809
  //       this._numberOfTabs++;
810
  //     }
811
  //     if(this.fetchOrps.searchUtils.totalResults > 0) {
812
  //       if(this._numberOfTabs == 0) {
813
  //         this.firstTab = 'other';
814
  //         this.searchOrpsInit();
815
  //       }
816
  //       this._numberOfTabs++;
817
  //     }
818
  //     this._numberOfTabs++;
819
  //   }
820
  //   this.activeTab = this.firstTab;
821
  //   this.tabsAreInitialized = true;
822
  //   return this._numberOfTabs;
823
  // }
824
}
(2-2/5)