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

567 lines
22 KiB
TypeScript

import {Component, ElementRef, Input, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Meta, Title} from '@angular/platform-browser';
import {OrganizationService} from '../../services/organization.service';
import {OrganizationInfo} from '../../utils/entities/organizationInfo';
import {ReportsService} from '../../services/reports.service';
import {FetchResearchResults} from '../../utils/fetchEntitiesClasses/fetchResearchResults.class';
// import {FetchDatasets} from '../../utils/fetchEntitiesClasses/fetchDatasets.class';
import {FetchProjects} from '../../utils/fetchEntitiesClasses/fetchProjects.class';
import {FetchDataproviders} from '../../utils/fetchEntitiesClasses/fetchDataproviders.class';
import {SearchResearchResultsService} from '../../services/searchResearchResults.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 {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';
import {HelperFunctions} from "../../utils/HelperFunctions.class";
import {HelperService} from "../../utils/helper/helper.service";
@Component({
selector: 'organization',
templateUrl: 'organization.component.html',
})
export class OrganizationComponent {
@Input() piwikSiteId = null;
@Input() communityId = 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;
public csvAffiliatedPublications: string;
// Active tab variable for responsiveness
public activeTab: string = "Publications";
// Variables for publications, research data, projects, dataproviders tabs
public fetchPublications: FetchResearchResults;
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();
public pageContents = null;
public divContents = null;
//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;
@ViewChild('AlertModalDeletedByInference') alertModalDeletedByInference;
public deleteByInferenceOpened: boolean = false;
//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 _searchResearchResultsService: SearchResearchResultsService,
// private _searchDatasetsService: SearchDatasetsService,
private _searchProjectsService: SearchProjectsService,
private _meta: Meta,
private _title: Title,
private _router: Router,
private helper: HelperService,
private seoService: SEOService) {
this.fetchPublications = new FetchResearchResults(this._searchResearchResultsService);
// 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.getDivContents();
this.getPageContents();
this.updateUrl(data.envSpecific.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";
}
HelperFunctions.scroll();
this.csvParamsTail = '" and relorganizationid exact "' + this.organizationId + '" ))';
});
this.downloadURLAPI = this.properties.csvAPIURL;
this.csvAffiliatedPublications = this.downloadURLAPI + "?format=csv&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relorganizationid exact \"" + this.organizationId + "\"))";
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 ';
}
private getPageContents() {
this.helper.getPageHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
this.pageContents = contents;
})
}
private getDivContents() {
this.helper.getDivHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
this.divContents = contents;
})
}
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.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.properties.searchLinkToOrganization + this.organizationInfo.objIdentifier);
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("publication", "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.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.properties.searchLinkToOrganizations);
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("publication", "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 title_index: number = 0;
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._searchResearchResultsService.numOfEntityResults("publication", projects[index].id, "project", this.properties).subscribe(
data => {
//if(data == 0 && title) { // if no publications for this project
if (data == 0 && (counter > 1 || title)) { // if no publications for this project
counter--;
response[index] = "";
//console.info("index: "+index, "counter: "+counter, "id:"+projects[index].id, response[index]);
if (counter == 0) {
//for(let i=count-1; i>=0; i--) {
for (let i = 0; i < projects.length; i++) {
if (response[i] != "") {
if (i == title_index) {
totalResponse = response[i] + totalResponse;
} else {
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
}
} else {
let url: string;
if (!title) {
title_index = index;
//console.info(title_index);
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 + "?format=csv-special-notitle&type=publications&fq=(((oaftype exact result) and (resulttypeid exact publication)) and (relprojectid exact \"" + projects[index].id + "\"))"
}
title = true;
this.downloadProjectPublSub = this._reportsService.getCSVResponse(url).subscribe(
data => {
counter--;
response[index] = data;
//console.info("index: "+index, "counter: "+counter, "id:"+projects[index].id, response[index]);
if (counter == 0) {
//for(let i=count-1; i>=0; i--) {
for (let i = 0; i < projects.length; i++) {
if (response[i] != "") {
if (i == title_index) {
totalResponse = response[i] + totalResponse;
} else {
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
}
},
err => {
this.handleError("Error downloading file: " + filename, err);
this.closeLoading();
this.confirmOpenCsvError();
}/*,
() => console.log('Completed file download.')*/
);
}
},
err => {
this.handleError("Error getting number of publications for project with id: " + projects[index].id, err);
});
}
},
err => {
this.handleError("Error getting projects for organization with id: " + this.organizationId, err);
this.closeLoading();
this.confirmOpenCsvError();
}
);
}
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 = "";
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 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);
}
openDeletedByInference() {
this.deleteByInferenceOpened = true;
this.alertModalDeletedByInference.cancelButton = false;
this.alertModalDeletedByInference.okButton = false;
this.alertModalDeletedByInference.alertTitle = "Original sources";
this.alertModalDeletedByInference.open();
}
}