connect-admin/src/app/pages/content-providers/remove-content-providers.co...

387 lines
13 KiB
TypeScript

import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {Subscriber} from 'rxjs';
import {ErrorCodes} from '../../openaireLibrary/utils/properties/errorCodes';
import {SearchUtilsClass} from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';
import {ManageCommunityContentProvidersService} from '../../services/manageContentProviders.service';
import {SearchCommunityDataprovidersService} from '../../openaireLibrary/connect/contentProviders/searchDataproviders.service';
import {RouterHelper} from '../../openaireLibrary/utils/routerHelper.class';
import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {Criteria, SelectionCriteria} from '../../openaireLibrary/utils/entities/contentProvider';
import {properties} from "../../../environments/environment";
import {SearchInputComponent} from "../../openaireLibrary/sharedComponents/search-input/search-input.component";
import {FormBuilder, FormGroup} from "@angular/forms";
import {Option} from "../../openaireLibrary/sharedComponents/input/input.component";
import {CommunityService} from "../../openaireLibrary/connect/community/community.service";
import {CriteriaUtils} from "./criteria-utils";
declare var UIkit;
@Component({
selector: 'remove-content-providers',
templateUrl: './remove-content-providers.component.html'
})
export class RemoveContentProvidersComponent implements OnInit {
public portal: string;
public name: string;
public routerHelper: RouterHelper = new RouterHelper();
public contentProviderUrl = "https://" + ((properties.environment == "beta" || properties.environment == "development") ? "beta." : "") + "explore.openaire.eu" + properties.searchLinkToDataProvider;
public previewCommunityContentProviders = [];
public communitySearchUtils: SearchUtilsClass = new SearchUtilsClass();
public errorCodes: ErrorCodes;
@Input() public showLoading: boolean = true;
@Input() public communityContentProviders = [];
@Output() communityContentProvidersChanged = new EventEmitter();
private properties: EnvProperties = properties;
private subscriptions: any[] = [];
private selectedCommunityContentProvider: any;
@ViewChild('AlertModalDeleteCommunity') alertModalDeleteCommunity;
/** Criteria */
private fields = CriteriaUtils.fields;
private verbs = CriteriaUtils.verbs;
/** Paging */
page: number = 1;
resultsPerPage: number = properties.resultsPerPage;
/** Search */
@ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
filterForm: FormGroup;
private searchText: RegExp = new RegExp('');
public keyword: string = '';
sortOptions: Option[] = [
{label: "Name ", value: {sort: "name", descending: false}},
{label: "Official Name ", value: {sort: "officialname", descending: false}}
];
@Output() toggleView: EventEmitter<any> = new EventEmitter();
@Input() public toggle: boolean = true;
constructor(private route: ActivatedRoute, private _router: Router,
private _fb: FormBuilder, private communityService: CommunityService,
private _manageCommunityContentProvidersService: ManageCommunityContentProvidersService,
private _searchCommunityContentProvidersService: SearchCommunityDataprovidersService) {
this.errorCodes = new ErrorCodes();
this.communitySearchUtils.status = this.errorCodes.LOADING;
}
ngOnInit() {
this.communitySearchUtils.keyword = "";
this.filterForm = this._fb.group({
keyword: [''],
// sort: this._fb.control(this.sortOptions[0].value)
});
this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
this.searchText = new RegExp(value, 'i');
this.page = 1;
this.applyFilters();
}));
// this.subscriptions.push(this.filterForm.get('sort').valueChanges.subscribe(value => {
// this.page = 1;
// this.sort();
// }));
this.subscriptions.push(this.communityService.getCommunityAsObservable().subscribe(community => {
if (community) {
this.portal = community.communityId;
this.name = community.shortTitle;
this.contentProviderUrl = "https://"
+ ((this.properties.environment == "beta" || this.properties.environment == "development") ? "beta." : "")
+ this.portal + ".openaire.eu" + this.properties.searchLinkToDataProvider;
this.keyword = '';
this._getCommunityContentProviders();
}
}));
}
public ngOnDestroy() {
this.subscriptions.forEach(sub => {
if (sub instanceof Subscriber) {
sub.unsubscribe();
}
});
}
public getCriteriaLabel(selectionCriteria: SelectionCriteria): string {
if (selectionCriteria && selectionCriteria.criteria.length > 0) {
return (selectionCriteria.criteria.length === 1) ? '1 criterion' : (selectionCriteria.criteria.length + ' criteria')
} else {
return 'no criteria';
}
}
// filterData(row: any, query: string) {
// let returnValue: boolean = false;
//
// if(query) {
// for(var i=0; i <2; i++){
// var r= this.filterQuery(row[i], query);
// if(r) {
// returnValue = true;
// break;
// }
// }
//
// if(!returnValue) {
// return false;
// }
// }
//
// return true;
// }
//
// filterQuery(data, query){
// if(data.toLowerCase().indexOf(query.toLowerCase()) > -1){
// return true;
// }else{
// return false;
// }
// }
public inCommunity(result: any): any {
let found = false;
for (let contentProvider of this.communityContentProviders) {
if (contentProvider.opeaireId == result.id) {
return true;
}
}
return found;
}
totalPages(): number {
let totalPages: any = this.communitySearchUtils.totalResults / (this.resultsPerPage);
if (!(Number.isInteger(totalPages))) {
totalPages = (parseInt(totalPages, 10) + 1);
}
return totalPages;
}
getFiltersAsText(criteria: Criteria[]): string {
let text = criteria.slice(0,3).map((criterion, index) => (index + 1) + ". " + criterion.constraint.map(constraint => {
let field = this.fields.find(field => field.value === constraint.field).label;
let matchCase = false;
if(!constraint.verb.includes('_caseinsensitive')) {
matchCase = true;
}
let verb = this.verbs.find(verb => verb.value === constraint.verb.replace("_caseinsensitive", "")).label;
let value = '"' + constraint.value + '"' + (matchCase?" (Match case)":"");
return field + " " + verb + " " + value;
}).join(" <b>and</b> "));
return text.join("<br>");
}
// goTo(page:number = 1){
// this.communitySearchUtils.page=page;
//
// var table = $('#dpTable').DataTable();
// table.page( page - 1 ).draw( false );
//
// var info = table.page.info();
// this.communitySearchUtils.totalResults = info.recordsDisplay;
// }
public confirmedDeleteContentProvider(data: any) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
"errorCode": LoginErrorCodes.NOT_VALID,
"redirectUrl": this._router.url
}
});
} else {
this.subscriptions.push(this._manageCommunityContentProvidersService.removeContentProvider(this.properties, this.portal, this.selectedCommunityContentProvider.id).subscribe(
data => {
let index = this.communityContentProviders.indexOf(this.selectedCommunityContentProvider);
this.communityContentProviders.splice(index, 1);
this.applyFilters();
UIkit.notification('Content Provider successfully removed!', {
status: 'success',
timeout: 6000,
pos: 'bottom-right'
});
this.communityContentProvidersChanged.emit({
value: this.communityContentProviders,
});
this.communitySearchUtils.totalResults--;
this.communitySearchUtils.page = 1;
},
err => {
this.handleError('An error has been occurred. Try again later!');
console.error(err);
}
));
}
}
public removeContentProvider(communityContentProvider: any) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
"errorCode": LoginErrorCodes.NOT_VALID,
"redirectUrl": this._router.url
}
});
} else {
this.selectedCommunityContentProvider = communityContentProvider;
this.alertModalDeleteCommunity.cancelButton = true;
this.alertModalDeleteCommunity.okButton = true;
this.alertModalDeleteCommunity.alertTitle = "Remove content provider?";
let title = "";
if (communityContentProvider.name) {
title = communityContentProvider.name;
}
if (communityContentProvider.name && communityContentProvider.acronym) {
title += " (";
}
if (communityContentProvider.acronym) {
title += communityContentProvider.acronym;
}
if (communityContentProvider.name && communityContentProvider.acronym) {
title += ")";
}
this.alertModalDeleteCommunity.message = "Content Provider";
if (title) {
this.alertModalDeleteCommunity.message += " '" + title + "' ";
}
this.alertModalDeleteCommunity.message += "will be removed from your community. Are you sure?";
this.alertModalDeleteCommunity.okButtonText = "Yes";
this.alertModalDeleteCommunity.open();
}
}
public _getCommunityContentProviders() {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
"errorCode": LoginErrorCodes.NOT_VALID,
"redirectUrl": this._router.url
}
});
} else {
this.communitySearchUtils.status = this.errorCodes.LOADING;
this.communityContentProviders = [];
this.communitySearchUtils.totalResults = 0;
this.communitySearchUtils.page = 1;
this.communitySearchUtils.keyword = "";
this.subscriptions.push(this._searchCommunityContentProvidersService.searchDataproviders(this.properties, this.portal).subscribe(
data => {
this.communityContentProviders = data;
this.previewCommunityContentProviders = this.communityContentProviders;
// this.sort();
this.communitySearchUtils.totalResults = data.length;
this.communitySearchUtils.status = this.errorCodes.DONE;
this.communityContentProvidersChanged.emit({
value: this.communityContentProviders,
});
this.showLoading = false;
},
err => {
console.error(err);
//TODO check erros (service not available, bad request)
if (err.status == '404') {
this.communitySearchUtils.status = this.errorCodes.NOT_FOUND;
} else if (err.status == '500') {
this.communitySearchUtils.status = this.errorCodes.ERROR;
} else {
this.communitySearchUtils.status = this.errorCodes.NOT_AVAILABLE;
}
this.showLoading = false;
}
));
}
}
public updatePage($event) {
this.page = $event.value;
}
addNew() {
this.toggleView.emit(null);
}
public applyFilters() {
this.previewCommunityContentProviders = this.communityContentProviders.filter(contentProvider => {
return this.filterCommunityContentProviderByKeyword(contentProvider);
});
// check paging here!!!
if (this.previewCommunityContentProviders.slice((this.page - 1) * this.resultsPerPage, this.page * this.resultsPerPage).length == 0) {
this.page = 1;
}
// this.sort();
}
public filterCommunityContentProviderByKeyword(contentProvider): boolean {
const textFlag = this.searchText.toString() === ''
|| (contentProvider.name + " " + contentProvider.officialname).match(this.searchText) != null;
return textFlag;
}
private sort() {
let sortOption: { sort: string, descending: boolean } = this.filterForm.get('sort').value;
this.previewCommunityContentProviders.sort((left, right): number => {
if (sortOption.sort == "name") {
if (left.name > right.name) {
return sortOption.descending ? -1 : 1;
} else if (left.name < right.name) {
return sortOption.descending ? 1 : -1;
}
} else if (sortOption.sort == "officialname") {
if (left.officialname > right.officialname) {
return sortOption.descending ? -1 : 1;
} else if (left.officialname < right.officialname) {
return sortOption.descending ? 1 : -1;
}
}
return 0;
});
}
public onSearchClose() {
this.communitySearchUtils.keyword = this.filterForm.get('keyword').value;
}
public resetInput() {
this.communitySearchUtils.keyword = null;
this.searchInputComponent.reset()
}
handleError(message: string) {
UIkit.notification(message, {
status: 'danger',
timeout: 6000,
pos: 'bottom-right'
});
}
goToCriteria(openaireId: string) {
this._router.navigate([openaireId], {
queryParams: {
// community: this.portal,
// provider: openaireId
},
relativeTo: this.route
})
}
}