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

558 lines
18 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, FormControl, FormGroup, Validators} from '@angular/forms';
import {CheckPage, Page} from '../../utils/entities/adminTool/page';
import {Portal} from '../../utils/entities/adminTool/portal';
import {CheckEntity, 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 {HelperFunctions} from '../../utils/HelperFunctions.class';
import {UserManagementService} from '../../services/user-management.service';
import {Observable, Subscriber} from "rxjs";
import {map, startWith} from "rxjs/operators";
import {MatAutocompleteSelectedEvent} from "@angular/material";
import {PortalUtils} from "../portal/portalHelper";
import {properties} from "../../../../environments/environment";
@Component({
selector: 'pages',
templateUrl: './pages.component.html',
})
export class PagesComponent implements OnInit {
@ViewChild('AlertModalSavePage') alertModalSavePage;
@ViewChild('AlertModalDeletePages') alertModalDeletePages;
private selectedPages: string[] = [];
public checkboxes: CheckPage[] = [];
public pages: Page[] = [];
public pageWithDivIds: string[] = [];
//public errorMessage: string;
public myForm: FormGroup;
private searchText: RegExp = new RegExp('');
public keyword: string = '';
public communities: Portal[] = [];
public selectedCommunityPid: string;
public pagesType: string;
public properties: EnvProperties = null;
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>;
public entitiesSearchCtrl: FormControl;
filteredEntities: Observable<Entity[]>;
selectedEntities: Entity[] = [];
allEntities: Entity[] = [];
private subscriptions: any[] = [];
public portalUtils:PortalUtils = new PortalUtils();
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.filterBySearch(value);
}));
this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => {
this.applyTypeFilter();
}));
this.entitiesSearchCtrl = this._fb.control('');
this.myForm = this._fb.group({
route: ['', Validators.required],
name: ['', Validators.required],
isEnabled: true,
portalType: ['', Validators.required],
top: true,
bottom: true,
left: true,
right: true,
type: ['', Validators.required],
entities: this.entitiesCtrl,
_id: '',
});
this.properties = properties;
this.subscriptions.push(this.route.queryParams.subscribe(params => {
HelperFunctions.scroll();
this.pagesType = '';
if (params['type']) {
// this.pagesType = params['type'];
this.filterForm.get('type').setValue(params['type']);
}
this.selectedCommunityPid = params['communityId'];
this.keyword = '';
this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
this.applyCommunityFilter(this.selectedCommunityPid);
this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.selectedCommunityPid;
}));
//this.getCommunities();
}));
this.subscriptions.push(this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
entities => {
this.allEntities = entities;
this.showLoading = false;
},
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(community_pid: 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 (community_pid) {
this.subscriptions.push(this._helpContentService.getCommunityPagesByType(community_pid, parameters, this.properties.adminToolsAPIURL).subscribe(
pages => {
this.pagesReturned(pages);
//if(!this.pagesType || this.pagesType == "link") {
this.getPagesWithDivIds(community_pid);
//} 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(community_pid: 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(community_pid, 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});
});
}
}
/*
getCommunities() {
this._helpContentService.getCommunities(this.properties.adminToolsAPIURL).subscribe(
communities => {
this.communities = communities;
this.selectedCommunityPid = this.communities[0].pid;
this.getPages(this.selectedCommunityPid);
this.getPagesWithDivIds(this.selectedCommunityPid);
},
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.checkboxes.findIndex(_ => _.page._id == id);
this.checkboxes.splice(i, 1);
}
}
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.alertModalDeletePages.cancelButton = true;
this.alertModalDeletePages.okButton = true;
this.alertModalDeletePages.alertTitle = 'Delete Confirmation';
this.alertModalDeletePages.message = 'Are you sure you want to delete the selected page(s)?';
this.alertModalDeletePages.okButtonText = 'Yes';
this.alertModalDeletePages.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);
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.myForm = this._fb.group({
route: [page.route, Validators.required],
name: [page.name, Validators.required],
isEnabled: page.isEnabled,
portalType: ['', Validators.required],
top: page.top,
bottom: page.bottom,
left: page.left,
right: page.right,
type: [page.type, Validators.required],
entities: this.entitiesCtrl,
_id: page._id,
});
this.myForm.controls['portalType'].disable();
for (let i = 0; i < page.entities.length; i++) {
this.entitiesCtrl.push(this._fb.control(page.entities[i]));
}
this.filteredEntities = this.entitiesSearchCtrl.valueChanges.pipe(startWith(''),
map(page => this._filter(page)));
this.selectedEntities = JSON.parse(JSON.stringify(page.entities));
this.modalErrorMessage = '';
this.pagesModalOpen(this.alertModalSavePage, '', 'Save changes');
}
private _filter(value: string): Entity[] {
if (!value || value.length == 0) {
return this.allEntities.slice();
}
const filterValue = value.toString().toLowerCase();
return this.allEntities.filter(page => page.name.toLowerCase().indexOf(filterValue) != -1);
}
public newPage() {
this.myForm.controls['portalType'].enable();
this.entitiesCtrl = this._fb.array([]);
this.myForm = this._fb.group({
route: ['', Validators.required],
name: ['', Validators.required],
isEnabled: true,
portalType: ['', Validators.required],
top: true,
bottom: true,
left: true,
right: true,
type: [this.typeOptions[0].value, Validators.required],
entities: this._fb.array([]),
_id: '',
});
this.selectedEntities = [];
this.modalErrorMessage = '';
this.filteredEntities = this.entitiesSearchCtrl.valueChanges.pipe(startWith(''),
map(page => this._filter(page)));
this.pagesModalOpen(this.alertModalSavePage, '', 'Save');
}
private pagesModalOpen(modal: any, title: string, yesBtn: string) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
modal.cancelButton = true;
modal.okButton = true;
modal.alertTitle = title;
modal.okButtonText = yesBtn;
modal.open();
}
}
public pageSaveConfirmed(data: any) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_VALID,
'redirectUrl': this._router.url
}
});
} else {
console.log(this.myForm.value)
if (this.myForm.value['_id'].length == 0) {
this.myForm.controls['portalType'].enable();
this.modalErrorMessage = '';
this.subscriptions.push(this._helpContentService.savePage(<Page>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
page => {
this.pageSavedSuccessfully(page, true);
},
error => this.handleUpdateError('System error creating page', error)
));
} else {
this.subscriptions.push(this._helpContentService.updatePage(<Page>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
page => {
this.pageSavedSuccessfully(page, false);
},
error => this.handleUpdateError('System error updating page', error)
));
}
}
}
/* public pageUpdateConfirmed(data: any) {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
} else {
if (!this.myForm.valid) {
this.pagesModalOpen(this.alertModalSavePage, 'Update', 'Update Page');
this.modalErrorMessage = 'Please fill in all required fields marked with *';
} else {
this._helpContentService.updatePage(<Page>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
page => {
this.pageUpdatedSuccessfully(page);
},
error => this.handleUpdateError('System error updating page', error)
);
}
}
}*/
public pageSavedSuccessfully(page: Page, isNew: boolean) {
if (isNew) {
this.checkboxes.push(<CheckPage>{page: page, checked: false});
} else {
this.checkboxes.find(checkItem => checkItem.page._id == page._id).page = page;
}
this.applyCheck(false);
}
public filterBySearch(text: string) {
this.searchText = new RegExp(text, 'i');
this.applyFilter();
}
public applyFilter() {
this.checkboxes = [];
this.pages.filter(item => this.filterPages(item)).forEach(
_ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
);
}
public applyTypeFilter() {
this.checkboxes = [];
this.pages.filter(item => this.filterByType(item)).forEach(
_ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
);
}
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.myForm = this._fb.group({
route: ['', Validators.required],
name: ['', Validators.required],
isEnabled: true,
portalType: ['', Validators.required],
top: true,
bottom: true,
left: true,
right: true,
type: ['', Validators.required],
entities: this._fb.array([]),
_id: '',
});
} else {
this.updateErrorMessage = message;// + ' (Server responded: ' + error + ')';
console.log('Server responded: ' + error);
}
this.showLoading = false;
}
// public filterByCommunity(event: any) {
// this.selectedCommunityPid = event.target.value;
// this.applyCommunityFilter(this.selectedCommunityPid);
// }
public applyCommunityFilter(community_pid: string) {
this.getPages(community_pid);
}
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.selectedCommunityPid, 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);
}
remove(entity): void {
let index = this.selectedEntities.indexOf(entity);
console.log(entity);
console.log(this.selectedEntities);
console.log(index)
if (index >= 0) {
this.selectedEntities.splice(index, 1);
this.entitiesCtrl.value.splice(index, 1);
this.entitiesCtrl.markAsDirty();
}
}
selected(event: MatAutocompleteSelectedEvent): void {
let newEntity = event.option.value;
if (this.selectedEntities.indexOf(newEntity) == -1) {
this.selectedEntities.push(event.option.value);
this.entitiesCtrl.push(this._fb.control(newEntity));
this.entitiesCtrl.markAsDirty();
}
this.pageInput.nativeElement.value = '';
this.entitiesSearchCtrl.setValue('');
}
}