Project

General

Profile

1 61381 k.triantaf
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
  private reloadDmps: boolean = true;
90
91
  // Variables for entity selections on the right column
92
  public share_research_results_type: string = "results";
93
  public download_research_results_type: string = "";
94
95
  // Variables for publications, research data, software tabs
96
  public fetchPublications: FetchResearchResults;
97
  public fetchDatasets: FetchResearchResults;
98
  public fetchSoftware: FetchResearchResults;
99
  public fetchOrps: FetchResearchResults;
100
  public fetchDmps: FetchResearchResults;
101
  public searchNumber: number = 5;
102
103
  public routerHelper: RouterHelper = new RouterHelper();
104
  public errorCodes: ErrorCodes = new ErrorCodes();
105
  public pageContents = null;
106
  public divContents = null;
107
108
  public indexUpdateDate: Date;
109
  public showFeedback: boolean;
110
  public feedbackFields: string [] = [
111
    'Title', 'Funding Information', 'Duration',
112
    'Organizations', 'Other'];
113
114
  @ViewChild(ModalLoading) loading: ModalLoading;
115
  // Alert box when something is wrong with CSV requests
116
  @ViewChild('AlertModalCsvError') alertCsvError;
117
118
  // Description variables for view more/less functionality
119
  public thresholdDescription: number = 670;
120
  public showNumDescription: number = 670;
121
122
  // Organizations variables for view more/less functionality
123
  public thresholdOrganizations: number = 20;
124
  public showNumOrganizations: number = 20;
125
126
  subscriptions = [];
127
  properties: EnvProperties;
128
  constructor(private  route: ActivatedRoute,
129
              private _router: Router,
130
              private _location: Location,
131
              private _meta: Meta,
132
              private _title: Title,
133
              private seoService: SEOService,
134
              private _piwikService: PiwikService,
135
              private helper: HelperService,
136
              private _projectService: ProjectService,
137
              private _searchResearchResultsService: SearchResearchResultsService,
138
              private _reportsService: ReportsService,
139
              private htmlService: HtmlProjectReportService,
140
              private indexInfoService: IndexInfoService) {}
141
142
  ngOnInit() {
143
144
        this.properties = properties;
145
        if (typeof document !== 'undefined') {
146
          this.subscriptions.push(this.indexInfoService.getLastIndexDate(this.properties).subscribe(lastIndexUpdate => {
147
            if (lastIndexUpdate) {
148
              this.indexUpdateDate = new Date(lastIndexUpdate);
149
            }
150
          }));
151
        }
152
        //this.getDivContents();
153
        this.getPageContents();
154
        this.updateUrl(this.properties.domain + this.properties.baseLink + this._router.url);
155
156
157
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
158
      this.metricsClicked = false;
159
      this.statsClicked = false;
160
      this.fetchPublications = new FetchResearchResults(this._searchResearchResultsService);
161
      this.fetchDatasets = new FetchResearchResults(this._searchResearchResultsService);
162
      this.fetchSoftware = new FetchResearchResults(this._searchResearchResultsService);
163
      this.fetchOrps = new FetchResearchResults(this._searchResearchResultsService);
164
      this.fetchDmps = new FetchResearchResults(this._searchResearchResultsService);
165
      var title = "Project";
166
      var description = "";
167
168
      this.header1 = "";
169
170
      this.updateTitle(title);
171
      this.updateDescription(description);
172
      this.projectId = params['projectId'];
173
      var grantId = params['grantId'];
174
      var funder = params['funder'];
175
176
177
      if (this.projectId  && StringUtils.isOpenAIREID(this.projectId)) {
178
        this.getProjectInfo(this.projectId);
179
        this.actionsAfterLoadId();
180
      } else if (grantId && funder) {
181
        this.getProjectInfoByGrantId(grantId, funder);
182
      } else {
183
184
        this.showLoading = false;
185
        this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
186
        //this.warningMessage = "No valid project id";
187
      }
188
189
      this.downloadURLAPI = this.properties.csvAPIURL;
190
191
      this.createClipboard();
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
      this.searchDmps(1, this.searchNumber);
256
    }
257
  }
258
259
  ngOnDestroy() {
260
    this.subscriptions.forEach(subscription => {
261
      if (subscription instanceof Subscriber) {
262
        subscription.unsubscribe();
263
      }
264
    });
265
    this.fetchDatasets.clearSubscriptions();
266
    this.fetchPublications.clearSubscriptions();
267
    this.fetchSoftware.clearSubscriptions();
268
    this.fetchOrps.clearSubscriptions();
269
    this.fetchDmps.clearSubscriptions();
270
  }
271
272
  private createClipboard() {
273
    if (typeof window !== 'undefined') {
274
      delete this.clipboard;
275
      let Clipboard;
276
      Clipboard = require('clipboard');
277
      this.clipboard = new Clipboard('.clipboard_btn');
278
    }
279
  }
280
281
  public searchPublications(page: number, size: number) {
282
    if (this.reloadPublications &&
283
      (this.fetchPublications.searchUtils.status == this.errorCodes.LOADING ||
284
        (this.fetchPublications.searchUtils.status == this.errorCodes.DONE && this.fetchPublications.searchUtils.totalResults > 0)
285
      )
286
    ) {
287
      this.fetchPublications.getResultsForEntity("publication", "project", this.projectId, page, size, this.properties);
288
    }
289
    this.reloadPublications = false;
290
  }
291
292
  public searchDmps(page: number, size: number) {
293
    if (this.reloadDmps &&
294
      (this.fetchDmps.searchUtils.status == this.errorCodes.LOADING ||
295
        (this.fetchDmps.searchUtils.status == this.errorCodes.DONE && this.fetchDmps.searchUtils.totalResults > 0)
296
      )
297
    ) {
298
      this.fetchDmps.getDmps("project", this.projectId, page, size, this.properties);
299
    }
300
    this.reloadDmps = false;
301
  }
302
303
  public searchDatasets(page: number, size: number) {
304
    if (this.reloadDatasets &&
305
      (this.fetchDatasets.searchUtils.status == this.errorCodes.LOADING ||
306
        (this.fetchDatasets.searchUtils.status == this.errorCodes.DONE && this.fetchDatasets.searchUtils.totalResults > 0)
307
      )
308
    ) {
309
      this.fetchDatasets.getResultsForEntity("dataset", "project", this.projectId, page, size, this.properties);
310
    }
311
    this.reloadDatasets = false;
312
  }
313
314
  private searchSoftware(page: number, size: number) {
315
    if (this.reloadSoftware &&
316
      (this.fetchSoftware.searchUtils.status == this.errorCodes.LOADING ||
317
        (this.fetchSoftware.searchUtils.status == this.errorCodes.DONE && this.fetchSoftware.searchUtils.totalResults > 0)
318
      )
319
    ) {
320
      this.fetchSoftware.getResultsForEntity("software", "project", this.projectId, page, size, this.properties);
321
    }
322
    this.reloadSoftware = false;
323
  }
324
325
  private searchOrps(page: number, size: number) {
326
    if (this.reloadOrps &&
327
      (this.fetchOrps.searchUtils.status == this.errorCodes.LOADING ||
328
        (this.fetchOrps.searchUtils.status == this.errorCodes.DONE && this.fetchOrps.searchUtils.totalResults > 0)
329
      )
330
    ) {
331
      this.fetchOrps.getResultsForEntity("other", "project", this.projectId, page, size, this.properties);
332
    }
333
    this.reloadOrps = false;
334
  }
335
336
  private getProjectInfo(id: string) {
337
    this.warningMessage = '';
338
    this.errorMessage = "";
339
    this.showLoading = true;
340
341
    this.projectInfo = null;
342
343
    this.subscriptions.push(this._projectService.getProjectInfo(id, this.properties).subscribe(
344
      data => {
345
        this.projectInfo = data;
346
347
        this.actionsAfterGettingProjectInfo();
348
      },
349
      err => {
350
        //console.log(err);
351
        this.handleError("Error getting project for id: " + this.projectId, err);
352
        if(err.status == 404) {
353
          this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
354
        }
355
        this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.properties.searchLinkToProjects);
356
        this.errorMessage = 'No project found';
357
        this.showLoading = false;
358
      }
359
    ));
360
  }
361
362
  private getProjectInfoByGrantId(grantId: string, funder: string) {
363
    this.warningMessage = '';
364
    this.errorMessage = "";
365
    this.showLoading = true;
366
367
    this.projectInfo = null;
368
369
    this.subscriptions.push(this._projectService.getProjectInfoByGrantId(grantId, funder, this.properties).subscribe(
370
      data => {
371
372
        this.projectInfo = data;
373
374
        this.actionsAfterGettingProjectInfo();
375
        this.projectId = this.projectInfo.id;
376
        this.actionsAfterLoadId();
377
      },
378
      err => {
379
        //console.log(err);
380
        this.handleError("Error getting project for grant id: " + grantId + " and funder: " + funder, err);
381
        if(err.status == 404) {
382
          this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}});
383
        }
384
        this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.properties.searchLinkToProjects);
385
        this.errorMessage = 'No project found';
386
        this.showLoading = false;
387
      }
388
    ));
389
  }
390
391
  actionsAfterGettingProjectInfo() {
392
    this.projectName = this.projectInfo.acronym;
393
    if (this.projectName == undefined || this.projectName == '') {
394
      this.projectName = this.projectInfo.title;
395
    }
396
    this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this._router.url);
397
    this.updateTitle(this.projectName);
398
    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:"")));
399
    if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
400
      this.subscriptions.push(this._piwikService.trackView(this.properties, this.projectName, this.piwikSiteId).subscribe());
401
    }
402
403
    this.project = {
404
      funderId: "",
405
      funderName: ((this.projectInfo.funding) ? this.projectInfo.funding.funderShortName: ''),
406
      projectId: this.projectId,
407
      projectName: this.projectInfo.title,
408
      projectAcronym: this.projectInfo.acronym,
409
      startDate: this.projectInfo.startDate,
410
      endDate: this.projectInfo.endDate
411
    };
412
413
    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';
414
415
    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';
416
417
    //stats tab charts
418
    if (this.properties.useNewStatistisTool) {
419
      this.chartScientificResultsUrl = this.properties.statisticsFrameNewAPIURL +
420
        '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"}}}');
421
      this.chartAccessModeUrl =  this.properties.statisticsFrameNewAPIURL +
422
        'chart?json='+StringUtils.URIEncode(
423
        '{"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"}}}');
424
      this.chartDatasourcesUrl =  this.properties.statisticsFrameNewAPIURL +
425
        'chart?json='+StringUtils.URIEncode(
426
        '{"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"}}}');
427
    } else {
428
      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%';
429
      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%';
430
      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%';
431
    }
432
433
    this.showLoading = false;
434
  }
435
436
  public downloadCsvFile(url: string, filename: string) {
437
    this.openLoading();
438
    this.setMessageLoading("Downloading CSV file");
439
440
    this.subscriptions.push(this._reportsService.downloadCSVFile(url).subscribe(
441
      data => {
442
        this.closeLoading();
443
444
        let url = window.URL.createObjectURL(data);
445
        this.download(url, filename+".csv");
446
447
        if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
448
          this.subscriptions.push(this._piwikService.trackDownload(this.properties, "DownloadCSV"+filename, this.piwikSiteId).subscribe());
449
        }
450
      },
451
      error => {
452
        //console.log("Error downloading the file.");
453
        this.handleError("Error downloading file: " + filename, error);
454
455
        this.closeLoading();
456
        this.confirmOpenFileDownloadError("CSV");
457
      }/*,
458
            () => console.log('Completed file download.')*/
459
    ));
460
  }
461
462
  public metricsResults($event) {
463
    this.totalViews = $event.totalViews;
464
    this.totalDownloads = $event.totalDownloads;
465
    this.pageViews = $event.pageViews;
466
  }
467
468
  public get hasMetrics(): boolean {
469
    return !(this.totalViews && this.totalDownloads && this.pageViews) || this.totalViews > 0 || this.totalDownloads > 0||this.pageViews > 0;
470
  }
471
472
  public openStatistics() {
473
    this.statsClicked = true;
474
    this.statisticsModal.cancelButton = false;
475
    this.statisticsModal.okButton = false;
476
    this.statisticsModal.alertTitle = "Statistics of";
477
    this.statisticsModal.open();
478
  }
479
480
  public openLinkProjectModal() {
481
    this.linkProjectModal.cancelButton = false;
482
    this.linkProjectModal.okButton = false;
483
    this.linkProjectModal.alertTitle = "Link this project to";
484
    //this.linkProjectModal.alertHeader = false;
485
    this.linkProjectModal.open();
486
  }
487
488
  public openShareResultsModal() {
489
    this.shareResultsModal.cancelButton = false;
490
    this.shareResultsModal.okButton = false;
491
    this.shareResultsModal.alertTitle = "Share results";
492
    this.shareResultsModal.open();
493
  }
494
495
  public openDownloadReportModal() {
496
    if(this.fetchPublications.searchUtils.totalResults > 0 || this.fetchDatasets.searchUtils.totalResults > 0 ||
497
       this.fetchSoftware.searchUtils.totalResults > 0 || this.fetchOrps.searchUtils.totalResults > 0) {
498
      this.download_research_results_type = "results";
499
    }
500
    this.downloadReportModal.cancelButton = false;
501
    this.downloadReportModal.okButton = false;
502
    this.downloadReportModal.alertTitle = "Download report";
503
    this.downloadReportModal.open();
504
  }
505
506
507
  public closeDownloadReportModal() {
508
    this.downloadReportModal.cancel();
509
  }
510
511
  private createHeaders(type: string) {
512
    this.openLoading();
513
    this.setMessageLoading("Downloading HTML file");
514
515
    if(!this.header1) {
516
      this.createHeader1();
517
    }
518
519
    if (type == "publications") {
520
      this.header2 = this.fetchPublications.searchUtils.totalResults.toLocaleString('en-US') + " publications";
521
    } else if (type == "datasets") {
522
      this.header2 = this.fetchDatasets.searchUtils.totalResults.toLocaleString('en-US') + " research data";
523
    } else if (type == "software") {
524
      this.header2 = this.fetchSoftware.searchUtils.totalResults.toLocaleString('en-US') + " software";
525
    } else if (type == "other") {
526
      this.header2 = this.fetchOrps.searchUtils.totalResults.toLocaleString('en-US') + " other research products";
527
    } else if (type == "results") {
528
      let totalResults: number = (+this.fetchPublications.searchUtils.totalResults) +
529
        (+this.fetchDatasets.searchUtils.totalResults) +
530
        (+this.fetchSoftware.searchUtils.totalResults) +
531
        (+this.fetchOrps.searchUtils.totalResults);
532
533
      this.header2 = totalResults.toLocaleString('en-US') + " research outcomes";
534
    }
535
  }
536
537
  private createHtmlFile(type: string, filename: string) {
538
    let intro: string = '<!doctype html>';
539
    intro += '<html lang="en-gb" dir="ltr" vocab="http://schema.org/">';
540
    intro += '<head>';
541
    intro += '<title>' + this.header1 + '</title>';
542
    intro += '</head>';
543
544
    if (typeof window !== 'undefined') {
545
      this.subscriptions.push(this.htmlService.getHTML(this.projectId, type, this.properties.csvAPIURL).subscribe(
546
        data => {
547
          //console.info(data);
548
          this.htmlResultDownload = intro + '<body><div>' + this.header1 + '</div><div><h4>' + this.header2 + '</h4></div>';
549
          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>";
550
          this.htmlResultDownload += '</body></html>';
551
552
          //console.info(this.htmlResultDownload);
553
          this.closeLoading();
554
555
          let url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' }));
556
          this.download(url, filename+".html");
557
558
          if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
559
            this.subscriptions.push(this._piwikService.trackDownload(this.properties, "DownloadHTML"+filename,  this.piwikSiteId).subscribe());
560
          }
561
        },
562
        err => {
563
          this.handleError("Error getting html for id: " + this.projectId, err);
564
          //this.errorMessage = 'Service not available';
565
          this.closeLoading();
566
          this.confirmOpenFileDownloadError("HTML");
567
        }
568
      ));
569
    } else {
570
      this.closeLoading();
571
      this.confirmOpenFileDownloadError("HTML");
572
    }
573
  }
574
575
  downloadHtmlFile(type: string, filename: string) {
576
    this.createHeaders(type);
577
    this.createHtmlFile(type, filename);
578
  }
579
580
  createHeader1() {
581
    // if (title != undefined && title != "") {
582
    //   this.header1 += title;
583
    // }
584
    // if ((title != undefined && title != "") &&
585
    //   ((acronym != undefined && acronym != "") ||
586
    //     (code != undefined && code != ""))) {
587
    //   this.header1 += "(";
588
    // }
589
    // if (acronym != undefined && acronym != "") {
590
    //   this.header1 += acronym + " - ";
591
    // }
592
    // if (code != undefined && code != "") {
593
    //   this.header1 += code;
594
    // }
595
    // if ((title != undefined && title != "") &&
596
    //   ((acronym != undefined && acronym != "") ||
597
    //     (code != undefined && code != ""))) {
598
    //   this.header1 += ")";
599
    // }
600
601
    this.header1 = "<div style=\"font-size:12px;\"><span>Project</span>";
602
603
    if(this.projectInfo.startDate || this.projectInfo.endDate) {
604
      this.header1 += "<span> . "
605
    }
606
    if(this.projectInfo.startDate && !this.projectInfo.endDate) {
607
      this.header1 += "from ";
608
    }
609
    if(!this.projectInfo.startDate && this.projectInfo.endDate) {
610
      this.header1 += "until ";
611
    }
612
    if(this.projectInfo.startDate) {
613
      let startYear = (new Date(this.projectInfo.startDate)).getFullYear();
614
      this.header1 += startYear;
615
    }
616
    if(this.projectInfo.startDate && this.projectInfo.endDate) {
617
      this.header1 += " - ";
618
    }
619
    if(this.projectInfo.endDate) {
620
      let endYear = (new Date(this.projectInfo.endDate)).getFullYear();
621
      this.header1 += endYear;
622
    }
623
    if(this.projectInfo.startDate || this.projectInfo.endDate) {
624
      this.header1 += "</span>"
625
    }
626
627
    if(this.projectInfo.status) {
628
      this.header1 += "<span> . "+this.projectInfo.status+"</span>";
629
    }
630
631
    if(this.projectInfo.funding && this.projectInfo.funding.code) {
632
      this.header1 += "<span> . "+this.projectInfo.funding.code+"</span>";
633
    }
634
    this.header1 += "</div>";
635
636
    this.header1 += "<h1 style=\"margin:0;\"><div><a href=\""+window.location.href +"\">";
637
    if(this.projectInfo.acronym) {
638
      this.header1 += this.projectInfo.acronym;
639
    } else {
640
      this.header1 += "[no title available]";
641
    }
642
    this.header1 += "</a></div></h2>";
643
    //<showTitle [titleName]="title" classNames="uk-margin-remove-bottom"></showTitle>
644
    if(this.projectInfo.title) {
645
      this.header1 += "<div><span>"+this.projectInfo.title+"</span></div>";
646
    }
647
  }
648
649
  public download(url, filename) {
650
    //var url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' }));
651
    var a = window.document.createElement('a');
652
    window.document.body.appendChild(a);
653
    a.setAttribute('style', 'display: none');
654
    a.href = url;
655
    a.download = filename;
656
    a.click();
657
    window.URL.revokeObjectURL(url);
658
    a.remove(); // remove the element
659
  }
660
661
662
  public onSelectActiveTab(activeTabId) {
663
    if(this.activeTab != activeTabId) {   // tab really changed
664
      if (activeTabId == 'summary') {
665
        this.activeTab = 'summary';
666
      } else if (activeTabId == 'publications') {
667
        this.activeTab = 'publications';
668
        this.searchPublications(1, this.searchNumber);
669
      } else if (activeTabId == 'datasets') {
670
        this.activeTab = 'datasets';
671
        this.searchDatasets(1, this.searchNumber);
672
      } else if (activeTabId == 'software') {
673
        this.activeTab = 'software';
674
        this.searchSoftware(1, this.searchNumber);
675
      } else if (activeTabId == 'other') {
676
        this.activeTab = "other";
677
        this.searchOrps(1, this.searchNumber);
678
      } else if (activeTabId == 'statistics') {
679
        this.activeTab = 'statistics';
680
        this.statsClicked = true;
681
      } else if (activeTabId == 'dmps') {
682
        this.activeTab = 'dmps';
683
        this.searchDmps(1, this.searchNumber);
684
      }
685
    }
686
  }
687
688
  private updateDescription(description: string) {
689
    this._meta.updateTag({content: description.substring(0, 160)}, "name='description'");
690
    this._meta.updateTag({content: description.substring(0, 160)}, "property='og:description'");
691
  }
692
693
  private updateTitle(title: string) {
694
    var _prefix = "";
695
    // if(!this.communityId) {
696
    //   _prefix = "OpenAIRE | ";
697
    // }
698
    // var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
699
    this._title.setTitle(title);
700
    this._meta.updateTag({content: title}, "property='og:title'");
701
  }
702
703
  private updateUrl(url: string) {
704
    this._meta.updateTag({content: url}, "property='og:url'");
705
  }
706
707
  private openLoading() {
708
    this.closeDownloadReportModal();
709
710
    if (this.loading) {
711
      this.loading.open();
712
    }
713
  }
714
715
  private closeLoading() {
716
    if (this.loading) {
717
      this.loading.close();
718
    }
719
  }
720
721
  private setMessageLoading(message: string) {
722
    if (this.loading) {
723
      this.loading.message = message;
724
    }
725
  }
726
727
  public confirmOpenFileDownloadError(fileType: string) {
728
    this.alertCsvError.cancelButton = false;
729
    this.alertCsvError.okButton = true;
730
    this.alertCsvError.alertTitle = "ERROR DOWNLOADING "+fileType+" FILE";
731
    this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
732
    this.alertCsvError.okButtonText = "OK";
733
    this.alertCsvError.open();
734
  }
735
736
  private handleError(message: string, error) {
737
    console.error("Project Landing Page: " + message, error);
738
  }
739
740
  isRouteAvailable(routeToCheck: string) {
741
    for (let i = 0; i < this._router.config.length; i++) {
742
      let routePath: string = this._router.config[i].path;
743
      if (routePath == routeToCheck) {
744
        return true;
745
      }
746
    }
747
    return false;
748
  }
749
750
  private getEntityName (entityType:string, plural:boolean, full:boolean): string {
751
    if(entityType == "publication") {
752
      return "publication" + (plural ? "s" : "");
753
    } else if(entityType == "dataset") {
754
      return (full ? "research data" : ("dataset" + (plural ? "s" : "")));
755
    } else if(entityType == "software") {
756
      return "software";
757
    } else if(entityType == "other") {
758
      return (full ? ("other research product" + (plural ? "s" : "")) : "other");
759
    } else if(entityType == "dataprovider") {
760
      return (full ? ("content provider" + (plural ? "s" : "")) : "dataprovider" + (plural ? "s" : ""));
761
    } else {
762
      return entityType + (plural ? "s" : "");
763
    }
764
  }
765
766
  public getResultPreview(result: SearchResult, type: string): ResultPreview {
767
    return ResultPreview.searchResultConvert(result, type);
768
  }
769
770
  public scroll() {
771
    HelperFunctions.scroll();
772
  }
773
774
  public getParamsForSearchLink(type: string = null, subtype: string = null) {
775
    if(type) {
776
      if(subtype) {
777
        return this.routerHelper.createQueryParams(['f0', 'fv0', 'type', 'instancetypename', 'qf', 'sortBy'], ['relprojectid', this.projectId, type, subtype, 'false', 'resultdateofacceptance,descending']);
778
      } else {
779
        return this.routerHelper.createQueryParams(['f0', 'fv0', 'type', 'qf', 'sortBy'], ['relprojectid', this.projectId, type, 'false', 'resultdateofacceptance,descending']);
780
      }
781
    } else {
782
      return this.routerHelper.createQueryParams(['f0', 'fv0'], ['relprojectid', this.projectId]);
783
    }
784
  }
785
786
  public get hasPrimaryInfo(): boolean {
787
    return !!this.projectInfo && (
788
      !!this.projectInfo.description
789
    );
790
  }
791
792
  public get hasSecondaryInfo(): boolean {
793
    return !!this.projectInfo && (
794
      (!!this.projectInfo.organizations && this.projectInfo.organizations.length > 0)
795
    );
796
  }
797
798
  // public get numberOfTabs(): number {
799
  //   if(this.tabsAreInitialized) {
800
  //     return this._numberOfTabs;
801
  //   }
802
  //
803
  //   if(!this.projectInfo
804
  //     || this.fetchPublications.searchUtils.status == this.errorCodes.LOADING
805
  //     || this.fetchDatasets.searchUtils.status == this.errorCodes.LOADING
806
  //     || this.fetchSoftware.searchUtils.status == this.errorCodes.LOADING
807
  //     || this.fetchOrps.searchUtils.status == this.errorCodes.LOADING) {
808
  //     return 0;
809
  //   }
810
  //
811
  //   if (this.hasPrimaryInfo || this.hasSecondaryInfo) {
812
  //     this.firstTab = "summary";
813
  //     this._numberOfTabs++;
814
  //   }
815
  //   if(this.fetchPublications.searchUtils.totalResults > 0 || this.fetchDatasets.searchUtils.totalResults > 0
816
  //     || this.fetchSoftware.searchUtils.totalResults > 0 || this.fetchOrps.searchUtils.totalResults > 0) {
817
  //     if(this.fetchPublications.searchUtils.totalResults > 0) {
818
  //       if(this._numberOfTabs == 0) {
819
  //         this.firstTab = 'publications';
820
  //         this.searchPublicationsInit();
821
  //       }
822
  //       this._numberOfTabs++;
823
  //     }
824
  //     if(this.fetchDatasets.searchUtils.totalResults > 0) {
825
  //       if(this._numberOfTabs == 0) {
826
  //         this.firstTab = 'datasets';
827
  //         this.searchDatasetsInit();
828
  //       }
829
  //       this._numberOfTabs++;
830
  //     }
831
  //     if(this.fetchSoftware.searchUtils.totalResults > 0) {
832
  //       if(this._numberOfTabs == 0) {
833
  //         this.firstTab = 'software';
834
  //         this.searchSoftwareInit();
835
  //       }
836
  //       this._numberOfTabs++;
837
  //     }
838
  //     if(this.fetchOrps.searchUtils.totalResults > 0) {
839
  //       if(this._numberOfTabs == 0) {
840
  //         this.firstTab = 'other';
841
  //         this.searchOrpsInit();
842
  //       }
843
  //       this._numberOfTabs++;
844
  //     }
845
  //     this._numberOfTabs++;
846
  //   }
847
  //   this.activeTab = this.firstTab;
848
  //   this.tabsAreInitialized = true;
849
  //   return this._numberOfTabs;
850
  // }
851
}