openaire-library/dashboard/page/pages.component.ts

517 lines
17 KiB
TypeScript

import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {HelpContentService} from '../../services/help-content.service';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CheckPage, Page} from '../../utils/entities/adminTool/page';
import {Entity} from '../../utils/entities/adminTool/entity';
import {EnvProperties} from '../../utils/properties/env-properties';
import {Session} from '../../login/utils/helper.class';
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
import {UserManagementService} from '../../services/user-management.service';
import {Subscriber} from "rxjs";
import {PortalUtils} from "../portal/portalHelper";
import {properties} from "../../../../environments/environment";
import {ConnectHelper} from "../../connect/connectHelper";
import {Option} from "../../sharedComponents/input/input.component";
import {AlertModal} from "../../utils/modal/alert";
import {SearchInputComponent} from "../../sharedComponents/search-input/search-input.component";
declare var UIkit;
@Component({
selector: 'pages',
templateUrl: './pages.component.html',
})
export class PagesComponent implements OnInit {
@ViewChild('editModal') editModal: AlertModal;
@ViewChild('deleteModal') deleteModal: AlertModal;
private selectedPages: string[] = [];
public checkboxes: CheckPage[] = [];
public pages: Page[] = [];
public pageWithDivIds: string[] = [];
//public errorMessage: string;
public pageForm: FormGroup;
private searchText: RegExp = new RegExp('');
public keyword: string = '';
public portal: string;
public pagesType: string;
public properties: EnvProperties = properties;
public showLoading: boolean = true;
public errorMessage: string = '';
public updateErrorMessage: string = '';
public modalErrorMessage: string = '';
public isPortalAdministrator = null;
public filterForm: FormGroup;
public typeOptions = [{label: 'Search', value: 'search'}, {
label: 'Share',
value: 'share'
}, {label: 'Landing', value: 'landing'}, {label: 'HTML', value: 'html'}, {
label: 'Link',
value: 'link'
}, {label: 'Other', value: 'other'}];
public entitiesCtrl: FormArray;
@ViewChild('PageInput') pageInput: ElementRef<HTMLInputElement>;
allEntities: Option[] = [];
private subscriptions: any[] = [];
public portalUtils: PortalUtils = new PortalUtils();
private index: number;
public selectedKeyword: string;
@ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
constructor(private element: ElementRef, private route: ActivatedRoute,
private _router: Router, private _helpContentService: HelpContentService,
private userManagementService: UserManagementService, private _fb: FormBuilder) {
}
ngOnInit() {
this.filterForm = this._fb.group({
keyword: [''],
type: ['all', Validators.required]
});
this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
this.searchText = new RegExp(value, 'i');
this.applyFilters();
}));
this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => {
this.applyFilters();
}));
this.subscriptions.push(this.route.queryParams.subscribe(params => {
this.pagesType = '';
if (params['type']) {
// this.pagesType = params['type'];
this.filterForm.get('type').setValue(params['type']);
}
this.portal = (this.route.snapshot.data.portal) ? this.route.snapshot.data.portal : this.route.snapshot.params[this.route.snapshot.data.param];
if (this.portal === 'connect' || this.portal === 'explore') {
ConnectHelper.setPortalTypeFromPid(this.portal);
}
this.keyword = '';
this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
this.applyPortalFilter(this.portal);
this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.portal;
}));
}));
this.subscriptions.push(this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
entities => {
this.allEntities = [];
entities.forEach(entity => {
this.allEntities.push({
label: entity.name,
value: entity
});
});
},
error => this.handleError('System error retrieving pages', error)));
}
ngOnDestroy(): void {
this.subscriptions.forEach(value => {
if (value instanceof Subscriber) {
value.unsubscribe();
} else if (value instanceof Function) {
value();
}
});
}
getPages(portal: string) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
this.showLoading = true;
this.updateErrorMessage = '';
this.errorMessage = '';
this.pageWithDivIds = [];
let parameters = '';
if (this.pagesType) {
parameters = '?page_type=' + this.pagesType;
}
if (portal) {
this.subscriptions.push(this._helpContentService.getCommunityPagesByType(portal, parameters, this.properties.adminToolsAPIURL).subscribe(
pages => {
this.pagesReturned(pages);
//if(!this.pagesType || this.pagesType == "link") {
this.getPagesWithDivIds(portal);
//} else {
//this.showLoading = false;
//}
},
error => this.handleError('System error retrieving pages', error)
));
} else {
this.subscriptions.push(this._helpContentService.getAllPagesFull(this.properties.adminToolsAPIURL).subscribe(
pages => {
this.pagesReturned(pages);
this.showLoading = false;
},
error => this.handleError('System error retrieving pages', error)
));
}
}
}
getPagesWithDivIds(portal: string) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
this.subscriptions.push(this._helpContentService.getPageIdsFromDivIds(portal, this.properties.adminToolsAPIURL).subscribe(
pages => {
this.pageWithDivIds = pages;
this.showLoading = false;
},
error => this.handleError('System error retrieving information about pages\' classes', error)));
}
}
pagesReturned(pages: Page[]) {
this.pages = pages;
this.checkboxes = [];
if (pages) {
pages.forEach(_ => {
this.checkboxes.push(<CheckPage>{page: _, checked: false});
});
}
}
/*
getPortals() {
this._helpContentService.getCommunities(this.properties.adminToolsAPIURL).subscribe(
communities => {
this.communities = communities;
this.portal = this.communities[0].pid;
this.getPages(this.portal);
this.getPagesWithDivIds(this.portal);
},
error => this.handleError('System error retrieving communities', error));
}
*/
public toggleCheckBoxes(event) {
this.checkboxes.forEach(_ => _.checked = event.target.checked);
}
public applyCheck(flag: boolean) {
this.checkboxes.forEach(_ => _.checked = flag);
}
public getSelectedPages(): string[] {
return this.checkboxes.filter(page => page.checked == true).map(checkedPage => checkedPage.page).map(res => res._id);
}
private deletePagesFromArray(ids: string[]): void {
for (let id of ids) {
let i = this.pages.findIndex(_ => _._id == id);
this.pages.splice(i, 1);
}
this.applyFilters();
}
public confirmDeletePage(id: string) {
//this.deleteConfirmationModal.ids = [id];
//this.deleteConfirmationModal.showModal();
this.selectedPages = [id];
this.confirmModalOpen();
}
public confirmDeleteSelectedPages() {
//this.deleteConfirmationModal.ids = this.getSelectedPages();
//this.deleteConfirmationModal.showModal();
this.selectedPages = this.getSelectedPages();
this.confirmModalOpen();
}
private confirmModalOpen() {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
this.deleteModal.cancelButton = true;
this.deleteModal.okButton = true;
this.deleteModal.alertTitle = 'Delete Confirmation';
this.deleteModal.message = 'Are you sure you want to delete the selected page(s)?';
this.deleteModal.okButtonText = 'Yes';
this.deleteModal.open();
}
}
public confirmedDeletePages(data: any) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
this.showLoading = true;
this.updateErrorMessage = '';
this.subscriptions.push(this._helpContentService.deletePages(this.selectedPages, this.properties.adminToolsAPIURL).subscribe(
_ => {
this.deletePagesFromArray(this.selectedPages);
UIkit.notification('Pages have been <b>successfully deleted</b>', {
status: 'success',
timeout: 6000,
pos: 'bottom-right'
});
this.showLoading = false;
},
error => this.handleUpdateError('System error deleting the selected pages', error)
));
}
}
public editPage(i: number) {
this.entitiesCtrl = this._fb.array([]);
let page: Page = this.checkboxes[i].page;
this.index = this.pages.findIndex(value => value._id === page._id);
this.pageForm = this._fb.group({
_id: this._fb.control(page._id),
route: this._fb.control(page.route, Validators.required),
name: this._fb.control(page.name, Validators.required),
isEnabled: this._fb.control(page.isEnabled),
portalType: this._fb.control(page.portalType, Validators.required),
top: this._fb.control(page.top),
bottom: this._fb.control(page.bottom),
left: this._fb.control(page.left),
right: this._fb.control(page.right),
type: this._fb.control(page.type, Validators.required),
entities: this.entitiesCtrl
});
this.pageForm.get('portalType').disable();
for (let i = 0; i < page.entities.length; i++) {
this.entitiesCtrl.push(this._fb.control(page.entities[i]));
}
this.modalErrorMessage = '';
this.pagesModalOpen('Edit Page', 'Save changes');
}
public newPage() {
if(this.pageForm) {
this.pageForm.get('portalType').enable();
}
this.entitiesCtrl = this._fb.array([]);
this.pageForm = this._fb.group({
_id: this._fb.control(null),
route: this._fb.control('', Validators.required),
name: this._fb.control('', Validators.required),
isEnabled: this._fb.control(true),
portalType: this._fb.control('', Validators.required),
top: this._fb.control(true),
bottom: this._fb.control(true),
left: this._fb.control(true),
right: this._fb.control(true),
type: this._fb.control(this.typeOptions[0].value, Validators.required),
entities: this.entitiesCtrl,
});
this.modalErrorMessage = '';
this.pagesModalOpen('Create Page', 'Create');
}
private pagesModalOpen(title: string, yesBtn: string) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
this.editModal.cancelButton = true;
this.editModal.okButton = true;
this.editModal.okButtonLeft = false;
this.editModal.alertTitle = title;
this.editModal.okButtonText = yesBtn;
this.editModal.open();
}
}
public pageSaveConfirmed(data: any) {
this.showLoading = true;
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
if (!this.pageForm.value._id) {
this.modalErrorMessage = '';
this.subscriptions.push(this._helpContentService.savePage(<Page>this.pageForm.value, this.properties.adminToolsAPIURL).subscribe(
page => {
this.pageSavedSuccessfully(page, true);
UIkit.notification('Page <b>' + page.name + '</b> has been <b>successfully created</b>', {
status: 'success',
timeout: 6000,
pos: 'bottom-right'
});
},
error => this.handleUpdateError('System error creating page', error)
));
} else {
this.pageForm.get('portalType').enable();
this.subscriptions.push(this._helpContentService.updatePage(<Page>this.pageForm.value, this.properties.adminToolsAPIURL).subscribe(
page => {
this.pageSavedSuccessfully(page, false);
UIkit.notification('Page <b>' + page.name + '</b> has been <b>successfully updated</b>', {
status: 'success',
timeout: 6000,
pos: 'bottom-right'
});
},
error => this.handleUpdateError('System error updating page', error)
));
}
}
}
public pageSavedSuccessfully(page: Page, isNew: boolean) {
if (isNew) {
this.pages.push(page);
} else {
this.pages[this.index] = page;
}
this.applyFilters();
this.applyCheck(false);
this.showLoading = false;
}
public applyFilters() {
this.checkboxes = [];
this.pages.filter(item => this.filterByType(item)).forEach(
_ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
);
this.checkboxes = this.checkboxes.filter(item => this.filterPages(item.page));
}
public filterByType(page: Page): boolean {
let type = this.filterForm.get("type").value;
return type == "all" || (type == page.type);
}
public filterPages(page: Page): boolean {
let textFlag = this.searchText.toString() == '' || (page.route + ' ' + page.name + ' ' + page.portalType).match(this.searchText) != null;
return textFlag;
}
handleError(message: string, error) {
// if(error == null) {
// this.formComponent.reset();
// } else {
this.errorMessage = message;// + ' (Server responded: ' + error + ')';
console.log('Server responded: ' + error);
//}
this.showLoading = false;
}
handleUpdateError(message: string, error) {
if (error == null) {
// this.formComponent.reset();
this.pageForm = this._fb.group({
route: this._fb.control('', Validators.required),
name: this._fb.control('', Validators.required),
isEnabled: this._fb.control(true),
portalType: this._fb.control('', Validators.required),
top: this._fb.control(true),
bottom: this._fb.control(true),
left: this._fb.control(true),
right: this._fb.control(true),
type: this._fb.control(this.typeOptions[0].value, Validators.required),
entities: this.entitiesCtrl,
_id: this._fb.control(''),
});
} else {
this.updateErrorMessage = message;// + ' (Server responded: ' + error + ')';
console.log('Server responded: ' + error);
}
UIkit.notification('An error has occurred. Please try again later', {
status: 'danger',
timeout: 6000,
pos: 'bottom-right'
});
this.showLoading = false;
}
public getEntitiesAsString(page: Page): string {
if(page.entities) {
return (<any[]> page.entities).map((page: Entity) => page.name).join(',');
}
return '';
}
// public filterByPortal(event: any) {
// this.portal = event.target.value;
// this.applyPortalFilter(this.portal);
// }
public applyPortalFilter(portal: string) {
this.getPages(portal);
}
public togglePages(status: boolean, ids: string[]) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
this.updateErrorMessage = '';
this.subscriptions.push(this._helpContentService.togglePages(this.portal, ids, status, this.properties.adminToolsAPIURL).subscribe(
() => {
for (let id of ids) {
let i = this.checkboxes.findIndex(_ => _.page._id == id);
this.checkboxes[i].page.isEnabled = status;
}
this.applyCheck(false);
},
error => this.handleUpdateError('System error changing the status of the selected page(s)', error)
));
}
}
public capitalizeFirstLetter(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
public onSearchClose() {
this.selectedKeyword = this.filterForm.get('keyword').value;
}
public reset() {
this.selectedKeyword = null;
this.searchInputComponent.reset()
}
}