import {Component, Input, ViewChild} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {Meta, Title} from '@angular/platform-browser'; import {ProjectService} from './project.service'; import {ProjectInfo} from '../../utils/entities/projectInfo'; import {RouterHelper} from '../../utils/routerHelper.class'; import {FetchResearchResults} from '../../utils/fetchEntitiesClasses/fetchResearchResults.class'; import {SearchResearchResultsService} from '../../services/searchResearchResults.service'; import {ModalLoading} from '../../utils/modal/loading.component'; import {ReportsService} from '../../services/reports.service'; import {ErrorCodes} from '../../utils/properties/errorCodes' import {PiwikService} from '../../utils/piwik/piwik.service'; import {EnvProperties} from '../../utils/properties/env-properties'; import {SEOService} from '../../sharedComponents/SEO/SEO.service'; import {HelperFunctions} from "../../utils/HelperFunctions.class"; import {HelperService} from "../../utils/helper/helper.service"; import {Location} from "@angular/common"; import {HtmlProjectReportService} from "../htmlProjectReport/htmlProjectReport.service"; @Component({ selector: 'project', templateUrl: 'project.component.html', }) export class ProjectComponent { @Input() piwikSiteId = null; @Input() communityId = null; public projectInfo: ProjectInfo; public projectId: string; public projectName: string; // Metrics tab variables public metricsClicked: boolean; public viewsFrameUrl: string; public downloadsFrameUrl: string; private totalViews: number; private totalDownloads: number; private pageViews: number; // Statistics tab variables public statsClicked: boolean; public chartScientificResultsUrl: string; public chartAccessModeUrl: string; public chartDatasourcesUrl: string; // Clipboard variable for HTML dynamic content public clipboard; public project; // CSV variables public downloadURLAPI: string; public csvParams: string; // HTML (download) variables public header1: string = ""; public header2: string = ""; public htmlResultDownload: string = ""; // Message variables public warningMessage = ""; public errorMessage = ""; public showLoading: boolean = true; // Active tab variable for responsiveness public activeTab: string = "Publications"; @ViewChild('statisticsModal') statisticsModal; // Request results for publications, research data and software only the one time (first time tab is clicked) private reloadPublications: boolean = true; private reloadDatasets: boolean = true; private reloadSoftware: boolean = true; private reloadOrps: boolean = true; // Variables for entity selections on the right column public share_research_results_type: string = ""; public download_research_results_type: string = ""; // Variables for publications, research data, software tabs public fetchPublications: FetchResearchResults; public linkToSearchPublications = ""; public fetchDatasets: FetchResearchResults; public linkToSearchDatasets = ""; public fetchSoftware: FetchResearchResults; public linkToSearchSoftware = ""; public fetchOrps: FetchResearchResults; public linkToSearchOrps = ""; public routerHelper: RouterHelper = new RouterHelper(); public errorCodes: ErrorCodes = new ErrorCodes(); public pageContents = null; public divContents = null; public indexUpdateDate: Date; public showFeedback: boolean; public feedbackFields: string [] = [ 'Title', 'Funding Information', 'Duration', 'Organizations', 'Other']; @ViewChild(ModalLoading) loading: ModalLoading; // Alert box when something is wrong with CSV requests @ViewChild('AlertModalCsvError') alertCsvError; // Description variables for view more/less functionality public thresholdDescription: number = 670; public showNumDescription: number = 670; // Organizations variables for view more/less functionality public thresholdOrganizations: number = 20; public showNumOrganizations: number = 20; sub: any; piwiksub: any; infoSub: any; downloadFilePiwikSub: any; downloadHtmlFilePiwikSub: any; properties: EnvProperties; public subHTML: any; constructor(private route: ActivatedRoute, private _router: Router, private _location: Location, private _meta: Meta, private _title: Title, private seoService: SEOService, private _piwikService: PiwikService, private helper: HelperService, private _projectService: ProjectService, private _searchResearchResultsService: SearchResearchResultsService, private _reportsService: ReportsService, private htmlService: HtmlProjectReportService) {} ngOnInit() { this.route.data .subscribe((data: { envSpecific: EnvProperties }) => { this.properties = data.envSpecific; if(this.properties.lastIndexUpdate) { this.indexUpdateDate = new Date(this.properties.lastIndexUpdate); } //this.getDivContents(); this.getPageContents(); this.updateUrl(data.envSpecific.baseLink + this._router.url); }); this.sub = this.route.queryParams.subscribe(params => { this.metricsClicked = false; this.statsClicked = false; this.fetchPublications = new FetchResearchResults(this._searchResearchResultsService); this.fetchDatasets = new FetchResearchResults(this._searchResearchResultsService); this.fetchSoftware = new FetchResearchResults(this._searchResearchResultsService); this.fetchOrps = new FetchResearchResults(this._searchResearchResultsService); var title = "Project"; var description = ""; this.header1 = ""; this.updateTitle(title); this.updateDescription(description); this.projectId = params['projectId']; var grantId = params['grantId']; var funder = params['funder']; if (this.projectId) { this.getProjectInfo(this.projectId); this.actionsAfterLoadId(); } else if (grantId && funder) { this.getProjectInfoByGrantId(grantId, funder); } else { this.showLoading = false; this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}}); //this.warningMessage = "No valid project id"; } this.downloadURLAPI = this.properties.csvAPIURL; this.createClipboard(); HelperFunctions.scroll(); }); } public getFileNameType(type: string) { if(type == "results") { return "research-outcomes"; } else if(type == "publications") { return "publications"; } else if(type == "datasets") { return "research-data"; } else if(type == "software") { return "software"; } else if(type == "other") { return "other-research-products"; } return "results"; } public getCsvParams(type: string) { // if(type == "results") { // type = "publications&type=datasets&type=software&type=other"; // } return "?format=csv-special&type="+type+"&fq=(relprojectid exact \"" + this.projectId + "\")"; } private getPageContents() { this.helper.getPageHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => { this.pageContents = contents; }) } private getDivContents() { this.helper.getDivHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => { this.divContents = contents; }) } getDynamicContent(type: string) { return ""; } actionsAfterLoadId() { this.getProjectInfo(this.projectId); //this.searchPublications(); this.fetchPublications.getNumForEntity("publication", "project", this.projectId, this.properties); this.fetchDatasets.getNumForEntity("dataset", "project", this.projectId, this.properties); this.fetchSoftware.getNumForEntity("software", "project", this.projectId, this.properties); this.fetchOrps.getNumForEntity("other", "project", this.projectId, this.properties); } ngOnDestroy() { if (this.sub) { this.sub.unsubscribe(); } if (this.piwiksub) { this.piwiksub.unsubscribe(); } if (this.infoSub) { this.infoSub.unsubscribe(); } if (this.downloadFilePiwikSub) { this.downloadFilePiwikSub.unsubscribe(); } if(this.downloadHtmlFilePiwikSub) { this.downloadHtmlFilePiwikSub.unsubscribe(); } } private createClipboard() { if (typeof window !== 'undefined') { delete this.clipboard; let Clipboard; Clipboard = require('clipboard'); this.clipboard = new Clipboard('.clipboard_btn'); } } private searchPublications() { this.fetchPublications.getResultsForEntity("publication", "project", this.projectId, 1, 10, this.properties); this.linkToSearchPublications = this.properties.searchLinkToAdvancedPublications;// + "?project=" + this.projectId+"&pr=and"; this.reloadPublications = false; } private searchDatasets() { this.fetchDatasets.getResultsForEntity("dataset", "project", this.projectId, 1, 10, this.properties); this.linkToSearchDatasets = this.properties.searchLinkToAdvancedDatasets;// + "?project=" + this.projectId+"&pr=and"; this.reloadDatasets = false; //this.activeTab = "Research Data"; } private searchSoftware() { this.fetchSoftware.getResultsForEntity("software", "project", this.projectId, 1, 10, this.properties); this.linkToSearchSoftware = this.properties.searchLinkToAdvancedSoftware; this.reloadSoftware = false; } private searchOrps() { this.fetchOrps.getResultsForEntity("other", "project", this.projectId, 1, 10, this.properties); this.linkToSearchOrps = this.properties.searchLinkToAdvancedOrps; this.reloadOrps = false; } public searchPublicationsInit() { if (this.reloadPublications && this.fetchPublications.searchUtils.totalResults > 0) { this.searchPublications(); } else if (this.fetchPublications.searchUtils.totalResults == 0) { //this.statsClicked=true; //this.activeTab = "Statistics"; } } public searchDatasetsInit() { if (this.reloadDatasets && this.fetchDatasets.searchUtils.totalResults > 0) { this.searchDatasets(); } else if (this.fetchDatasets.searchUtils.totalResults == 0) { //this.statsClicked=true; //this.activeTab = "Statistics"; } } public searchSoftwareInit() { if (this.reloadSoftware && this.fetchSoftware.searchUtils.totalResults > 0) { this.searchSoftware(); } } public searchOrpsInit() { if (this.reloadOrps && this.fetchOrps.searchUtils.totalResults > 0) { this.searchOrps(); } } private getProjectInfo(id: string) { this.warningMessage = ''; this.errorMessage = ""; this.showLoading = true; this.projectInfo = null; this.infoSub = this._projectService.getProjectInfo(id, this.properties).subscribe( data => { this.projectInfo = data; this.actionsAfterGettingProjectInfo(); }, err => { //console.log(err); this.handleError("Error getting project for id: " + this.projectId, err); if(err.status == 404) { this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}}); } this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.properties.searchLinkToProjects); this.errorMessage = 'No project found'; this.showLoading = false; } ); } private getProjectInfoByGrantId(grantId: string, funder: string) { this.warningMessage = ''; this.errorMessage = ""; this.showLoading = true; this.projectInfo = null; this._projectService.getProjectInfoByGrantId(grantId, funder, this.properties).subscribe( data => { this.projectInfo = data; this.actionsAfterGettingProjectInfo(); this.projectId = this.projectInfo.id; this.actionsAfterLoadId(); }, err => { //console.log(err); this.handleError("Error getting project for grant id: " + grantId + " and funder: " + funder, err); if(err.status == 404) { this._router.navigate(['/error'], {queryParams: {"page": this._location.path(true), "page_type": "project"}}); } this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.properties.searchLinkToProjects); this.errorMessage = 'No project found'; this.showLoading = false; } ); } actionsAfterGettingProjectInfo() { this.projectName = this.projectInfo.acronym; if (this.projectName == undefined || this.projectName == '') { this.projectName = this.projectInfo.title; } this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this._router.url); this.updateTitle(this.projectName); this.updateDescription("project, " + this.projectName + "," + this.projectInfo.funding.funderShortName + "," + this.projectInfo.acronym); if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) { this.piwiksub = this._piwikService.trackView(this.properties, this.projectName, this.piwikSiteId).subscribe(); } this.project = { funderId: "", funderName: ((this.projectInfo.funding) ? this.projectInfo.funding.funderShortName: ''), projectId: this.projectId, projectName: this.projectInfo.title, projectAcronym: this.projectInfo.acronym, startDate: this.projectInfo.startDate, endDate: this.projectInfo.endDate }; 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":80,"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'; 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":80,"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'; //stats tab charts 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%'; 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%'; 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%'; this.showLoading = false; } public downloadCsvFile(url: string, filename: string) { this.openLoading(); this.setMessageLoading("Downloading CSV file"); this._reportsService.downloadCSVFile(url).subscribe( data => { this.closeLoading(); let url = window.URL.createObjectURL(data); this.download(url, filename+".csv"); if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) { this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url).subscribe(); } }, error => { //console.log("Error downloading the file."); this.handleError("Error downloading file: " + filename, error); this.closeLoading(); this.confirmOpenFileDownloadError("CSV"); }/*, () => console.log('Completed file download.')*/ ); } public metricsResults($event) { this.totalViews = $event.totalViews; this.totalDownloads = $event.totalDownloads; this.pageViews = $event.pageViews; } public openStatistics() { this.statsClicked = true; this.statisticsModal.cancelButton = false; this.statisticsModal.okButton = false; this.statisticsModal.alertTitle = "Statistics of"; this.statisticsModal.open(); } private createHeaders(type: string) { this.openLoading(); this.setMessageLoading("Downloading HTML file"); if(!this.header1) { this.createHeader1(); } if (type == "publications") { this.header2 = this.fetchPublications.searchUtils.totalResults.toLocaleString('en-US') + " publications"; } else if (type == "datasets") { this.header2 = this.fetchDatasets.searchUtils.totalResults.toLocaleString('en-US') + " research data"; } else if (type == "software") { this.header2 = this.fetchSoftware.searchUtils.totalResults.toLocaleString('en-US') + " software"; } else if (type == "other") { this.header2 = this.fetchOrps.searchUtils.totalResults.toLocaleString('en-US') + " other research products"; } else if (type == "results") { let totalResults: number = (+this.fetchPublications.searchUtils.totalResults) + (+this.fetchDatasets.searchUtils.totalResults) + (+this.fetchSoftware.searchUtils.totalResults) + (+this.fetchOrps.searchUtils.totalResults); this.header2 = totalResults.toLocaleString('en-US') + " research outcomes"; } } private createHtmlFile(type: string, filename: string) { let intro: string = ''; intro += ''; intro += ''; intro += '' + this.header1 + ''; intro += ''; if (typeof window !== 'undefined') { this.subHTML = this.htmlService.getHTML(this.projectId, type, this.properties.csvAPIURL).subscribe( data => { //console.info(data); this.htmlResultDownload = intro + '
' + this.header1 + '

' + this.header2 + '

'; this.htmlResultDownload += "" + data + "
TypeTitleAuthorsPublication YearDOIPermanent IdentifierPublication typeJournalProject Name (GA Number)Access Mode
"; this.htmlResultDownload += ''; //console.info(this.htmlResultDownload); this.closeLoading(); let url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' })); this.download(url, filename+".html"); if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) { this.downloadHtmlFilePiwikSub = this._piwikService.trackDownload(this.properties, url).subscribe(); } }, err => { this.handleError("Error getting html for id: " + this.projectId, err); //this.errorMessage = 'Service not available'; this.closeLoading(); this.confirmOpenFileDownloadError("HTML"); } ); } else { this.closeLoading(); this.confirmOpenFileDownloadError("HTML"); } } downloadHtmlFile(type: string, filename: string) { this.createHeaders(type); this.createHtmlFile(type, filename); } createHeader1() { // if (title != undefined && title != "") { // this.header1 += title; // } // if ((title != undefined && title != "") && // ((acronym != undefined && acronym != "") || // (code != undefined && code != ""))) { // this.header1 += "("; // } // if (acronym != undefined && acronym != "") { // this.header1 += acronym + " - "; // } // if (code != undefined && code != "") { // this.header1 += code; // } // if ((title != undefined && title != "") && // ((acronym != undefined && acronym != "") || // (code != undefined && code != ""))) { // this.header1 += ")"; // } this.header1 = "
Project"; if(this.projectInfo.startDate || this.projectInfo.endDate) { this.header1 += " . " } if(this.projectInfo.startDate && !this.projectInfo.endDate) { this.header1 += "from "; } if(!this.projectInfo.startDate && this.projectInfo.endDate) { this.header1 += "until "; } if(this.projectInfo.startDate) { let startYear = (new Date(this.projectInfo.startDate)).getFullYear(); this.header1 += startYear; } if(this.projectInfo.startDate && this.projectInfo.endDate) { this.header1 += " - "; } if(this.projectInfo.endDate) { let endYear = (new Date(this.projectInfo.endDate)).getFullYear(); this.header1 += endYear; } if(this.projectInfo.startDate || this.projectInfo.endDate) { this.header1 += "" } if(this.projectInfo.status) { this.header1 += " . "+this.projectInfo.status+""; } if(this.projectInfo.funding && this.projectInfo.funding.code) { this.header1 += " . "+this.projectInfo.funding.code+""; } this.header1 += "
"; this.header1 += "

"; if(this.projectInfo.acronym) { this.header1 += this.projectInfo.acronym; } else { this.header1 += "[no title available]"; } this.header1 += "

"; // if(this.projectInfo.title) { this.header1 += "
"+this.projectInfo.title+"
"; } } public download(url, filename) { //var url = window.URL.createObjectURL(new Blob([this.htmlResultDownload], { type: 'text/html' })); var a = window.document.createElement('a'); window.document.body.appendChild(a); a.setAttribute('style', 'display: none'); a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); a.remove(); // remove the element } // copyToClipboard(element: HTMLElement) { // if (typeof document !== 'undefined') { // if (window.getSelection) { // const selection = window.getSelection(); // const range = document.createRange(); // range.selectNodeContents(element); // selection.removeAllRanges(); // selection.addRange(range); // document.execCommand('copy'); // } else { // console.warn("Could not select text in node: Unsupported browser."); // } // } // } private updateDescription(description: string) { this._meta.updateTag({content: description.substring(0, 160)}, "name='description'"); this._meta.updateTag({content: description.substring(0, 160)}, "property='og:description'"); } private updateTitle(title: string) { var _prefix = ""; // if(!this.communityId) { // _prefix = "OpenAIRE | "; // } // var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title); this._title.setTitle(title); this._meta.updateTag({content: title}, "property='og:title'"); } private updateUrl(url: string) { this._meta.updateTag({content: url}, "property='og:url'"); } private openLoading() { if (this.loading) { this.loading.open(); } } private closeLoading() { if (this.loading) { this.loading.close(); } } private setMessageLoading(message: string) { if (this.loading) { this.loading.message = message; } } public confirmOpenFileDownloadError(fileType: string) { this.alertCsvError.cancelButton = false; this.alertCsvError.okButton = true; this.alertCsvError.alertTitle = "ERROR DOWNLOADING "+fileType+" FILE"; this.alertCsvError.message = "There was an error in csv downloading. Please try again later."; this.alertCsvError.okButtonText = "OK"; this.alertCsvError.open(); } private handleError(message: string, error) { console.error("Project Landing Page: " + message, error); } isRouteAvailable(routeToCheck: string) { for (let i = 0; i < this._router.config.length; i++) { let routePath: string = this._router.config[i].path; if (routePath == routeToCheck) { return true; } } return false; } }