openaire-library/claims/claimsByToken/claimsByToken.component.ts

572 lines
18 KiB
TypeScript

import {Component, ViewChild, ViewChildren, QueryList, Input, ViewEncapsulation} from '@angular/core';
import {Location} from '@angular/common';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {Title, Meta} from '@angular/platform-browser';
import {DataTableDirective} from 'angular-datatables';
import {Observable, Subject } from 'rxjs';
import{EnvProperties} from '../../utils/properties/env-properties';
import {ErrorCodes} from '../../utils/properties/errorCodes';
import {ErrorMessagesComponent} from '../../utils/errorMessages.component';
import {ClaimsDatatablePipe} from '../../utils/pipes/claimsDatatable.pipe';
import {RouterHelper} from '../../utils/routerHelper.class';
import {ModalSelect} from '../../utils/modal/selectModal.component';
import {ModalLoading} from '../../utils/modal/loading.component';
import {ClaimsByTokenService} from './claimsByToken.service';
import {Session} from '../../login/utils/helper.class';
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
import {properties} from "../../../../environments/environment";
@Component({
selector: 'claims-project-manager',
templateUrl: 'claimsByToken.component.html',
styles: [`
#table1_info, #table1_paginate, #table1_length, #table1_filter,
#table2_info, #table2_paginate, #table2_length, #table2_filter{
display: none;
}
`],
encapsulation: ViewEncapsulation.None // this used in order styles to work
})
export class ClaimsByTokenComponent {
public openaireId: string = "";
public sub: any;
public project: any;
private claims:any = [];
public pending_claims: any = [];
public curated_claims: any = [];
public selectedRight_PendingMode: Set<string>;
public selectedWrong_PendingMode: Set<string>;
public selectedRight_CuratedMode: Set<string>;
public selectedWrong_CuratedMode: Set<string>;
public editable: Set<number>;
public contact_person: string[] = ["Konstantina", "Argiro", "Katerina"];
private errorCodes: ErrorCodes;
private errorMessages: ErrorMessagesComponent;
public pending_status: number;
public curated_status: number;
// when 'valid' show proper claims, when 'invalid' show no matched entry-wanna retry
public accessStatus: string;// = "empty";
public mode: string = "pending";
public showTables: boolean = true;
public rowsOnPage = 5;
public sortOrder = "asc";
public keyword1:string = "";
public keyword2:string = "";
public activePendingPage:any = {page: 1};
public totalPendingResults:any = {count: 0};
public activeCuratedPage:any = {page: 1};
public totalCuratedResults:any = {count: 0};
dtTrigger: Subject<any>[] = [];
private triggered: boolean = false;
dtOptions: DataTables.Settings[] = [];
@ViewChildren(DataTableDirective)
dtElements: QueryList<any>;
//@ViewChild("table1") table1: DataTableDirective;
//@ViewChild("table2") table2: DataTableDirective;
@ViewChild (ModalSelect) selectModal : ModalSelect;
@ViewChild (ModalLoading) loading : ModalLoading ;
properties:EnvProperties = properties;
public routerHelper:RouterHelper = new RouterHelper();
constructor (private route: ActivatedRoute,
private _router: Router,
private claimsByTokenService: ClaimsByTokenService,
private _meta: Meta, private _title: Title) {
this.errorCodes = new ErrorCodes();
this.errorMessages = new ErrorMessagesComponent();
this.pending_status = this.errorCodes.LOADING;
this.curated_status = this.errorCodes.LOADING;
}
ngOnInit() {
this.sub = this.route.queryParams.subscribe(params => {
this.mode = "pending";
this.openaireId = params['openaireId'];
this.selectedRight_PendingMode = new Set<string>();
this.selectedWrong_PendingMode = new Set<string>();
this.selectedRight_CuratedMode = new Set<string>();
this.selectedWrong_CuratedMode = new Set<string>();
this.editable = new Set<number>();
this.validateJWTandToken();
this.updateTitle("Claims For Project Managers");
}
);
this.dtOptions[0] = {
//"paging": false,
//"searching": false,
//"lengthChange": false,
"pageLength": this.rowsOnPage,
"columnDefs": [ {
"type": "date",
"targets": 2
} ],
"order": [[ 2, 'desc' ]]
//"pagingType": 'full_numbers',
/*"language": {
"search": "",
"searchPlaceholder": "Search projects..."
}*/
};
this.dtOptions[1] = {
"pageLength": this.rowsOnPage,
"columnDefs": [ {
"type": "date",
"targets": [2,4]
} ],
"order": [[ 4, 'desc' ]]
};
this.dtTrigger[0] = new Subject<any>();
this.dtTrigger[1] = new Subject<any>();
}
ngAfterViewInit(): void {
$.fn['dataTable'].ext.search.push((settings, data, dataIndex) => {
if(settings.sTableId == 'table1') {
if (this.filterData(data, this.keyword1)) {
return true;
}
return false;
} else if(settings.sTableId == 'table2') {
if (this.filterData(data, this.keyword2)) {
return true;
}
return false;
}
});
}
ngOnDestroy(): void {
$.fn['dataTable'].ext.search.pop();
// Do not forget to unsubscribe the event
this.dtTrigger[0].unsubscribe();
this.dtTrigger[1].unsubscribe();
}
/*
Trigger a table draw in order to get the initial filtering
*/
triggerInitialLoad(){
this.triggered = true;
//console.info("triggerInitialLoad");
setTimeout(function(){
/*var table1 = <any>$('#table1').DataTable();
table1.page( 0 ).draw( false );
var table2 = <any>$('#table2').DataTable();
table2.page( 0 ).draw( false );*/
}, 500);
setTimeout(() => {
this.dtTrigger[0].next();
this.dtTrigger[1].next();
});
}
rerender(): void {
//console.info("RERENDER");
this.dtElements.forEach((dtElement: DataTableDirective, index: number) => {
dtElement.dtInstance.then((dtInstance: any) => {
// Destroy the table first
dtInstance.destroy();
// Call the dtTrigger to rerender again
this.dtTrigger[index].next();
});
});
}
filterData(row: any, query: string) {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
let returnValue: boolean = false;
if(query) {
for(var i=0; i <3; i++){
var r= this.filterQuery(row[i], query);
if(r) {
returnValue = true;
break;
}
}
if(!returnValue) {
return false;
}
}
return true;
}
}
filterQuery(data, query){
if(data.toLowerCase().indexOf(query.toLowerCase()) > -1){
return true;
}else{
return false;
}
}
refreshTable(page:number, whichTable: string) {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
if(whichTable == "pending") {
var table = $('#table1').DataTable();
table.page( page - 1 ).draw( false );
var info = table.page.info();
this.activePendingPage.page = page;//$event.value;
this.totalPendingResults.count = info.recordsDisplay;
} else if(whichTable == 'curated') {
var table = $('#table2').DataTable();
table.page( page - 1 ).draw( false );
var info = table.page.info();
this.activeCuratedPage.page = page;//$event.value;
this.totalCuratedResults.count = info.recordsDisplay;
}
}
//table.mfActivePage=$event.value;
//table.setPage(table.mfActivePage, this.rowsOnPage);
}
validateJWTandToken() {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
if(this.openaireId) {
this.pending_status = this.errorCodes.LOADING;
this.curated_status = this.errorCodes.LOADING;
this.showTables = false;
this.pending_claims = [];
this.curated_claims = [];
this.activePendingPage.page = 1;
this.totalPendingResults.count = 0;
this.activeCuratedPage.page = 1;
this.totalCuratedResults.count = 0;
this.claimsByTokenService.getClaims(this.openaireId, this.properties.claimsAPIURL).subscribe(
data => {
//this.closeLoading();
this.accessStatus = "valid";
this.claims = data.data;
for(let claim of this.claims) {
if(claim.targetType == "project") {
this.project = claim.target;
} else {
this.project = claim.source;
}
if(claim.curatedBy) {
this.curated_claims.push(claim);
} else {
this.pending_claims.push(claim);
}
}
this.totalPendingResults.count = this.pending_claims.length;
this.totalCuratedResults.count = this.curated_claims.length;
if(this.project) {
this.updateTitle("Claims For Project Managers - "+this.project.name);
}
this.showTables = true;
if(!this.triggered) {
//console.info("initial load");
this.triggerInitialLoad();
} else {
//console.info("rerender");
var table1 = $('#table1').DataTable();
table1.clear();
var table2 = $('#table2').DataTable();
table2.clear();
this.rerender();
}
this.pending_status = this.errorCodes.DONE;
this.curated_status = this.errorCodes.DONE;
},
err => {
this.handleError("Error getting claims for openaire id: "+this.openaireId, err);
this.pending_status = this.errorMessages.getErrorCode(err.status);
this.curated_status = this.pending_status;
/*if(err.status == '404') {
this.pending_status = this.errorCodes.NOT_FOUND;
this.curated_status = this.errorCodes.NOT_FOUND;
} else if(err.status == '500') {
this.pending_status = this.errorCodes.ERROR;
this.curated_status = this.errorCodes.ERROR;
} else {
this.pending_status = this.errorCodes.NOT_AVAILABLE;
this.curated_status = this.errorCodes.NOT_AVAILABLE;
}*/
this.showTables = true;
if(!this.triggered) {
this.triggerInitialLoad();
} else {
var table1 = $('#table1').DataTable();
table1.clear();
var table2 = $('#table2').DataTable();
table2.clear();
this.rerender();
}
this.accessStatus = "invalid";
//console.log(err);
}
);
} else {
this.accessStatus = "invalid";
}
}
}
selectApprove(id:string, event, mode: string) {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
var value = event.currentTarget.checked;
if(value){
if(mode == "pending") {
this.selectedRight_PendingMode.add(id);
this.selectedWrong_PendingMode.delete(id);
} else {
this.selectedRight_CuratedMode.add(id);
this.selectedWrong_CuratedMode.delete(id);
}
}else{
if(mode == "pending") {
this.selectedRight_PendingMode.delete(id);
}
// } else {
// this.selectedRight_CuratedMode.delete(id);
// this.selectedWrong_CuratedMode.add(id);
// }
}
}
}
selectDisapprove(id:string, event, mode: string) {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
var value = event.currentTarget.checked;
if(value){
if(mode == "pending") {
this.selectedWrong_PendingMode.add(id);
this.selectedRight_PendingMode.delete(id);
} else {
this.selectedWrong_CuratedMode.add(id);
this.selectedRight_CuratedMode.delete(id);
}
}else{
if(mode == "pending") {
this.selectedWrong_PendingMode.delete(id);
}
// } else {
// this.selectedWrong_CuratedMode.delete(id);
// this.selectedRight_CuratedMode.add(id);
// }
}
}
}
isSelected(id:string, set:Set<string>) {
return set.has(id);
}
/*
isSelectedWrong(id:string) {
return this.selectedWrong.has(id);
}
*/
isRight_CuratedMode(claim: any) {
if(this.isSelected(claim.id, this.selectedRight_CuratedMode)) {
return true;
} else if(claim.approved == true && !this.isSelected(claim.id, this.selectedWrong_CuratedMode)) {
return true;
}
return false;
}
isWrong_CuratedMode(claim: any) {
if(this.isSelected(claim.id, this.selectedWrong_CuratedMode)) {
return true;
} else if(claim.approved == false && !this.isSelected(claim.id, this.selectedRight_CuratedMode)) {
return true;
}
return false;
}
cancelEditOfCuration(claim: any) {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
if(claim.approved) {
//this.selectedRight_CuratedMode.add(claim.id);
this.selectedWrong_CuratedMode.delete(claim.id);
} else {
this.selectedRight_CuratedMode.delete(claim.id);
//this.selectedWrong_CuratedMode.add(claim.id);
}
}
}
saveEdited(claim: any, editable_index: number) {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
this.curated_status = this.errorCodes.LOADING;
let approved: boolean = this.isRight_CuratedMode(claim);
if(approved == claim.approved) {
this.selectedRight_CuratedMode.delete(claim.id);
this.selectedWrong_CuratedMode.delete(claim.id);
this.editable.delete(editable_index);
this.curated_status = this.errorCodes.DONE;
} else {
let claimCurationInfo: {"id": string, "approved": boolean} = {"id": claim.id, "approved": approved};
this.claimsByTokenService.updateClaimCuration(claimCurationInfo, this.properties.claimsAPIURL).subscribe(
data => {
this.selectedRight_CuratedMode.delete(claim.id);
this.selectedWrong_CuratedMode.delete(claim.id);
this.editable.delete(editable_index);
this.validateJWTandToken();
},
err => {
//console.log(err);
this.handleError("Error updating claim curation: "+JSON.stringify(claimCurationInfo), err);
this.curated_status = this.errorCodes.NOT_SAVED;
}
);
}
}
}
saveChanges() {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
this.pending_status = this.errorCodes.LOADING;
//this.openLoading();
//console.info("Changes Saved!, right-wrong", this.selectedRight_PendingMode, this.selectedWrong_PendingMode);
this.claimsByTokenService.updateClaimsCuration(this.selectedRight_PendingMode, this.selectedWrong_PendingMode, this.properties.claimsAPIURL).subscribe(
data => {
//this.closeLoading();
this.mode = "curated";
this.clearCheckboxes();
this.validateJWTandToken();
},
err => {
//this.closeLoading();
//console.log(err);
this.handleError("Error updating claims: right: "+JSON.stringify(this.selectedRight_PendingMode)+" and wrong: "+JSON.stringify(this.selectedWrong_PendingMode), err);
this.pending_status = this.errorCodes.NOT_SAVED;
}
);
}
}
clearCheckboxes() {
if(!Session.isLoggedIn()){
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
} else {
this.pending_status = this.errorCodes.LOADING;
this.selectedRight_PendingMode.clear();
this.selectedWrong_PendingMode.clear();
this.pending_status = this.errorCodes.DONE;
}
}
public openLoading(){
if(this.loading){
this.loading.open();
}
}
public closeLoading(){
if(this.loading){
this.loading.close();
}
}
curatorSelected(selected: string) {
//console.info("selected curator: "+selected);
}
public openSelect(){
if(this.selectModal){
this.selectModal.open();
}
}
public setMessageSelect(message: string){
if(this.selectModal){
this.selectModal.message = message;
}
}
public setOptionsSelect(options: string[]){
if(this.selectModal){
this.selectModal.options = options;
}
}
totalPages(totalResults: number): number {
let totalPages:any = totalResults/(this.rowsOnPage);
if(!(Number.isInteger(totalPages))) {
totalPages = (parseInt(totalPages, 10) + 1);
}
return totalPages;
}
updateTitle(title:string){
var _prefix ="OpenAIRE | ";
var _title = _prefix + ((title.length> 50 ) ?title.substring(0,50):title);
this._meta.updateTag({content:_title},"property='og:title'");
this._title.setTitle(_title);
}
private handleError(message: string, error) {
console.error("Claims Project Manager Page: "+message, error);
}
}