connect-admin/src/app/pages/subjects/subjects-edit-form/subjects-edit-form.componen...

498 lines
16 KiB
TypeScript

import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {UntypedFormArray, UntypedFormBuilder, UntypedFormControl} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {CommunityService} from '../../../openaireLibrary/connect/community/community.service';
import {SubjectsService} from '../subjects.service';
import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
import {Title} from '@angular/platform-browser';
import {properties} from '../../../../environments/environment';
import {AlertModal} from '../../../openaireLibrary/utils/modal/alert';
import {SearchInputComponent} from '../../../openaireLibrary/sharedComponents/search-input/search-input.component';
import {forkJoin, Subscription} from 'rxjs';
import {CommunityInfo} from '../../../openaireLibrary/connect/community/communityInfo';
import {FullScreenModalComponent} from 'src/app/openaireLibrary/utils/modal/full-screen-modal/full-screen-modal.component';
import {HelperFunctions} from 'src/app/openaireLibrary/utils/HelperFunctions.class';
import {NotificationHandler} from "../../../openaireLibrary/utils/notification-handler";
import {ClearCacheService} from "../../../openaireLibrary/services/clear-cache.service";
import {SdgSelectionComponent} from '../../../openaireLibrary/sdg/sdg-selection/sdg-selection.component';
import {FosSelectionComponent} from '../../../openaireLibrary/fos/fos-selection/fos-selection.component';
declare var UIkit: any;
@Component({
selector: 'subjects-edit-form',
templateUrl: './subjects-edit-form.component.html',
})
export class SubjectsEditFormComponent implements OnInit {
subjectsForm = new UntypedFormArray([]);
groupedAllSubjects = [];
groupedSubjects = [];
groupedSdg = [];
groupedFos = [];
subjectsColumns = [];
index: number = 0;
subjectsLimit: number = 6;
public maxCharacters: number = 25;
displayedAllSubjects = [];
displayedSubjects = [];
displayedSdg = [];
displayedFos = [];
hasChanges: boolean = false;
myForm = new UntypedFormArray([]);
public showLoading = true;
public res = [];
params: any;
public communityId: string = null;
public community: CommunityInfo = null;
public properties: EnvProperties = properties;
public edit = null;
public originalSubjects = [];
@ViewChild('editModal') editModal: AlertModal;
@ViewChild('deleteModal') deleteModal: AlertModal;
@ViewChild('fsModal', {static: true}) fullscreen: FullScreenModalComponent;
@ViewChild('modalTabs') modalTabs: ElementRef;
page = 1;
size = 10;
selectedSubjects = [];
isEditModal: boolean = false;
public selectedKeyword: string;
@ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
public filterForm: UntypedFormControl;
private subscriptions: any[] = [];
@ViewChild('sdgSelection') sdgSelection: SdgSelectionComponent;
@ViewChild('fosSelection') fosSelection: FosSelectionComponent;
/*//Check again functionality to enable page
subjectsPage;
@ViewChild('enablePageModal') enablePageModal: AlertModal;*/
onEnter: () => void = () => {
this.addSubjectsIntoList();
}
constructor(private element: ElementRef,
private route: ActivatedRoute,
private _router: Router,
public _fb: UntypedFormBuilder,
private title: Title,
// private _helpContentService: HelpContentService,
private _communityService: CommunityService,
private _subjectsService: SubjectsService,
private _clearCacheService: ClearCacheService
) {
}
ngOnInit() {
this.filterForm = this._fb.control('');
this.subscriptions.push(this.filterForm.valueChanges.subscribe(value => {
this.community.subjects = this.originalSubjects.filter(subject => {
return !value || subject.toLowerCase().indexOf(value.toLowerCase()) != -1
});
}));
this.subscriptions.push(this.route.params.subscribe(
params => {
this.communityId = params['community'];
this.title.setTitle(this.communityId.toUpperCase() + ' | Subjects');
this.showLoading = true;
this.subscriptions.push(this._communityService.getCommunityAsObservable().subscribe(
community => {
this.community = community;
this.params = {
community: encodeURIComponent(
'"' + community.queryId + '"')
};
this.community.subjects.sort((n1,n2)=> {
if (n1.toLowerCase() > n2.toLowerCase()) {
return 1;
}
if (n1.toLowerCase() < n2.toLowerCase()) {
return -1;
}
return 0;
});
// assigning values
this.displayedSubjects = HelperFunctions.copy(this.community.subjects);
this.displayedSdg = this.community.sdg;
this.displayedFos = this.community.fos;
this.displayedAllSubjects = [...this.displayedSubjects, ...this.displayedSdg, ...this.displayedFos];
// grouping eveything for 'All' view
this.groupSubjects(this.displayedAllSubjects, 'all');
this.originalSubjects = [];
for (let i = 0; i < this.community.subjects.length; i++) {
this.originalSubjects.push(this.community.subjects[i]);
}
if (this.community.subjects.length === 0) {
this.community.subjects.push('');
}
this.showLoading = false;
},
error => this.handleUpdateError('System error retrieving community profile', error)
));
}));
}
ngOnDestroy() {
this.subscriptions.forEach(subscription => {
if (subscription instanceof Subscription) {
subscription.unsubscribe();
}
});
}
public groupSubjects(subjects: string[], type: string) {
if(subjects.length === 0) {
return [];
}
subjects.sort((a, b) => a.localeCompare(b));
if(type === 'all') {
this.groupedAllSubjects = Object.values(
subjects.reduce((acc, subject) => {
let firstLetter = subject[0].toLocaleUpperCase();
if(!acc[firstLetter]) {
acc[firstLetter] = {group: firstLetter, data: [subject]};
} else {
acc[firstLetter].data.push(subject);
}
return acc;
},{})
)
if(subjects.length > 1) {
this.groupedAllSubjects.unshift({group: 'All', data: subjects});
}
}
if(type === 'freeText') {
this.groupedSubjects = Object.values(
subjects.reduce((acc, subject) => {
let firstLetter = subject[0].toLocaleUpperCase();
if(!acc[firstLetter]) {
acc[firstLetter] = {group: firstLetter, data: [subject]};
} else {
acc[firstLetter].data.push(subject);
}
return acc;
},{})
)
if(subjects.length > 1) {
this.groupedSubjects.unshift({group: 'All', data: subjects});
}
}
if(type === 'sdg') {
this.groupedSdg = Object.values(
subjects.reduce((acc, subject) => {
let firstLetter = subject[0].toLocaleUpperCase();
if(!acc[firstLetter]) {
acc[firstLetter] = {group: firstLetter, data: [subject]};
} else {
acc[firstLetter].data.push(subject);
}
return acc;
},{})
)
if(subjects.length > 1) {
this.groupedSdg.unshift({group: 'All', data: subjects});
}
}
if(type === 'fos') {
this.groupedFos = Object.values(
subjects.reduce((acc, subject) => {
let key = subject.substring(0,2).toLocaleUpperCase();
if(!acc[key]) {
acc[key] = {group: key, data: [subject]};
} else {
acc[key].data.push(subject);
}
return acc;
},{})
)
if(subjects.length > 1) {
this.groupedFos.unshift({group: 'All', data: subjects});
}
}
}
public changeDisplayedSubjects(i, group) {
this.subjectsColumns = [];
this.index = i;
if(group.data.length > this.subjectsLimit && group.group != 'All') {
this.divideSubjects(group);
}
}
public divideSubjects(group) {
let columns = [];
for(let i = 0; i < (group.data.length / this.subjectsLimit); i++) {
columns.push(group.data.slice(i * this.subjectsLimit, ((i + 1) * this.subjectsLimit)));
}
this.subjectsColumns = columns;
}
private removeModalOpen(subject: string, i: any) {
this.selectedSubjects = [subject];
this.reset(['']);
this.deleteModal.cancelButton = true;
this.deleteModal.okButton = true;
this.deleteModal.alertTitle = 'Delete Subject';
this.deleteModal.message = 'Are you sure you want to delete this subject?';
this.deleteModal.okButtonText = 'Yes';
this.deleteModal.cancelButtonText = 'No';
this.deleteModal.open();
}
public getSubjectsExistOnlyInFirst(firstArray: string[], secondArray: string[]): string[] {
const difference = [];
for (let i = 0; i < firstArray.length; i++) {
if (secondArray.indexOf(firstArray[i]) === -1) {
difference.push(firstArray[i]);
}
}
return difference;
}
public editAllSubjects() {
UIkit.tab(this.modalTabs.nativeElement).show(0);
this.displayedSubjects = HelperFunctions.copy(this.community.subjects);
this.sdgSelection.reset();
this.sdgSelection.sdgs.markAsPristine();
this.fosSelection.reset();
this.fosSelection.fosOptions.markAsPristine();
this.fullscreen.title = "Add/Edit Subjects";
this.fullscreen.okButtonText = "Save";
this.fullscreen.back = true;
this.fullscreen.okButton = true;
this.fullscreen.open();
}
public addSubjectsIntoList() {
const subjectsFromUserInput = this.subjectsForm.getRawValue();
subjectsFromUserInput.forEach(element => {
this.displayedSubjects.unshift(element);
});
this.subjectsForm.clear();
this.hasChanges = true;
}
public removeSubjectFromList(i) {
this.displayedSubjects.splice(i, 1);
this.hasChanges = true;
}
public saveAllSubjects() {
let selectedSdg = this.sdgSelection.getSelectedSubjects().map(a => a.id);
let selectedFos = this.fosSelection.getSelectedSubjects().map(a => a.id);
let requests = [
...this.saveSubjects(this.community.subjects, this.displayedSubjects, 'subjects'),
...this.saveSubjects(this.community.sdg, selectedSdg, 'sdg'),
...this.saveSubjects(this.community.fos, selectedFos, 'fos')
];
this.subscriptions.push(forkJoin(requests).subscribe(res => {
this.afterUpdateActions(res, "updated");
}));
}
public saveSubjects(subjects, displayedSubjects, type: string) {
if (this.communityId != null && this.communityId !== '') {
this.showLoading = true;
const subjectsToDeleteAr = this.getSubjectsExistOnlyInFirst(subjects, displayedSubjects);
const subjectsToAddAr = this.getSubjectsExistOnlyInFirst(displayedSubjects, subjects);
const subjectsToDelete = this.getNonEmptyItems(subjectsToDeleteAr);
const subjectsToAdd = this.getNonEmptyItems(subjectsToAddAr);
let requests = [];
if (subjectsToDelete.length > 0) {
requests.push(this._subjectsService.removeSubjects(
this.properties.communityAPI + this.communityId + '/' + type, subjectsToDelete))
}
if (subjectsToAdd.length > 0) {
requests.push(this._subjectsService.addSubjects(
this.properties.communityAPI + this.communityId + '/' + type, subjectsToAdd))
}
return requests;
}
}
handleUpdateError(message: string, error = null) {
if(error) {
console.error(error)
}
NotificationHandler.rise(message, 'danger');
this.showLoading = false;
}
afterUpdateActions(response, message: string) {
response.forEach(res => {
if (res.subjects) {
this.community.subjects = res.subjects;
} else if (res.sdg) {
this.community.sdg = res.sdg;
} else if (res.fos) {
this.community.fos = res.fos;
}
});
this._communityService.updateSubjects(this.community.subjects, this.community.fos, this.community.sdg);
// this.originalSubjects = [];
// for (let i = 0; i < this.community.subjects.length; i++) {
// this.originalSubjects.push(this.community.subjects[i]);
// }
// this.originalSubjects.sort((n1,n2)=> {
// if (n1.toLowerCase() > n2.toLowerCase()) {
// return 1;
// }
// if (n1.toLowerCase() < n2.toLowerCase()) {
// return -1;
// }
// return 0;
// });
// this.community.subjects = this.originalSubjects.filter(subject => {
// return !this.filterForm.value || subject.toLowerCase().indexOf(this.filterForm.value.toLowerCase()) != -1
// }).sort();
// this._clearCacheService.purgeBrowserCache("Subjects "+message, this.communityId);
NotificationHandler.rise('Subjects successfully ' + message + '!')
this.showLoading = false;
}
private getNonEmptyItems(data: string[]): string[] {
const length = data.length;
const arrayNonEmpty = new Array<string>();
let j = 0;
for (let i = 0; i < length; i++) {
if (this.isEmpty(data[i])) {
} else if (this.isNonEmpty(data[i])) {
arrayNonEmpty[j] = data[i];
j++;
}
}
return arrayNonEmpty;
}
private isEmpty(data: string): boolean {
if (data !== undefined && !data.replace(/\s/g, '').length) {
return true;
} else {
return false;
}
}
private isNonEmpty(data: string): boolean {
if (data !== undefined && data != null) {
return true;
} else {
return false;
}
}
public addSubjectInForm() {
this.myForm.push(new UntypedFormControl(''));
}
public removeSubjectInForm(i: number) {
this.myForm.removeAt(i);
}
public reset(subjects: string[]) {
this.myForm = new UntypedFormArray([]);
for (let subject in subjects) {
this.myForm.push(new UntypedFormControl(''));
}
this.myForm.patchValue(subjects);
}
newSubject() {
this.isEditModal = false;
this.selectedSubjects = [];
this.reset([]);
this.fullscreen.title = "Add/Edit Subjects";
this.fullscreen.okButtonText = "Save";
this.fullscreen.back = true;
this.fullscreen.okButton = true;
this.fullscreen.open();
}
get currentPage() {
if(this.community.subjects) {
return this.community.subjects.slice((this.page - 1) * this.size, this.page * this.size);
} else {
return [];
}
}
public updatePage(event) {
this.page = event.value;
HelperFunctions.scroll();
}
public editSubject(subject: string) {
this.isEditModal = true;
this.selectedSubjects = [subject];
this.reset([subject]);
this.fullscreen.title = "Edit Subject";
this.fullscreen.okButtonText = "Save";
this.fullscreen.back = true;
this.fullscreen.okButton = true;
this.fullscreen.open();
}
private formModalOpen(title: string, yesBtn: string) {
this.editModal.okButtonLeft = false;
this.editModal.cancelButton = true;
this.editModal.okButton = true;
this.editModal.alertTitle = title;
this.editModal.okButtonText = yesBtn;
this.editModal.open();
}
public onSearchClose() {
this.selectedKeyword = this.filterForm.value;
}
public resetInput() {
this.selectedKeyword = null;
this.searchInputComponent.reset()
}
/*
//Check again functionality to enable page
private getSubjectsPageStatus() {
this._helpContentService.getCommunityPagesByRoute(this.communityId, '/subjects', this.properties.adminToolsAPIURL).subscribe((page) => {
this.subjectsPage = page;
});
}
public get subjectsEnabled(): boolean {
return !this.subjectsPage || this.subjectsPage.isEnabled;
}
enablePage() {
this._helpContentService.togglePages(this.communityId, [this.subjectsPage._id], true, this.properties.adminToolsAPIURL).subscribe(() => {
this.subjectsPage.isEnabled = true;
UIkit.notification('Curators Page has been <b>enabled successfully</b>', {
status: 'success',
timeout: 6000,
pos: 'bottom-right'
});
},error => {
this.subjectsPage.isEnabled = false;
UIkit.notification('An error occured', {
status: 'danger',
timeout: 6000,
pos: 'bottom-right'
});
});
}
private curatorsEnabledOpen() {
this.enablePageModal.okButtonLeft = false;
this.enablePageModal.alertTitle = 'Enable Subjects Page';
this.enablePageModal.okButtonText = 'Yes';
this.enablePageModal.cancelButtonText = 'No';
this.enablePageModal.open();
}*/
}