openaire-library/dashboard/divId/divIds.component.ts

367 lines
11 KiB
TypeScript
Raw Normal View History

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 {CheckDivId, DivId} from "../../utils/entities/adminTool/divId";
import {Page} from "../../utils/entities/adminTool/page";
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 {Observable, Subscriber} from "rxjs";
import {map, startWith} from "rxjs/operators";
import {MatAutocompleteSelectedEvent, MatChipInputEvent} from "@angular/material";
@Component({
selector: 'divIds',
templateUrl: './divIds.component.html',
})
export class DivIdsComponent implements OnInit {
@ViewChild('AlertModalSaveDivId') alertModalSaveDivId;
@ViewChild('AlertModalDeleteDivIds') alertModalDeleteDivIds;
private selectedDivIds: string[] = [];
public checkboxes: CheckDivId[] = [];
public divIds: DivId[] = [];
public myForm: FormGroup;
public pageSearchCtrl: FormControl;
public pagesCtrl: FormArray;
private searchText: RegExp = new RegExp('');
public keyword: string = "";
public properties: EnvProperties = null;
public formPages: Page[] = [];
public showLoading: boolean = true;
public errorMessage: string = '';
public updateErrorMessage: string = '';
public modalErrorMessage: string = '';
public filterForm: FormControl;
private subscriptions: any[] = [];
public allPages: Page[] = [];
filteredPages: Observable<Page[]>;
@ViewChild('PageInput') pageInput: ElementRef<HTMLInputElement>;
selectedPages: Page[] = [];
selectedCommunityPid = null;
ngOnInit() {
this.filterForm = this._fb.control('');
this.pageSearchCtrl = this._fb.control('');
this.subscriptions.push(this.filterForm.valueChanges.subscribe(value => {
this.filterBySearch(value);
}));
this.pagesCtrl = this._fb.array([]);
this.myForm = this._fb.group({
_id: '',
name: ['', Validators.required],
pages: this.pagesCtrl,
portalType: ['', Validators.required]
});
this.route.data
.subscribe((data: { envSpecific: EnvProperties }) => {
HelperFunctions.scroll();
this.properties = data.envSpecific;
this.getDivIds();
this.route.queryParams.subscribe(params => {
this.selectedCommunityPid = params['communityId'];
this.getPages();
});
});
}
constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router, private _helpContentService: HelpContentService, private _fb: FormBuilder) {
}
ngOnDestroy(): void {
this.subscriptions.forEach(value => {
if (value instanceof Subscriber) {
value.unsubscribe();
} else if (value instanceof Function) {
value();
}
});
}
getDivIds() {
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._helpContentService.getDivIdsFull(null, this.properties.adminToolsAPIURL).subscribe(
divIds => {
this.divIds = divIds;
this.checkboxes = [];
let self = this;
divIds.forEach(_ => {
self.checkboxes.push(<CheckDivId>{divId: _, checked: false});
});
this.showLoading = false;
},
error => this.handleError('System error retrieving classes', error));
}
}
// public showModal():void {
// this.modal.showModal();
// }
public toggleCheckBoxes(event) {
this.checkboxes.forEach(_ => _.checked = event.target.checked);
}
public applyCheck(flag: boolean) {
this.checkboxes.forEach(_ => _.checked = flag);
}
public getSelectedDivIds(): string[] {
return this.checkboxes.filter(divId => divId.checked == true).map(checkedDivId => checkedDivId.divId).map(res => res._id);
}
private deleteDivIdsFromArray(ids: string[]): void {
for (let id of ids) {
let i = this.checkboxes.findIndex(_ => _.divId._id == id);
this.checkboxes.splice(i, 1);
}
}
public confirmDeleteDivId(id: string) {
this.selectedDivIds = [id];
this.confirmModalOpen();
}
public confirmDeleteSelectedDivIds() {
this.selectedDivIds = this.getSelectedDivIds();
this.confirmModalOpen();
}
private confirmModalOpen() {
if (!Session.isLoggedIn()) {
this._router.navigate(['/user-info'], {
queryParams: {
"errorCode": LoginErrorCodes.NOT_VALID,
"redirectUrl": this._router.url
}
});
} else {
this.alertModalDeleteDivIds.cancelButton = true;
this.alertModalDeleteDivIds.okButton = true;
this.alertModalDeleteDivIds.alertTitle = "Delete Confirmation";
this.alertModalDeleteDivIds.message = "Are you sure you want to delete the selected class(es)?";
this.alertModalDeleteDivIds.okButtonText = "Yes";
this.alertModalDeleteDivIds.open();
}
}
public confirmedDeleteDivIds(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._helpContentService.deleteDivIds(this.selectedDivIds, this.properties.adminToolsAPIURL).subscribe(
_ => {
this.deleteDivIdsFromArray(this.selectedDivIds);
this.showLoading = false;
},
error => this.handleUpdateError('System error deleting the selected classes', error)
);
}
}
public editDivId(i: number) {
let divId: DivId = this.checkboxes[i].divId;
this.formPages = <Page[]>divId.pages;
this.pagesCtrl = this._fb.array([]);
this.myForm = this._fb.group({
_id: divId._id,
name: [divId.name,Validators.required],
pages: this.pagesCtrl,
portalType: [divId.portalType, Validators.required]
});
this.myForm.controls['portalType'].disable();
for(let i = 0; i < divId.pages.length; i++) {
this.pagesCtrl.push(this._fb.control(divId.pages[i]));
}
this.filteredPages = this.pageSearchCtrl.valueChanges.pipe(startWith(''),
map(page => this._filter(page)));
this.selectedPages = JSON.parse(JSON.stringify(divId.pages));
this.divIdsModalOpen(this.alertModalSaveDivId, "", "Save Changes");
}
public newDivId() {
this.myForm.controls['portalType'].enable();
this.pagesCtrl = this._fb.array([]);
this.myForm = this._fb.group({
_id: '',
name: ['', Validators.required],
pages: this.pagesCtrl,
//openaire: this._fb.control(true),
portalType: ['', Validators.required]
});
this.filteredPages = this.pageSearchCtrl.valueChanges.pipe(startWith(''),
map(page => this._filter(page)));
this.modalErrorMessage = "";
this.selectedPages = [];
this.divIdsModalOpen(this.alertModalSaveDivId, "", "Save");
}
private divIdsModalOpen(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 divIdSaveConfirmed(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._helpContentService.saveDivId(<DivId>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
divId => {
this.divIdSavedSuccessfully(divId);
},
error => this.handleUpdateError("System error creating class", error)
);
} else {
this._helpContentService.updateDivId(<DivId>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
divId => {
this.divIdUpdatedSuccessfully(divId);
},
error => this.handleUpdateError("System error updating class", error)
);
}
}
}
public divIdSavedSuccessfully(divId: DivId) {
this.checkboxes.push(<CheckDivId>{divId: divId, checked: false});
this.applyCheck(false);
}
public divIdUpdatedSuccessfully(divId: DivId) {
this.checkboxes.find(checkItem => checkItem.divId._id == divId._id).divId = divId;
this.applyCheck(false);
}
public filterBySearch(text: string) {
this.searchText = new RegExp(text, 'i');
this.applyFilter();
}
public applyFilter() {
this.checkboxes = [];
this.divIds.filter(item => this.filterDivIds(item)).forEach(
_ => this.checkboxes.push(<CheckDivId>{divId: _, checked: false})
);
}
public filterDivIds(divId: DivId): boolean {
let textFlag = this.searchText.toString() == '' || (divId.name + ' ' + divId.portalType).match(this.searchText) != null;
return textFlag;
}
handleUpdateError(message: string, error) {
if (error == null) {
// this.formComponent.reset();
} else {
this.updateErrorMessage = message;
console.log('Server responded: ' + error);
}
this.showLoading = false;
}
handleError(message: string, error) {
this.errorMessage = message;
console.log('Server responded: ' + error);
this.showLoading = false;
}
getPages() {
this.showLoading = true;
this.errorMessage = "";
this._helpContentService.getPages(this.properties.adminToolsAPIURL, this.selectedCommunityPid).subscribe(
pages => {
this.allPages = pages;
this.showLoading = false;
},
error => this.handleError('System error retrieving pages', error)
);
}
remove(page): void {
let index = this.selectedPages.indexOf(page);
if (index >= 0) {
this.selectedPages.splice(index, 1);
this.pagesCtrl.value.splice(index, 1);
this.pagesCtrl.markAsDirty();
}
}
selected(event: MatAutocompleteSelectedEvent): void {
let newPage = event.option.value;
if (this.selectedPages.indexOf(newPage) == -1) {
this.selectedPages.push(event.option.value);
this.pagesCtrl.push(this._fb.control(newPage));
this.pagesCtrl.markAsDirty();
}
this.pageInput.nativeElement.value = '';
this.pageSearchCtrl.setValue('');
}
private _filter(value: string): Page[] {
if (!value || value.length == 0) {
return this.allPages.slice();
}
const filterValue = value.toString().toLowerCase();
return this.allPages.filter(page => page.name.toLowerCase().indexOf(filterValue) != -1);
}
}