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 {ResultLandingInfo} from "../../utils/entities/resultLandingInfo";
26
import {ResultPreview} from "../../utils/result-preview/result-preview";
27
import {SearchResult} from "../../utils/entities/searchResult";
28
import {IndexInfoService} from "../../utils/indexInfo.service";
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
  public firstTab: string = "";
79
  public _numberOfTabs: number = 0;
80
  public tabsAreInitialized: boolean = false;
81

    
82
  @ViewChild('statisticsModal') statisticsModal;
83

    
84
  @ViewChild('linkProjectModal') linkProjectModal;
85
  @ViewChild('shareResultsModal') shareResultsModal;
86
  @ViewChild('downloadReportModal') downloadReportModal;
87

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

    
94
  // Variables for entity selections on the right column
95
  public share_research_results_type: string = "results";
96
  public download_research_results_type: string = "";
97

    
98
  // Variables for publications, research data, software tabs
99
  public fetchPublications: FetchResearchResults;
100
  public fetchDatasets: FetchResearchResults;
101
  public fetchSoftware: FetchResearchResults;
102
  public fetchOrps: FetchResearchResults;
103
  public searchNumber: number = 5;
104

    
105
  public routerHelper: RouterHelper = new RouterHelper();
106
  public errorCodes: ErrorCodes = new ErrorCodes();
107
  public pageContents = null;
108
  public divContents = null;
109

    
110
  public indexUpdateDate: Date;
111
  public showFeedback: boolean;
112
  public feedbackFields: string [] = [
113
    'Title', 'Funding Information', 'Duration',
114
    'Organizations', 'Other'];
115

    
116
  @ViewChild(ModalLoading) loading: ModalLoading;
117
  // Alert box when something is wrong with CSV requests
118
  @ViewChild('AlertModalCsvError') alertCsvError;
119

    
120
  // Description variables for view more/less functionality
121
  public thresholdDescription: number = 670;
122
  public showNumDescription: number = 670;
123

    
124
  // Organizations variables for view more/less functionality
125
  public thresholdOrganizations: number = 20;
126
  public showNumOrganizations: number = 20;
127

    
128
  sub: any;
129
  piwiksub: any;
130
  infoSub: any;
131
  downloadFilePiwikSub: any;
132
  downloadHtmlFilePiwikSub: any;
133
  properties: EnvProperties;
134

    
135
  public subHTML: any;
136

    
137
  constructor(private  route: ActivatedRoute,
138
              private _router: Router,
139
              private _location: Location,
140
              private _meta: Meta,
141
              private _title: Title,
142
              private seoService: SEOService,
143
              private _piwikService: PiwikService,
144
              private helper: HelperService,
145
              private _projectService: ProjectService,
146
              private _searchResearchResultsService: SearchResearchResultsService,
147
              private _reportsService: ReportsService,
148
              private htmlService: HtmlProjectReportService,
149
              private indexInfoService: IndexInfoService) {}
150

    
151
  ngOnInit() {
152
    this.route.data
153
      .subscribe((data: { envSpecific: EnvProperties }) => {
154
        this.properties = data.envSpecific;
155
        if (typeof document !== 'undefined') {
156
          this.indexInfoService.getLastIndexDate(this.properties).subscribe(lastIndexUpdate => {
157
            if (lastIndexUpdate) {
158
              this.indexUpdateDate = new Date(lastIndexUpdate);
159
            }
160
          });
161
        }
162
        //this.getDivContents();
163
        this.getPageContents();
164
        this.updateUrl(this.properties.domain + this.properties.baseLink + this._router.url);
165

    
166
      });
167
    this.sub = this.route.queryParams.subscribe(params => {
168
      this.metricsClicked = false;
169
      this.statsClicked = false;
170
      this.fetchPublications = new FetchResearchResults(this._searchResearchResultsService);
171
      this.fetchDatasets = new FetchResearchResults(this._searchResearchResultsService);
172
      this.fetchSoftware = new FetchResearchResults(this._searchResearchResultsService);
173
      this.fetchOrps = new FetchResearchResults(this._searchResearchResultsService);
174

    
175
      var title = "Project";
176
      var description = "";
177

    
178
      this.header1 = "";
179

    
180
      this.updateTitle(title);
181
      this.updateDescription(description);
182
      this.projectId = params['projectId'];
183
      var grantId = params['grantId'];
184
      var funder = params['funder'];
185

    
186

    
187
      if (this.projectId  && StringUtils.isOpenAIREID(this.projectId)) {
188
        this.getProjectInfo(this.projectId);
189
        this.actionsAfterLoadId();
190
      } else if (grantId && funder) {
191
        this.getProjectInfoByGrantId(grantId, funder);
192
      } else {
193

    
194
        this.showLoading = false;
195
        this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
196
        //this.warningMessage = "No valid project id";
197
      }
198

    
199
      this.downloadURLAPI = this.properties.csvAPIURL;
200

    
201
      this.createClipboard();
202
      HelperFunctions.scroll();
203
    });
204
  }
205

    
206
  public getFileNameType(type: string) {
207
    if(type == "results") {
208
      return "research-outcomes";
209
    } else if(type == "publications") {
210
      return "publications";
211
    } else if(type == "datasets") {
212
      return "research-data";
213
    } else if(type == "software") {
214
      return "software";
215
    } else if(type == "other") {
216
      return "other-research-products";
217
    }
218
    return "results";
219
  }
220

    
221
  public getCsvParams(type: string) {
222
    // if(type == "results") {
223
    //   type = "publications&type=datasets&type=software&type=other";
224
    // }
225
    return "?format=csv-special&type="+type+"&fq=(relprojectid exact \"" + this.projectId + "\")";
226
  }
227

    
228
  private getPageContents() {
229
    if(this.communityId) {
230
      this.helper.getPageHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
231
        this.pageContents = contents;
232
      });
233
    }
234
  }
235

    
236
  private getDivContents() {
237
    if(this.communityId) {
238
      this.helper.getDivHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
239
        this.divContents = contents;
240
      });
241
    }
242
  }
243

    
244
  getDynamicContent(type: string) {
245
    return  "<script type=\"text/javascript\">"
246
      + "\n<!--"
247
      + "\ndocument.write('<div id=\"oa_widget\"></div>');"
248
      + "\ndocument.write('<script type=\"text/javascript\""
249
      + " src=\"" + this.properties.widgetLink
250
      + this.projectId + "&type="
251
      + type
252
      + "\"></script>');"
253
      + "\n-->"
254
      + "\n</script>";
255
  }
256

    
257
  actionsAfterLoadId() {
258
    //this.getProjectInfo(this.projectId);
259
    //this.searchPublications();
260

    
261
    if (typeof document !== 'undefined') {
262
      this.fetchPublications.getNumForEntity("publication", "project", this.projectId, this.properties);
263
      this.fetchDatasets.getNumForEntity("dataset", "project", this.projectId, this.properties);
264
      this.fetchSoftware.getNumForEntity("software", "project", this.projectId, this.properties);
265
      this.fetchOrps.getNumForEntity("other", "project", this.projectId, this.properties);
266
    }
267
  }
268

    
269
  ngOnDestroy() {
270
    if (this.sub) {
271
      this.sub.unsubscribe();
272
    }
273
    if (this.piwiksub) {
274
      this.piwiksub.unsubscribe();
275
    }
276
    if (this.infoSub) {
277
      this.infoSub.unsubscribe();
278
    }
279
    if (this.downloadFilePiwikSub) {
280
      this.downloadFilePiwikSub.unsubscribe();
281
    }
282
    if(this.downloadHtmlFilePiwikSub) {
283
      this.downloadHtmlFilePiwikSub.unsubscribe();
284
    }
285
  }
286

    
287
  private createClipboard() {
288
    if (typeof window !== 'undefined') {
289
      delete this.clipboard;
290
      let Clipboard;
291
      Clipboard = require('clipboard');
292
      this.clipboard = new Clipboard('.clipboard_btn');
293
    }
294
  }
295

    
296
  public searchPublications(page: number, size: number) {
297
    if (this.reloadPublications &&
298
      (this.fetchPublications.searchUtils.status == this.errorCodes.LOADING ||
299
        (this.fetchPublications.searchUtils.status == this.errorCodes.DONE && this.fetchPublications.searchUtils.totalResults > 0)
300
      )
301
    ) {
302
      this.fetchPublications.getResultsForEntity("publication", "project", this.projectId, page, size, this.properties);
303
    }
304
    this.reloadPublications = false;
305
  }
306

    
307
  public searchDatasets(page: number, size: number) {
308
    if (this.reloadDatasets &&
309
      (this.fetchDatasets.searchUtils.status == this.errorCodes.LOADING ||
310
        (this.fetchDatasets.searchUtils.status == this.errorCodes.DONE && this.fetchDatasets.searchUtils.totalResults > 0)
311
      )
312
    ) {
313
      this.fetchDatasets.getResultsForEntity("dataset", "project", this.projectId, page, size, this.properties);
314
    }
315
    this.reloadDatasets = false;
316
  }
317

    
318
  private searchSoftware(page: number, size: number) {
319
    if (this.reloadSoftware &&
320
      (this.fetchSoftware.searchUtils.status == this.errorCodes.LOADING ||
321
        (this.fetchSoftware.searchUtils.status == this.errorCodes.DONE && this.fetchSoftware.searchUtils.totalResults > 0)
322
      )
323
    ) {
324
      this.fetchSoftware.getResultsForEntity("software", "project", this.projectId, page, size, this.properties);
325
    }
326
    this.reloadSoftware = false;
327
  }
328

    
329
  private searchOrps(page: number, size: number) {
330
    if (this.reloadOrps &&
331
      (this.fetchOrps.searchUtils.status == this.errorCodes.LOADING ||
332
        (this.fetchOrps.searchUtils.status == this.errorCodes.DONE && this.fetchOrps.searchUtils.totalResults > 0)
333
      )
334
    ) {
335
      this.fetchOrps.getResultsForEntity("other", "project", this.projectId, page, size, this.properties);
336
    }
337
    this.reloadOrps = false;
338
  }
339

    
340
  private getProjectInfo(id: string) {
341
    this.warningMessage = '';
342
    this.errorMessage = "";
343
    this.showLoading = true;
344

    
345
    this.projectInfo = null;
346

    
347
    this.infoSub = this._projectService.getProjectInfo(id, this.properties).subscribe(
348
      data => {
349
        this.projectInfo = data;
350

    
351
        this.actionsAfterGettingProjectInfo();
352
      },
353
      err => {
354
        //console.log(err);
355
        this.handleError("Error getting project for id: " + this.projectId, err);
356
        if(err.status == 404) {
357
          this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
358
        }
359
        this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.properties.searchLinkToProjects);
360
        this.errorMessage = 'No project found';
361
        this.showLoading = false;
362
      }
363
    );
364
  }
365

    
366
  private getProjectInfoByGrantId(grantId: string, funder: string) {
367
    this.warningMessage = '';
368
    this.errorMessage = "";
369
    this.showLoading = true;
370

    
371
    this.projectInfo = null;
372

    
373
    this._projectService.getProjectInfoByGrantId(grantId, funder, this.properties).subscribe(
374
      data => {
375

    
376
        this.projectInfo = data;
377

    
378
        this.actionsAfterGettingProjectInfo();
379
        this.projectId = this.projectInfo.id;
380
        this.actionsAfterLoadId();
381
      },
382
      err => {
383
        //console.log(err);
384
        this.handleError("Error getting project for grant id: " + grantId + " and funder: " + funder, err);
385
        if(err.status == 404) {
386
          this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
387
        }
388
        this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.properties.searchLinkToProjects);
389
        this.errorMessage = 'No project found';
390
        this.showLoading = false;
391
      }
392
    );
393
  }
394

    
395
  actionsAfterGettingProjectInfo() {
396
    this.projectName = this.projectInfo.acronym;
397
    if (this.projectName == undefined || this.projectName == '') {
398
      this.projectName = this.projectInfo.title;
399
    }
400
    this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this._router.url);
401
    this.updateTitle(this.projectName);
402
    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:"")));
403
    if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
404
      this.piwiksub = this._piwikService.trackView(this.properties, this.projectName, this.piwikSiteId).subscribe();
405
    }
406

    
407
    this.project = {
408
      funderId: "",
409
      funderName: ((this.projectInfo.funding) ? this.projectInfo.funding.funderShortName: ''),
410
      projectId: this.projectId,
411
      projectName: this.projectInfo.title,
412
      projectAcronym: this.projectInfo.acronym,
413
      startDate: this.projectInfo.startDate,
414
      endDate: this.projectInfo.endDate
415
    };
416

    
417
    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';
418

    
419
    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';
420

    
421
    //stats tab charts
422
    if (this.properties.useNewStatistisTool) {
423
      this.chartScientificResultsUrl = this.properties.statisticsFrameNewAPIURL +
424
        '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"}}}');
425
      this.chartAccessModeUrl =  this.properties.statisticsFrameNewAPIURL +
426
        'chart?json='+StringUtils.URIEncode(
427
        '{"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"}}}');
428
      this.chartDatasourcesUrl =  this.properties.statisticsFrameNewAPIURL +
429
        'chart?json='+StringUtils.URIEncode(
430
        '{"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"}}}');
431
    } else {
432
      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%';
433
      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%';
434
      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%';
435
    }
436

    
437
    this.showLoading = false;
438
  }
439

    
440
  public downloadCsvFile(url: string, filename: string) {
441
    this.openLoading();
442
    this.setMessageLoading("Downloading CSV file");
443

    
444
    this._reportsService.downloadCSVFile(url).subscribe(
445
      data => {
446
        this.closeLoading();
447

    
448
        let url = window.URL.createObjectURL(data);
449
        this.download(url, filename+".csv");
450

    
451
        if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
452
          this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url).subscribe();
453
        }
454
      },
455
      error => {
456
        //console.log("Error downloading the file.");
457
        this.handleError("Error downloading file: " + filename, error);
458

    
459
        this.closeLoading();
460
        this.confirmOpenFileDownloadError("CSV");
461
      }/*,
462
            () => console.log('Completed file download.')*/
463
    );
464
  }
465

    
466
  public metricsResults($event) {
467
    this.totalViews = $event.totalViews;
468
    this.totalDownloads = $event.totalDownloads;
469
    this.pageViews = $event.pageViews;
470
  }
471
  
472
  public get hasMetrics(): boolean {
473
    return !(this.totalViews && this.totalDownloads && this.pageViews) || this.totalViews > 0 || this.totalDownloads > 0||this.pageViews > 0;
474
  }
475

    
476
  public openStatistics() {
477
    this.statsClicked = true;
478
    this.statisticsModal.cancelButton = false;
479
    this.statisticsModal.okButton = false;
480
    this.statisticsModal.alertTitle = "Statistics of";
481
    this.statisticsModal.open();
482
  }
483

    
484
  public openLinkProjectModal() {
485
    this.linkProjectModal.cancelButton = false;
486
    this.linkProjectModal.okButton = false;
487
    this.linkProjectModal.alertTitle = "Link this project to";
488
    //this.linkProjectModal.alertHeader = false;
489
    this.linkProjectModal.open();
490
  }
491

    
492
  public openShareResultsModal() {
493
    this.shareResultsModal.cancelButton = false;
494
    this.shareResultsModal.okButton = false;
495
    this.shareResultsModal.alertTitle = "Share results";
496
    this.shareResultsModal.open();
497
  }
498

    
499
  public openDownloadReportModal() {
500
    if(this.fetchPublications.searchUtils.totalResults > 0 || this.fetchDatasets.searchUtils.totalResults > 0 ||
501
       this.fetchSoftware.searchUtils.totalResults > 0 || this.fetchOrps.searchUtils.totalResults > 0) {
502
      this.download_research_results_type = "results";
503
    }
504
    this.downloadReportModal.cancelButton = false;
505
    this.downloadReportModal.okButton = false;
506
    this.downloadReportModal.alertTitle = "Download report";
507
    this.downloadReportModal.open();
508
  }
509

    
510
  private createHeaders(type: string) {
511
    this.openLoading();
512
    this.setMessageLoading("Downloading HTML file");
513

    
514
    if(!this.header1) {
515
      this.createHeader1();
516
    }
517

    
518
    if (type == "publications") {
519
      this.header2 = this.fetchPublications.searchUtils.totalResults.toLocaleString('en-US') + " publications";
520
    } else if (type == "datasets") {
521
      this.header2 = this.fetchDatasets.searchUtils.totalResults.toLocaleString('en-US') + " research data";
522
    } else if (type == "software") {
523
      this.header2 = this.fetchSoftware.searchUtils.totalResults.toLocaleString('en-US') + " software";
524
    } else if (type == "other") {
525
      this.header2 = this.fetchOrps.searchUtils.totalResults.toLocaleString('en-US') + " other research products";
526
    } else if (type == "results") {
527
      let totalResults: number = (+this.fetchPublications.searchUtils.totalResults) +
528
        (+this.fetchDatasets.searchUtils.totalResults) +
529
        (+this.fetchSoftware.searchUtils.totalResults) +
530
        (+this.fetchOrps.searchUtils.totalResults);
531

    
532
      this.header2 = totalResults.toLocaleString('en-US') + " research outcomes";
533
    }
534
  }
535

    
536
  private createHtmlFile(type: string, filename: string) {
537
    let intro: string = '<!doctype html>';
538
    intro += '<html lang="en-gb" dir="ltr" vocab="http://schema.org/">';
539
    intro += '<head>';
540
    intro += '<title>' + this.header1 + '</title>';
541
    intro += '</head>';
542

    
543
    if (typeof window !== 'undefined') {
544
      this.subHTML = this.htmlService.getHTML(this.projectId, type, this.properties.csvAPIURL).subscribe(
545
        data => {
546
          //console.info(data);
547
          this.htmlResultDownload = intro + '<body><div>' + this.header1 + '</div><div><h4>' + this.header2 + '</h4></div>';
548
          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>";
549
          this.htmlResultDownload += '</body></html>';
550

    
551
          //console.info(this.htmlResultDownload);
552
          this.closeLoading();
553

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

    
557
          if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
558
            this.downloadHtmlFilePiwikSub = this._piwikService.trackDownload(this.properties, url).subscribe();
559
          }
560
        },
561
        err => {
562
          this.handleError("Error getting html for id: " + this.projectId, err);
563
          //this.errorMessage = 'Service not available';
564
          this.closeLoading();
565
          this.confirmOpenFileDownloadError("HTML");
566
        }
567
      );
568
    } else {
569
      this.closeLoading();
570
      this.confirmOpenFileDownloadError("HTML");
571
    }
572
  }
573

    
574
  downloadHtmlFile(type: string, filename: string) {
575
    this.createHeaders(type);
576
    this.createHtmlFile(type, filename);
577
  }
578

    
579
  createHeader1() {
580
    // if (title != undefined && title != "") {
581
    //   this.header1 += title;
582
    // }
583
    // if ((title != undefined && title != "") &&
584
    //   ((acronym != undefined && acronym != "") ||
585
    //     (code != undefined && code != ""))) {
586
    //   this.header1 += "(";
587
    // }
588
    // if (acronym != undefined && acronym != "") {
589
    //   this.header1 += acronym + " - ";
590
    // }
591
    // if (code != undefined && code != "") {
592
    //   this.header1 += code;
593
    // }
594
    // if ((title != undefined && title != "") &&
595
    //   ((acronym != undefined && acronym != "") ||
596
    //     (code != undefined && code != ""))) {
597
    //   this.header1 += ")";
598
    // }
599

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

    
602
    if(this.projectInfo.startDate || this.projectInfo.endDate) {
603
      this.header1 += "<span> . "
604
    }
605
    if(this.projectInfo.startDate && !this.projectInfo.endDate) {
606
      this.header1 += "from ";
607
    }
608
    if(!this.projectInfo.startDate && this.projectInfo.endDate) {
609
      this.header1 += "until ";
610
    }
611
    if(this.projectInfo.startDate) {
612
      let startYear = (new Date(this.projectInfo.startDate)).getFullYear();
613
      this.header1 += startYear;
614
    }
615
    if(this.projectInfo.startDate && this.projectInfo.endDate) {
616
      this.header1 += " - ";
617
    }
618
    if(this.projectInfo.endDate) {
619
      let endYear = (new Date(this.projectInfo.endDate)).getFullYear();
620
      this.header1 += endYear;
621
    }
622
    if(this.projectInfo.startDate || this.projectInfo.endDate) {
623
      this.header1 += "</span>"
624
    }
625

    
626
    if(this.projectInfo.status) {
627
      this.header1 += "<span> . "+this.projectInfo.status+"</span>";
628
    }
629

    
630
    if(this.projectInfo.funding && this.projectInfo.funding.code) {
631
      this.header1 += "<span> . "+this.projectInfo.funding.code+"</span>";
632
    }
633
    this.header1 += "</div>";
634

    
635
    this.header1 += "<h1 style=\"margin:0;\"><div><a href=\""+window.location.href +"\">";
636
    if(this.projectInfo.acronym) {
637
      this.header1 += this.projectInfo.acronym;
638
    } else {
639
      this.header1 += "[no title available]";
640
    }
641
    this.header1 += "</a></div></h2>";
642
    //<showTitle [titleName]="title" classNames="uk-margin-remove-bottom"></showTitle>
643
    if(this.projectInfo.title) {
644
      this.header1 += "<div><span>"+this.projectInfo.title+"</span></div>";
645
    }
646
  }
647

    
648
  public download(url, filename) {
649
    //var url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' }));
650
    var a = window.document.createElement('a');
651
    window.document.body.appendChild(a);
652
    a.setAttribute('style', 'display: none');
653
    a.href = url;
654
    a.download = filename;
655
    a.click();
656
    window.URL.revokeObjectURL(url);
657
    a.remove(); // remove the element
658
  }
659

    
660
  // copyToClipboard(element: HTMLElement) {
661
  //   if (typeof document !== 'undefined') {
662
  //     if (window.getSelection) {
663
  //       const selection = window.getSelection();
664
  //       const range = document.createRange();
665
  //       range.selectNodeContents(element);
666
  //       selection.removeAllRanges();
667
  //       selection.addRange(range);
668
  //       document.execCommand('copy');
669
  //     } else {
670
  //       console.warn("Could not select text in node: Unsupported browser.");
671
  //     }
672
  //   }
673
  // }
674

    
675
  public onSelectActiveTab(activeTabId) {
676
    if(this.activeTab != activeTabId) {   // tab really changed
677
      if (activeTabId == 'summary') {
678
        this.activeTab = 'summary';
679
      } else if (activeTabId == 'publications') {
680
        this.activeTab = 'publications';
681
        this.searchPublications(1, this.searchNumber);
682
      } else if (activeTabId == 'datasets') {
683
        this.activeTab = 'datasets';
684
        this.searchDatasets(1, this.searchNumber);
685
      } else if (activeTabId == 'software') {
686
        this.activeTab = 'software';
687
        this.searchSoftware(1, this.searchNumber);
688
      } else if (activeTabId == 'other') {
689
        this.activeTab = "other";
690
        this.searchOrps(1, this.searchNumber);
691
      } else if (activeTabId == 'statistics') {
692
        this.activeTab = 'statistics';
693
        this.statsClicked = true;
694
      }
695
    }
696
  }
697

    
698
  private updateDescription(description: string) {
699
    this._meta.updateTag({content: description.substring(0, 160)}, "name='description'");
700
    this._meta.updateTag({content: description.substring(0, 160)}, "property='og:description'");
701
  }
702

    
703
  private updateTitle(title: string) {
704
    var _prefix = "";
705
    // if(!this.communityId) {
706
    //   _prefix = "OpenAIRE | ";
707
    // }
708
    // var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
709
    this._title.setTitle(title);
710
    this._meta.updateTag({content: title}, "property='og:title'");
711
  }
712

    
713
  private updateUrl(url: string) {
714
    this._meta.updateTag({content: url}, "property='og:url'");
715
  }
716

    
717
  private openLoading() {
718
    if (this.loading) {
719
      this.loading.open();
720
    }
721
  }
722

    
723
  private closeLoading() {
724
    if (this.loading) {
725
      this.loading.close();
726
    }
727
  }
728

    
729
  private setMessageLoading(message: string) {
730
    if (this.loading) {
731
      this.loading.message = message;
732
    }
733
  }
734

    
735
  public confirmOpenFileDownloadError(fileType: string) {
736
    this.alertCsvError.cancelButton = false;
737
    this.alertCsvError.okButton = true;
738
    this.alertCsvError.alertTitle = "ERROR DOWNLOADING "+fileType+" FILE";
739
    this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
740
    this.alertCsvError.okButtonText = "OK";
741
    this.alertCsvError.open();
742
  }
743

    
744
  private handleError(message: string, error) {
745
    console.error("Project Landing Page: " + message, error);
746
  }
747

    
748
  isRouteAvailable(routeToCheck: string) {
749
    for (let i = 0; i < this._router.config.length; i++) {
750
      let routePath: string = this._router.config[i].path;
751
      if (routePath == routeToCheck) {
752
        return true;
753
      }
754
    }
755
    return false;
756
  }
757

    
758
  private getEntityName (entityType:string, plural:boolean, full:boolean): string {
759
    if(entityType == "publication") {
760
      return "publication" + (plural ? "s" : "");
761
    } else if(entityType == "dataset") {
762
      return (full ? "research data" : ("dataset" + (plural ? "s" : "")));
763
    } else if(entityType == "software") {
764
      return "software";
765
    } else if(entityType == "other") {
766
      return (full ? ("other research product" + (plural ? "s" : "")) : "other");
767
    } else if(entityType == "dataprovider") {
768
      return (full ? ("content provider" + (plural ? "s" : "")) : "dataprovider" + (plural ? "s" : ""));
769
    } else {
770
      return entityType + (plural ? "s" : "");
771
    }
772
  }
773

    
774
  public getResultPreview(result: SearchResult, type: string): ResultPreview {
775
    return ResultPreview.searchResultConvert(result, type);
776
  }
777
  
778
  public scroll() {
779
    HelperFunctions.scroll();
780
  }
781

    
782
  public getParamsForSearchLink(type: string = "") {
783
    if(type) {
784
      return this.routerHelper.createQueryParams(['f0', 'fv0', 'type', 'qf', 'sortBy'], ['relprojectid', this.projectId, type, 'false', 'resultdateofacceptance,descending']);
785
    } else {
786
      return this.routerHelper.createQueryParams(['f0', 'fv0'], ['relprojectid', this.projectId]);
787
    }
788
  }
789

    
790
  public get hasPrimaryInfo(): boolean {
791
    return !!this.projectInfo && (
792
      !!this.projectInfo.description
793
    );
794
  }
795

    
796
  public get hasSecondaryInfo(): boolean {
797
    return !!this.projectInfo && (
798
      (!!this.projectInfo.organizations && this.projectInfo.organizations.length > 0)
799
    );
800
  }
801

    
802
  // public get numberOfTabs(): number {
803
  //   if(this.tabsAreInitialized) {
804
  //     return this._numberOfTabs;
805
  //   }
806
  //
807
  //   if(!this.projectInfo
808
  //     || this.fetchPublications.searchUtils.status == this.errorCodes.LOADING
809
  //     || this.fetchDatasets.searchUtils.status == this.errorCodes.LOADING
810
  //     || this.fetchSoftware.searchUtils.status == this.errorCodes.LOADING
811
  //     || this.fetchOrps.searchUtils.status == this.errorCodes.LOADING) {
812
  //     return 0;
813
  //   }
814
  //
815
  //   if (this.hasPrimaryInfo || this.hasSecondaryInfo) {
816
  //     this.firstTab = "summary";
817
  //     this._numberOfTabs++;
818
  //   }
819
  //   if(this.fetchPublications.searchUtils.totalResults > 0 || this.fetchDatasets.searchUtils.totalResults > 0
820
  //     || this.fetchSoftware.searchUtils.totalResults > 0 || this.fetchOrps.searchUtils.totalResults > 0) {
821
  //     if(this.fetchPublications.searchUtils.totalResults > 0) {
822
  //       if(this._numberOfTabs == 0) {
823
  //         this.firstTab = 'publications';
824
  //         this.searchPublicationsInit();
825
  //       }
826
  //       this._numberOfTabs++;
827
  //     }
828
  //     if(this.fetchDatasets.searchUtils.totalResults > 0) {
829
  //       if(this._numberOfTabs == 0) {
830
  //         this.firstTab = 'datasets';
831
  //         this.searchDatasetsInit();
832
  //       }
833
  //       this._numberOfTabs++;
834
  //     }
835
  //     if(this.fetchSoftware.searchUtils.totalResults > 0) {
836
  //       if(this._numberOfTabs == 0) {
837
  //         this.firstTab = 'software';
838
  //         this.searchSoftwareInit();
839
  //       }
840
  //       this._numberOfTabs++;
841
  //     }
842
  //     if(this.fetchOrps.searchUtils.totalResults > 0) {
843
  //       if(this._numberOfTabs == 0) {
844
  //         this.firstTab = 'other';
845
  //         this.searchOrpsInit();
846
  //       }
847
  //       this._numberOfTabs++;
848
  //     }
849
  //     this._numberOfTabs++;
850
  //   }
851
  //   this.activeTab = this.firstTab;
852
  //   this.tabsAreInitialized = true;
853
  //   return this._numberOfTabs;
854
  // }
855
}
(2-2/5)