openaire-library/landingPages/organization/organization.component.ts

571 lines
26 KiB
TypeScript

import {Component, ViewChild} from '@angular/core';
import {ElementRef, Input} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Title, Meta} from '@angular/platform-browser';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {OrganizationService} from '../../services/organization.service';
import {OrganizationInfo} from '../../utils/entities/organizationInfo';
import {ReportsService} from '../../services/reports.service';
import {FetchPublications} from '../../utils/fetchEntitiesClasses/fetchPublications.class';
// import {FetchDatasets} from '../../utils/fetchEntitiesClasses/fetchDatasets.class';
import {FetchProjects} from '../../utils/fetchEntitiesClasses/fetchProjects.class';
import {FetchDataproviders} from '../../utils/fetchEntitiesClasses/fetchDataproviders.class';
import {SearchPublicationsService} from '../../services/searchPublications.service';
// import {SearchDatasetsService} from '../../services/searchDatasets.service';
import {SearchDataprovidersService} from '../../services/searchDataproviders.service';
import {SearchProjectsService} from '../../services/searchProjects.service';
import {ErrorCodes} from '../../utils/properties/errorCodes';
import {SearchingProjectsTabComponent} from '../landing-utils/searchingProjectsInTab.component';
import {RouterHelper} from '../../utils/routerHelper.class';
import {ModalLoading} from '../../utils/modal/loading.component';
import {AlertModal} from '../../utils/modal/alert';
import {PiwikService} from '../../utils/piwik/piwik.service';
import {StringUtils} from '../../utils/string-utils.class';
import {EnvProperties} from '../../utils/properties/env-properties';
import { SEOService } from '../../sharedComponents/SEO/SEO.service';
@Component({
selector: 'organization',
templateUrl: 'organization.component.html',
})
export class OrganizationComponent {
@Input() piwikSiteId = null;
public organizationInfo: OrganizationInfo;
public organizationId: string;
// Message variables
public warningMessage = "";
public errorMessage = "";
public showLoading: boolean = true;
// CSV variables
public downloadURLAPI: string;
public csvProjectParamsHead: string;
public csvPublicationParamsHead: string;
public csvParamsTail: string;
// Active tab variable for responsiveness
public activeTab: string = "Publications";
// Variables for publications, research data, projects, dataproviders tabs
public fetchPublications: FetchPublications;
public linkToSearchPublications: string = "";
// public fetchDatasets: FetchDatasets;
// public linkToSearchDatasets: string = "";
public fetchProjects: FetchProjects;
public fetchDataproviders : FetchDataproviders;
public linkToSearchDataproviders:string = "";
//public projectFunders:string[] = [];
// Variables for projects query (query results only if projects tab is clicked)
public projectsClicked: boolean = false;
@ViewChild (SearchingProjectsTabComponent) searchingProjectsTabComponent : SearchingProjectsTabComponent ;
@ViewChild (ModalLoading) loading : ModalLoading ;
// Alert box when CSV: Project Publications for a funder is requested
@ViewChild('AlertModalApplyAll') alertApplyAll;
// Alert box when something is wrong with CSV requests
@ViewChild('AlertModalCsvError') alertCsvError;
public routerHelper:RouterHelper = new RouterHelper();
public errorCodes:ErrorCodes = new ErrorCodes();
//private projectsNum: number = 0;
//private fundersSet: Set<string>;
//private emptyFundersSet: boolean = true;
// Request results for publications, research data and content providers only the one time (first time tab is clicked)
private reloadPublications: boolean = true;
// private reloadDatasets: boolean = true;
private reloadDataproviders: boolean = true;
// Helper variables to specify funder in downloadPublicationsFile function
private funder: string;
private funderId: string;
private funderCountPublications: number;
sub: any;
infoSub: any;
piwiksub: any;
downloadFileSub: any;
downloadFilePiwikSub: any;
countProjectsSub: any;
countPublSub: any;
downloadProjectPublSub: any;
properties:EnvProperties;
//private ngUnsubscribe: Subject<void> = new Subject<void>();
constructor (private element: ElementRef,
private _organizationService: OrganizationService,
private _piwikService:PiwikService,
private route: ActivatedRoute,
private _searchDataprovidersService: SearchDataprovidersService,
private _reportsService: ReportsService,
private _searchPublicationsService: SearchPublicationsService,
// private _searchDatasetsService: SearchDatasetsService,
private _searchProjectsService: SearchProjectsService,
private _meta: Meta,
private _title: Title,
private _router: Router,
private seoService: SEOService) {
this.fetchPublications = new FetchPublications(this._searchPublicationsService);
// this.fetchDatasets = new FetchDatasets(this._searchDatasetsService);
this.fetchProjects = new FetchProjects(this._searchProjectsService);
this.fetchDataproviders = new FetchDataproviders(this._searchDataprovidersService);
}
ngOnInit() {
this.route.data
.subscribe((data: { envSpecific: EnvProperties }) => {
this.properties = data.envSpecific;
this.updateUrl(data.envSpecific.baseLink+this._router.url);
this.seoService.createLinkForCanonicalURL(this.properties.baseLink+this._router.url);
});
this.sub = this.route.queryParams.subscribe(params => {
this.organizationInfo=null;
this.updateTitle("Organization");
this.updateDescription("");
this.projectsClicked = false;
this.organizationId = params['organizationId'];
if(this.organizationId){
this.getOrganizationInfo();
}else{
this.showLoading = false;
this.warningMessage="No valid organization id";
}
if (typeof document !== 'undefined') {
this.element.nativeElement.scrollIntoView();
}
this.csvParamsTail = '" and relorganizationid exact "'+this.organizationId+'" ))';
});
this.downloadURLAPI =this.properties.csvAPIURL;
this.csvProjectParamsHead = 'format=csv&type=projects&fq=( (oaftype exact project)and (funder exact "';
//this.csvPublicationParamsHead = 'format=csv-special&type=publications&page=0&query=((((oaftype exact result) and (resulttypeid exact publication)) and (funderid exact ';
}
ngOnDestroy() {
if(this.sub){
this.sub.unsubscribe();
}
if(this.piwiksub){
this.piwiksub.unsubscribe();
}
if(this.infoSub) {
this.infoSub.unsubscribe();
}
if(this.downloadFileSub) {
this.downloadFileSub.unsubscribe();
}
if(this.downloadFilePiwikSub) {
this.downloadFilePiwikSub.unsubscribe();
}
if(this.countProjectsSub) {
this.countProjectsSub.unsubscribe();
}
if(this.countPublSub) {
this.countPublSub.unsubscribe();
}
if(this.downloadProjectPublSub) {
this.downloadProjectPublSub.unsubscribe();
}
/*
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
*/
}
private getOrganizationInfo () {
this.warningMessage = '';
this.errorMessage=""
this.showLoading = true;
this.organizationInfo = null;
this.infoSub = this._organizationService.getOrganizationInfo(this.organizationId, this.properties).subscribe(
data => {
if(data == null) {
this.showLoading = false;
this.errorMessage = 'No organization found';
} else {
this.organizationInfo = data;
this.updateTitle(this.organizationInfo.title.name);
this.updateDescription("Organization, country, "+this.organizationInfo.title.name +((this.organizationInfo.title.name && this.organizationInfo.title.name != this.organizationInfo.name)?(", "+this.organizationInfo.name):"") );
if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
this.piwiksub = this._piwikService.trackView(this.properties, this.organizationInfo.title.name, this.piwikSiteId).subscribe();
}
var refineFields:string [] = ["funder"];
//this.searchPublications();
this.fetchPublications.getNumForEntity("organization", this.organizationId, this.properties);
// this.fetchDatasets.getNumForEntity("organization", this.organizationId, this.properties);
this.fetchProjects.getResultsForOrganizations(this.organizationId, "", 1, 0,refineFields,this.properties);
this.fetchDataproviders.getNumForEntity("organization", this.organizationId,this.properties);
this.showLoading = false;
/*let projectsNum = 0;
if(this.organizationInfo.projects != undefined) {
this.fundersSet = new Set<string>();
this.organizationInfo.projects.forEach(function (value, key, map) {
projectsNum += value.length;
this.fundersSet.add(key);
}.bind(this));
}
this.projectsNum = projectsNum;*/
}
},
err => {
//console.log(err)
this.handleError("Error getting organization for id: "+this.organizationId, err);
this.errorMessage = 'No organization found';
this.showLoading = false;
}
);
}
/*
private handleClick(funder: string) {
if(this.emptyFundersSet) {
this.fundersSet.clear();
this.emptyFundersSet = false;
}
if(this.fundersSet.has(funder)) {
this.fundersSet.delete(funder);
if(this.fundersSet.size == 0) {
this.organizationInfo.projects.forEach(function (value, key, map) {
this.fundersSet.add(key);
}.bind(this));
this.emptyFundersSet = true;
}
console.info(funder+" funder deleted");
} else {
this.fundersSet.add(funder);
console.info(funder+" funder added");
}
}
*/
//private getProjectsData(key: string): any {
//return this.projectsData;
//}
private searchPublications() {
this.fetchPublications.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
this.linkToSearchPublications = this.properties.searchLinkToAdvancedPublications;
//if(this.fetchPublications.searchUtils.totalResults > 0) {
this.reloadPublications = false;
//this.activeTab = "Publications";
//} else {
//this.projectsClicked = true;
//}
}
// private searchDatasets() {
// this.fetchDatasets.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
// this.linkToSearchPublications = this.properties.searchLinkToAdvancedDatasets;
// this.reloadDatasets = false;
// }
private searchDataproviders() {
this.fetchDataproviders.getResultsForEntity("organization", this.organizationId, 1, 10,this.properties);
this.linkToSearchDataproviders = this.properties.searchLinkToAdvancedDataProviders;
//if(this.fetchDataproviders.searchUtils.totalResults > 0) {
this.reloadDataproviders = false;
//this.activeTab = "Content Providers";
//} else {
//}
}
public searchPublicationsInit() {
if(this.reloadPublications && this.fetchPublications.searchUtils.totalResults > 0) {
this.searchPublications();
}
}
// public searchDatasetsInit() {
// if(this.reloadDatasets && this.fetchDatasets.searchUtils.totalResults > 0) {
// this.searchDatasets();
// }
// }
public searchDataprovidersInit() {
if(this.reloadDataproviders && this.fetchDataproviders.searchUtils.totalResults > 0) {
this.searchDataproviders();
}
}
public downloadFile(url:string, filename: string){
this.openLoading();
this.setMessageLoading("Downloading CSV file");
this.downloadFileSub = this._reportsService.downloadCSVFile(url).subscribe(
data => {
this.closeLoading();
var url = window.URL.createObjectURL(data);
var a = window.document.createElement('a');
window.document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = filename+".csv";
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
//window.open(window.URL.createObjectURL(data));
if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url, this.piwikSiteId).subscribe();
}
},
err => {
//console.log("Error downloading the file.");
this.handleError("Error downloading file: "+filename+".csv", err);
this.closeLoading();
this.confirmOpenCsvError();
}/*,
() => console.log('Completed file download.')*/
);
}
private downloadPublicationsFile(funder: string, funderId:string, count:number){
this.openLoading();
this.setMessageLoading("Downloading CSV file");
let response: string[] = [];
let totalResponse: string = "";
let projects = [];
let counter: number = count;
let title: boolean = false;
let filename: string = 'funder-project-publications-report';
this.countProjectsSub = this._searchProjectsService.getProjectsForOrganizations(this.organizationId,' and (funder exact "'+ funderId + '" ) ',1,count,[], this.properties).subscribe(
data =>
{
projects = data[1];
for(let index=0; index < projects.length; index++) {
this.countPublSub = this._searchPublicationsService.numOfEntityPublications(projects[index].id, "project", this.properties).subscribe(
data =>
{
// let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
let url: string;
if(!title) {
//url = this.downloadURLAPI+"projects/"+projects[index].id+"?type=publications&format=csv-special";//&size="+data;
url = this.downloadURLAPI+"?format=csv-special&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact '"+projects[index].id+"'))"
} else {
//url = this.downloadURLAPI+"projects/"+projects[index].id+"/publications?format=csv-special-notitle";//&size="+data;
url = this.downloadURLAPI+"?format=csv-special-notitle&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact '"+projects[index].id+"'))"
}
if(data == 0 && (counter > 1 || title)) { // if no publications for this project
counter--;
response[index] = "";
if(counter == 0) {
for(let i=0; i<count; i++) {
if(response[i] != "") {
totalResponse += response[i];
}
}
this.closeLoading();
var csvurl = window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' }));
var a = window.document.createElement('a');
window.document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = csvurl;
a.download = filename+".csv";
a.click();
window.URL.revokeObjectURL(csvurl);
a.remove(); // remove the element
//window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
// if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
// this._piwikService.trackDownload(this.properties, url).subscribe();
// }
}
} else {
title = true;
this.downloadProjectPublSub = this._reportsService.getCSVResponse(url).subscribe(
data =>
{
counter--;
response[index] = data;
if(counter == 0) {
for(let i=0; i<count; i++) {
if(response[i] != "") {
totalResponse += response[i];
}
}
this.closeLoading();
var csvurl = window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' }));
var a = window.document.createElement('a');
window.document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = csvurl;
a.download = filename+".csv";
a.click();
window.URL.revokeObjectURL(csvurl);
a.remove(); // remove the element
//window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
// if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
// this._piwikService.trackDownload(this.properties, url).subscribe();
// }
}
},
err => {
//console.log("Error downloading the file.");
this.handleError("Error downloading file: "+filename, err);
this.closeLoading();
this.confirmOpenCsvError();
}/*,
() => console.log('Completed file download.')*/
);
}
},
err => {
//console.log("Error getting number of publications for project.")
this.handleError("Error getting number of publications for project with id: "+projects[index].id, err);
});
}//);
},
err => {
//console.log("Error getting projects project.");
this.handleError("Error getting projects for organization with id: "+this.organizationId, err);
this.closeLoading();
this.confirmOpenCsvError();
}
);
// let counter: number = this.organizationInfo.projects.get(funder).length;
//
// for(let project of this.organizationInfo.projects.get(funder)) {
// this._searchPublicationsService.numOfEntityPublications(project.id, "projects/").subscribe(
// data =>
// {
// let index: number = this.organizationInfo.projects.get(funder).indexOf(project);
//
// let url: string;
// if(index == 0) {
// url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special&size="+data;
// } else {
// url = this.downloadURLAPI+"projects/"+project.id+"/publications?format=csv-special-notitle&size="+data;
// }
//
// this._reportsService.getCSVResponse(url).subscribe(
// data =>
// {
// counter--;
//
// response[index] = data;
//
// if(counter == 0) {
// for(let i=0; i<this.organizationInfo.projects.get(funder).length; i++) {
// totalResponse += response[i]+"\n";
// }
// window.open(window.URL.createObjectURL(new Blob([totalResponse], { type: 'text/csv' })));
// }
// },
// error => console.log("Error downloading the file."),
// () => console.log('Completed file download.'));
// },
// error => console.log("Error getting number of publications for project."));
// }//);
}
private updateDescription(description:string) {
this._meta.updateTag({content:description},"name='description'");
this._meta.updateTag({content:description},"property='og:description'");
}
private updateTitle(title:string){
var _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 confirmOpenApplyAll(funder: string, funderId:string, funderCountPublications:number){
this.alertApplyAll.cancelButton = true;
this.alertApplyAll.okButton = true;
this.alertApplyAll.alertTitle = "CSV FILE";
this.alertApplyAll.message = "Do you wish to download a CSV file? Note that this process may take a while.";
this.alertApplyAll.okButtonText = "Yes";
this.alertApplyAll.cancelButtonText = "No";
this.alertApplyAll.open();
this.funder = funder;
this.funderId = funderId;
this.funderCountPublications = funderCountPublications;
}
public confirmCloseApplyAll(data){
this.downloadPublicationsFile(this.funder, this.funderId, this.funderCountPublications);
}
public confirmOpenCsvError(){
this.alertCsvError.cancelButton = false;
this.alertCsvError.okButton = true;
this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
this.alertCsvError.okButtonText = "OK";
this.alertCsvError.open();
}
encodeURI(input: string): string {
return StringUtils.URIEncode(input);
}
private handleError(message: string, error) {
console.error("Organizaton Landing Page: "+message, error);
}
}