connect-admin/src/app/pages/projects/add-projects.component.ts

343 lines
12 KiB
TypeScript

import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {SearchResult} from '../../openaireLibrary/utils/entities/searchResult';
import {ErrorCodes} from '../../openaireLibrary/utils/properties/errorCodes';
import {SearchUtilsClass} from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';
import {SearchProjectsService} from '../../openaireLibrary/services/searchProjects.service';
import {RouterHelper} from '../../openaireLibrary/utils/routerHelper.class';
import {StringUtils} from '../../openaireLibrary/utils/string-utils.class';
import {ManageCommunityProjectsService} from '../../services/manageProjects.service';
import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {properties} from "../../../environments/environment";
import {Subscriber} from "rxjs";
import {FormBuilder, FormGroup} from "@angular/forms";
import {Option} from "../../openaireLibrary/sharedComponents/input/input.component";
import {debounceTime, distinctUntilChanged} from "rxjs/operators";
import {ResultPreview} from "../../openaireLibrary/utils/result-preview/result-preview";
import {SearchInputComponent} from "../../openaireLibrary/sharedComponents/search-input/search-input.component";
declare var UIkit;
@Component({
selector: 'add-projects',
templateUrl: './add-projects.component.html',
})
export class AddProjectsComponent implements OnInit {
private subscriptions: any[] = [];
public subResults: any;
private community: string = '';
public routerHelper: RouterHelper = new RouterHelper();
public properties: EnvProperties = properties;
public errorCodes: ErrorCodes;
public openaireSearchUtils: SearchUtilsClass = new SearchUtilsClass();
@Output() communityProjectsChanged = new EventEmitter();
@Input() communityProjects = [];
public openaireProjects = [];
public queryParameters: string = "";
// public pagingLimit: number = properties.pagingLimit;
public resultsPerPage: number = properties.resultsPerPage;
public selectedFunderId: string = "";
filterForm: FormGroup;
allOptions: Option[] = [];
@ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
private projectUrl: string = "https://" + ((properties.environment == "beta" || properties.environment == "development") ? "beta." : "") + "explore.openaire.eu" + properties.searchLinkToProject;
public body: string = "Send from page";
@Output() toggleView: EventEmitter<any> = new EventEmitter();
constructor(private route: ActivatedRoute, private _router: Router, private _searchProjectsService: SearchProjectsService,
private _manageCommunityProjectsService: ManageCommunityProjectsService,
private _fb: FormBuilder) {
this.errorCodes = new ErrorCodes();
this.openaireSearchUtils.status = this.errorCodes.LOADING;
}
ngOnInit() {
this.subscriptions.push(this.route.params.subscribe(params => {
this.openaireSearchUtils.status = this.errorCodes.LOADING;
this.community = params['community'];
// this.projectUrl = "https://" + ((this.properties.environment == "beta" || this.properties.environment == "development") ? "beta." : "")
// + this.community + ".openaire.eu" + this.properties.searchLinkToProject;
this.getFunders();
this._getOpenaireProjects("", 1, this.resultsPerPage);
this.body = "[Please write your message here]";
this.body = StringUtils.URIEncode(this.body);
}));
this.openaireSearchUtils.keyword = "";
this.filterForm = this._fb.group({
keyword: [''],
funder: []
});
this.subscriptions.push(this.filterForm.get('keyword').valueChanges
.pipe(debounceTime(1000), distinctUntilChanged())
.subscribe(value => {
this.keywordChanged(value);
}));
this.subscriptions.push(this.filterForm.get('funder').valueChanges
.pipe(debounceTime(1000), distinctUntilChanged())
.subscribe(value => {
// console.log("value: ",value);
if (value == null) {
// console.log("will be called funder changed: null");
this.funderChanged("", "");
} else if (value && value.id != undefined && value.id != this.selectedFunderId) {
// console.log("will be called funder changed: name="+value.label+", id="+value.id);
this.funderChanged(value.id, value.label);
}
}));
}
public ngOnDestroy() {
this.subscriptions.forEach(sub => {
if (sub instanceof Subscriber) {
sub.unsubscribe();
}
});
if (this.subResults) {
this.subResults.unsubscribe();
}
}
public addProject(project: SearchResult) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
"errorCode": LoginErrorCodes.NOT_VALID,
"redirectUrl": this._router.url
}
});
} else {
this.subscriptions.push(this._manageCommunityProjectsService.addProject(this.properties, this.community, project).subscribe(
data => {
this.communityProjects.push(data);
UIkit.notification('Project successfully added!', {
status: 'success',
timeout: 6000,
pos: 'bottom-right'
});
this.communityProjectsChanged.emit({
value: this.communityProjects,
});
},
err => {
this.handleError('An error has been occurred. Try again later!');
console.error(err.status);
}
));
}
}
public removeProject(project: any) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
"errorCode": LoginErrorCodes.NOT_VALID,
"redirectUrl": this._router.url
}
});
} else {
let communityProject = this.getCommunityProject(project);
let projectId: string = communityProject['id'];
this.subscriptions.push(this._manageCommunityProjectsService.removeProject(this.properties, this.community, projectId).subscribe(
data => {
let index = this.communityProjects.indexOf(communityProject);
this.communityProjects.splice(index, 1);
UIkit.notification('Project successfully removed!', {
status: 'success',
timeout: 6000,
pos: 'bottom-right'
});
this.communityProjectsChanged.emit({
value: this.communityProjects,
});
},
err => {
this.handleError('An error has been occurred. Try again later!');
console.error(err);
}
));
}
}
public getCommunityProject(project: any): string {
let index: number = 0;
for (let communityProject of this.communityProjects) {
if (communityProject.openaireId == project.id ||
(project.code == communityProject.grantId && project.funderShortname == communityProject.funder)) {
return communityProject;
}
index++;
}
return "";
}
getFunders() {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
"errorCode": LoginErrorCodes.NOT_VALID,
"redirectUrl": this._router.url
}
});
} else {
this.subscriptions.push(this._searchProjectsService.getFunders(this.properties).subscribe(
data => {
let funders = data[1];
this.allOptions = [];
let i;
for (i = 0; i < funders.length; i++) {
let funder = funders[i];
if (funder && funder['id']) {
this.allOptions.push({label: funder['name'], value: {id: funder['id'], label: funder['name']}});
}
}
},
err => console.error("Server error fetching funders: ", err)
));
}
}
public getResultPreview(result: SearchResult): ResultPreview {
return ResultPreview.searchResultConvert(result, "project");
}
private _getOpenaireProjects(parameters: string, page: number, size: number) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
"errorCode": LoginErrorCodes.NOT_VALID,
"redirectUrl": this._router.url
}
});
} else {
// if (page > this.pagingLimit) {
// size = 0;
// }
if (this.openaireSearchUtils.status == this.errorCodes.LOADING) {
this.openaireSearchUtils.status = this.errorCodes.LOADING;
this.openaireProjects = [];
this.openaireSearchUtils.totalResults = 0;
if (this.subResults) {
this.subResults.unsubscribe();
}
this.subResults = this._searchProjectsService.searchProjects(parameters, null, page, size, [], this.properties).subscribe(
data => {
this.openaireSearchUtils.totalResults = data[0];
this.openaireProjects = data[1];
//this.searchPage.checkSelectedFilters(this.filters);
this.openaireSearchUtils.status = this.errorCodes.DONE;
if (this.openaireSearchUtils.totalResults == 0) {
this.openaireSearchUtils.status = this.errorCodes.NONE;
}
// if (this.openaireSearchUtils.status == this.errorCodes.DONE) {
// // Page out of limit!!!
// let totalPages: any = this.openaireSearchUtils.totalResults / (this.openaireSearchUtils.size);
// if (!(Number.isInteger(totalPages))) {
// totalPages = (parseInt(totalPages, 10) + 1);
// }
// if (totalPages < page) {
// this.openaireSearchUtils.totalResults = 0;
// this.openaireSearchUtils.status = this.errorCodes.OUT_OF_BOUND;
// }
// }
},
err => {
console.error(err);
//TODO check erros (service not available, bad request)
if (err.status == '404') {
this.openaireSearchUtils.status = this.errorCodes.NOT_FOUND;
} else if (err.status == '500') {
this.openaireSearchUtils.status = this.errorCodes.ERROR;
} else {
this.openaireSearchUtils.status = this.errorCodes.NOT_AVAILABLE;
}
}
);
}
}
}
totalPages(): number {
let totalPages: any = this.openaireSearchUtils.totalResults / (this.resultsPerPage);
if (!(Number.isInteger(totalPages))) {
totalPages = (parseInt(totalPages, 10) + 1);
}
return totalPages;
}
keywordChanged(keyword) {
this.openaireSearchUtils.keyword = keyword;
this.buildQueryParameters();
this.goTo(1);
}
funderChanged(funderId: string, funderName: string) {
this.selectedFunderId = funderId;
this.buildQueryParameters();
this.goTo(1);
}
buildQueryParameters() {
this.queryParameters = "";
if (this.openaireSearchUtils.keyword) {
this.queryParameters = "q=" + StringUtils.URIEncode(this.openaireSearchUtils.keyword);
}
if (this.selectedFunderId) {
this.queryParameters += this.queryParameters ? "&" : "";
this.queryParameters += "fq=funder exact " + '"' + StringUtils.URIEncode(this.selectedFunderId) + '"';
}
}
goTo(page: number = 1) {
this.openaireSearchUtils.page = page;
this.openaireSearchUtils.status = this.errorCodes.LOADING;
this._getOpenaireProjects(this.queryParameters, page, this.resultsPerPage);
}
back() {
this.toggleView.emit(null);
}
public onSearchClose() {
this.openaireSearchUtils.keyword = this.filterForm.get('keyword').value;
}
public resetInput() {
this.openaireSearchUtils.keyword = null;
this.searchInputComponent.reset()
}
handleError(message: string) {
UIkit.notification(message, {
status: 'danger',
timeout: 6000,
pos: 'bottom-right'
});
}
}