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

455 lines
16 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 {Option} from '../../sharedComponents/input/input.component';
import {AlertModal} from '../../utils/modal/alert';
import {SearchInputComponent} from '../../sharedComponents/search-input/search-input.component';
import {Title} from '@angular/platform-browser';
import {StringUtils} from '../../utils/string-utils.class';
import {StakeholderService} from '../../monitor/services/stakeholder.service';
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 name: string;
public logo: string;
public pagesType: string;
public properties: EnvProperties = properties;
public showLoading: boolean = true;
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;
allEntities: Option[] = [];
private subscriptions: any[] = [];
public portalUtils: PortalUtils = new PortalUtils();
private index: number;
pageHelpContentsCount = {};
pageClassContentsCount = {};
public stickyPageHeader: boolean = false;
constructor(private element: ElementRef, private route: ActivatedRoute,
private title: Title,
private _router: Router, private _helpContentService: HelpContentService,
private userManagementService: UserManagementService, private _fb: FormBuilder,
private stakeholderService: StakeholderService) {
}
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.route.snapshot.data.portal) {
this.title.setTitle(StringUtils.capitalize(this.portal) + ' | Pages');
} else if (this.route.snapshot.params[this.route.snapshot.data.param]) {
if(this.route.snapshot.data.param === 'stakeholder') {
this.subscriptions.push(this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
if(stakeholder) {
this.name = stakeholder.name;
this.logo = stakeholder.logoUrl;
this.title.setTitle(stakeholder.name + ' | Pages');
}
}));
} else {
// TODO: for portals as well
this.title.setTitle(this.portal.toUpperCase() + ' | Pages');
}
} else {
this.title.setTitle('Administrator Dashboard | Pages');
}
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)));
if (this.portal) {
this.getPageHelpContentsCounts(this.portal);
}
}
ngOnDestroy(): void {
this.subscriptions.forEach(value => {
if (value instanceof Subscriber) {
value.unsubscribe();
} else if (value instanceof Function) {
value();
}
});
}
getPages(portal: string) {
this.showLoading = true;
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) {
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});
});
}
}
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.selectedPages = [id];
this.confirmModalOpen();
}
public confirmDeleteSelectedPages() {
this.selectedPages = this.getSelectedPages();
this.confirmModalOpen();
}
private confirmModalOpen() {
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) {
this.showLoading = true;
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),
portalPid: this._fb.control(page.portalPid),
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.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),
portalPid: this._fb.control(null),
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.pagesModalOpen('Create Page', 'Create');
}
private pagesModalOpen(title: string, yesBtn: string) {
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 (!this.pageForm.value._id) {
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 {
return this.searchText.toString() == '' || (page.route + ' ' + page.name + ' ' + page.portalType).match(this.searchText) != null;
}
handleError(message: string, error) {
UIkit.notification(message, {
status: 'danger',
timeout: 6000,
pos: 'bottom-right'
});
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 {
UIkit.notification(message, {
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 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.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)
));
}
}
selectAll() {
let checked = this.getSelectedPages().length != this.checkboxes.length;
for (let check of this.checkboxes) {
check.checked = checked;
}
}
getPageHelpContentsCounts(community_pid: string) {
this.subscriptions.push(this._helpContentService.countCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL, false).subscribe(
pageHelpContentsCount => {
this.pageHelpContentsCount = pageHelpContentsCount;
},
error => this.handleError('System error retrieving page contents', error)));
this.subscriptions.push(this._helpContentService.countCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL, true).subscribe(
pageClassContentsCount => {
this.pageClassContentsCount = pageClassContentsCount;
},
error => this.handleError('System error retrieving page contents', error)));
}
}