monitor/src/app/funders/searchFunders.component.ts

400 lines
14 KiB
TypeScript

import {Component, ViewChild} from "@angular/core";
import {SearchUtilsClass} from "../openaireLibrary/searchPages/searchUtils/searchUtils.class";
import {ErrorMessagesComponent} from "../openaireLibrary/utils/errorMessages.component";
import {ErrorCodes} from "../openaireLibrary/utils/properties/errorCodes";
import {EnvProperties} from "../openaireLibrary/utils/properties/env-properties";
import {SearchPageComponent} from "../openaireLibrary/searchPages/searchUtils/searchPage.component";
import {ActivatedRoute} from "@angular/router";
import {Filter, Value} from "../openaireLibrary/searchPages/searchUtils/searchHelperClasses.class";
import {SearchFields} from "../openaireLibrary/utils/properties/searchFields";
import {Session, User} from "../openaireLibrary/login/utils/helper.class";
import {CommunityInfo} from "../openaireLibrary/connect/community/communityInfo";
import {StringUtils} from "../openaireLibrary/utils/string-utils.class";
import {HelperFunctions} from "../openaireLibrary/utils/HelperFunctions.class";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {StakeholderService} from "../services/stakeholder.service";
@Component({
selector: 'search-funders',
template: `
<search-page pageTitle="OpenAIRE-Monitor | Search Funders"
[hasPrefix]=false [piwikSiteId]="piwikSiteId"
searchFormClass="communitiesSearchForm"
formPlaceholderText="Search for funders"
type="funders" entityType="funder" [filters]="filters"
[results]="results" [searchUtils]="searchUtils"
[showResultCount]=true [baseUrl]="baseUrl"
[disableForms]="disableForms"
[lastIndex]=false [sort]=true
[showType]="showType" >
</search-page>
`
})
export class SearchFundersComponent {
public piwikSiteId = null;
private errorCodes: ErrorCodes;
private errorMessages: ErrorMessagesComponent;
public results= [];
public totalResults: CommunityInfo[] = [];
public sub: any; public subResults: any;
public filters = [];
public searchFields:SearchFields = new SearchFields();
public searchUtils:SearchUtilsClass = new SearchUtilsClass();
public disableForms: boolean = false;
public baseUrl: string = null;
public refineFields: string[] = ["jurisdiction"];//this.searchFields.COMMUNITIES_SEARCH_FIELDS;
public showType = false;
properties:EnvProperties;
@ViewChild (SearchPageComponent) searchPage : SearchPageComponent ;
private user: User;
constructor (private route: ActivatedRoute,
private _stakeholderService: StakeholderService,
private userManagementService: UserManagementService) {
this.errorCodes = new ErrorCodes();
this.errorMessages = new ErrorMessagesComponent();
this.searchUtils.status = this.errorCodes.LOADING;
}
public ngOnInit() {
this.route.data
.subscribe((data: { envSpecific: EnvProperties }) => {
this.properties = data.envSpecific;
this.piwikSiteId = this.properties.piwikSiteId;
this.baseUrl = "/search/find/funders";
});
this.sub = this.route.queryParams.subscribe(params => {
this.searchPage.resultsPerPage = 10;
this.searchUtils.keyword = (params['keyword']?params['keyword']:'');
this.searchUtils.page = (params['page'] === undefined) ? 1: + params['page'];
this.searchUtils.sortBy = (params['sortBy'] === undefined)? '' : params['sortBy'];
this.searchUtils.size = (params['size'] === undefined) ? this.searchPage.resultsPerPage: +params['size'];
this.searchPage.searchUtils = this.searchUtils;
if(this.searchUtils.size != 5 && this.searchUtils.size != 10 && this.searchUtils.size != 20 && this.searchUtils.size != 50) {
this.searchUtils.size = this.searchPage.resultsPerPage;
}
if(this.searchUtils.sortBy && this.searchUtils.sortBy != "creationdate,descending" && this.searchUtils.sortBy != "creationdate,ascending") {
this.searchUtils.sortBy = "";
}
this.searchPage.refineFields = this.refineFields;
let queryParams = this.searchPage.getQueryParamsFromUrl(params);
console.log(queryParams)
if(typeof document !== 'undefined') {
this.userManagementService.getUserInfo(this.properties.userInfoUrl).subscribe(user => {
this.user = user;
this.initFunders(queryParams);
});
} else {
this.initFunders(queryParams);
}
});
}
public ngOnDestroy() {
if(this.sub){
this.sub.unsubscribe();
}
if(this.subResults){
this.subResults.unsubscribe();
}
}
/**
* Initialize funders from Communities APIs
*
* @param params
*/
private initFunders(params: Map<string, string>) {
this.subResults = this._stakeholderService.mockgetFunders().subscribe(
data => {
if(!data){
return;
}
for(let i = 0; i < data.length; i++) {
if(data[i]["jurisdiction"]){
if(data[i]["jurisdiction"]=='European Union'){
data[i]["jurisdictionLogo"] = "eu";
}else if (StringUtils.isEuropeanCountry(data[i]["jurisdiction"])){
data[i]["jurisdictionLogo"] = "europe";
}else{
data[i]["jurisdictionLogo"] = "international";
}
}else{
data[i]["jurisdictionLogo"] = "";
}
this.totalResults[i] = data[i];
}
this._getResults(params);
},
err => {
this.handleError('Error getting funders', err);
this.searchUtils.status = this.errorMessages.getErrorCode(err.status);
this.disableForms = false;
HelperFunctions.scroll();
}
);
}
/**
* Get all funders from mock API and apply permission access validator,
* keyword searching, filter, paging and sorting.
*
* @param params, status
* @private
*/
private _getResults(params: Map<string, string>){
this.searchUtils.status = this.errorCodes.LOADING;
this.disableForms = true;
this.results = this.totalResults;
if(this.filters.length == 0){
this.filters = this.createFilters();
}
this.searchUtils.totalResults = 0;
this.applyParams(params);
}
/**
* Return the funders in which user has permission to view or manage.
*/
private showFunders() {
let ret = [];
for(let result of this.results) {
if (result.status == 'hidden') {
continue;
}
ret.push(result);
}
this.results = ret;
}
/**
* Apply permission access validator,
* keyword searching, filter, paging and sorting.
*
* @param params
* @param status
*/
public applyParams(params: Map<string, string>) {
this.showFunders();
if(this.searchUtils.keyword && this.searchUtils.keyword != '') {
this.searchForKeywords();
}
this.checkFilters(params);
this.sort();
this.searchUtils.totalResults = this.results.length;
this.searchPage.checkSelectedFilters(this.filters);
this.searchPage.updateBaseUrlWithParameters(this.filters);
this.results = this.results.slice((this.searchUtils.page-1)*this.searchUtils.size, (this.searchUtils.page*this.searchUtils.size));
this.searchUtils.status = this.errorCodes.DONE;
if(this.searchUtils.totalResults == 0 ){
this.searchUtils.status = this.errorCodes.NONE;
}
this.disableForms = false;
if(this.searchUtils.status == this.errorCodes.DONE) {
// Page out of limit!!!
let totalPages:any = this.searchUtils.totalResults/(this.searchUtils.size);
if(!(Number.isInteger(totalPages))) {
totalPages = (parseInt(totalPages, 10) + 1);
}
if(totalPages < this.searchUtils.page) {
this.searchUtils.totalResults = 0;
this.searchUtils.status = this.errorCodes.OUT_OF_BOUND;
}
}
HelperFunctions.scroll();
}
/**
* Parse the given keywords into array and check if any of the requirements field of a funder includes
* one of the given words.
*/
private searchForKeywords() {
let ret= [];
let keywords: string[] = this.searchUtils.keyword.split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,-1);
for(let i = 0; i < this.results.length; i++) {
for(let keyword of keywords) {
keyword = keyword.toLowerCase();
if (keyword != '' && (this.results[i].title.toLowerCase().includes(keyword) || this.results[i].shortTitle.toLowerCase().includes(keyword) ||
this.results[i].alias.toLowerCase().includes(keyword) || this.results[i].description.toLowerCase().includes(keyword))) {
ret.push(this.results[i]);
break;
}
}
}
this.results = ret;
}
/**
* Check the current results if they satisfy the values of each filter category and
* update the number of possible results in each value.
*
* @param params
*/
private checkFilters(params: Map<string, string>) {
let jurisdictionResults = this.applyFilter('jurisdiction', params);
this.resetFilterNumbers('jurisdiction');
this.results = this.results.filter(value => {
return jurisdictionResults.includes(value);
});
this.updateFilterNumbers(this.results, 'jurisdiction');
}
/**
* Apply filter with filterId and return the results
*
* @param filterId
* @param params
*/
private applyFilter(filterId: string, params: Map<string, string>):any {
console.log("Apply filter "+ filterId);
let results = [];
let values: string[] = [];
if(params.get(filterId) != undefined) {
values = (StringUtils.URIDecode(params.get(filterId))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,-1);
}
console.log(values);
if(filterId == 'jurisdiction') {
console.log('Here');
for (let i = 0; i < this.results.length; i++) {
if (values.length == 0) {
results.push(this.results[i]);
} else {
for (let value of values) {
console.log(value);
if (this.results[i]['jurisdiction'] == value.replace(/["']/g, "")) {
results.push(this.results[i]);
break;
}
}
}
}
}
console.log(results);
return results;
}
/**
* Reset the values of filter with id filterId with zero.
*
* @param filterId
*/
private resetFilterNumbers(filterId: string) {
for (let i = 0; i < this.filters.length; i++) {
if(this.filters[i].filterId == filterId) {
for (let j = 0; j < this.filters[i].values.length; j++) {
this.filters[i].values[j].number = 0;
}
break;
}
}
}
/**
* Update the values of filter with id filterId based on
* results.
*
* @param results
* @param filterId
*/
private updateFilterNumbers(results, filterId: string) {
for(let k = 0; k < results.length; k++) {
for (let i = 0; i < this.filters.length; i++) {
if(this.filters[i].filterId == filterId) {
if (this.filters[i].filterId == 'jurisdiction') {
for (let j = 0; j < this.filters[i].values.length; j++) {
if (results[k]['jurisdiction'] == this.filters[i].values[j].id) {
this.filters[i].values[j].number++;
break;
}
}
}
}
}
}
}
/**
* Sorting results based on sortBy.
*/
private sort() {
if(this.searchUtils.sortBy == '') {
this.results.sort((left, right): number => {
if (left.title > right.title) {
return 1;
} else if (left.title < right.title) {
return -1;
} else {
return 0;
}
})
} else if(this.searchUtils.sortBy == 'creationdate,descending') {
this.results.sort((left, right): number => {
if (!right.date || left.date > right.date) {
return -1;
} else if (!left.date || left.date < right.date) {
return 1;
} else {
return 0;
}
})
} else if(this.searchUtils.sortBy == 'creationdate,ascending') {
this.results.sort((left, right): number => {
if (!right.date || left.date > right.date) {
return 1;
} else if (!left.date || left.date < right.date) {
return -1;
} else {
return 0;
}
})
}
}
/**
* Create Search Communities filters.
*
*/
private createFilters(): Filter[] {
let filter_names = [];
let filter_ids = [];
let filter_original_ids = ["jurisdiction"];
console.log("init refine")
let value_names = [];
let value_original_ids=[];
value_names[0]=[];
value_original_ids[0]=[];
filter_names.push("Jurisdiction");
filter_ids.push("jurisdiction");
this.results.forEach(result => {
if(result['jurisdiction'] && result['jurisdiction'].length > 0) {
value_names[0].push(result['jurisdiction']);
value_original_ids[0].push(result['jurisdiction']);
}
});
let filters: Filter[] = [];
for(let i =0 ; i < filter_names.length; i++){
let values: Value[] = [];
for(let j =0 ; j < value_names[i].length; j++){
let value: Value = {name: value_names[i][j], id: value_original_ids[i][j], number:0, selected:false};
values.push(value);
}
let filter: Filter = {title: filter_names[i], filterId: filter_ids[i], originalFilterId: filter_original_ids[i], values : values, countSelectedValues:0, "filterOperator": 'or', valueIsExact: true , valueIsUnique: false};
filters.push(filter);
}
return filters;
}
private handleError(message: string, error) {
console.error('Communities Search Page: ' + message, error);
}
}