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
import {properties} from "../../../../environments/environment";
30

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

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

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

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

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

    
60
  public project;
61

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

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

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

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

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

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

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

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

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

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

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

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

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

    
124
  subscriptions = [];
125
  properties: EnvProperties;
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

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

    
154

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

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

    
166
      this.header1 = "";
167

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

    
174

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
327
    this.projectInfo = null;
328

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

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

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

    
353
    this.projectInfo = null;
354

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

    
358
        this.projectInfo = data;
359

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

    
377
  actionsAfterGettingProjectInfo() {
378
    this.projectName = this.projectInfo.acronym;
379
    if (this.projectName == undefined || this.projectName == '') {
380
      this.projectName = this.projectInfo.title;
381
    }
382
    this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this._router.url);
383
    this.updateTitle(this.projectName);
384
    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:"")));
385
    if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
386
      this.subscriptions.push(this._piwikService.trackView(this.properties, this.projectName, this.piwikSiteId).subscribe());
387
    }
388

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

    
399
    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';
400

    
401
    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';
402

    
403
    //stats tab charts
404
    if (this.properties.useNewStatistisTool) {
405
      this.chartScientificResultsUrl = this.properties.statisticsFrameNewAPIURL +
406
        '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"}}}');
407
      this.chartAccessModeUrl =  this.properties.statisticsFrameNewAPIURL +
408
        'chart?json='+StringUtils.URIEncode(
409
        '{"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"}}}');
410
      this.chartDatasourcesUrl =  this.properties.statisticsFrameNewAPIURL +
411
        'chart?json='+StringUtils.URIEncode(
412
        '{"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"}}}');
413
    } else {
414
      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%';
415
      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%';
416
      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%';
417
    }
418

    
419
    this.showLoading = false;
420
  }
421

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
525
    if (typeof window !== 'undefined') {
526
      this.subscriptions.push(this.htmlService.getHTML(this.projectId, type, this.properties.csvAPIURL).subscribe(
527
        data => {
528
          //console.info(data);
529
          this.htmlResultDownload = intro + '<body><div>' + this.header1 + '</div><div><h4>' + this.header2 + '</h4></div>';
530
          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>";
531
          this.htmlResultDownload += '</body></html>';
532

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

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

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

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

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

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

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

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

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

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

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

    
642

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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