openaire-library/claims/claim-utils/displayClaims/displayClaims.component.ts

574 lines
18 KiB
TypeScript

import {distinctUntilChanged, debounceTime} from 'rxjs/operators';
import {Component, ViewChild, Input} from '@angular/core';
import {Location} from '@angular/common';
import {Observable, Subject} from 'rxjs';
import {ActivatedRoute, Router} from '@angular/router';
import {ClaimsService} from '../service/claims.service';
import {ModalLoading} from '../../../utils/modal/loading.component';
import {AlertModal} from '../../../utils/modal/alert';
import {Session} from '../../../login/utils/helper.class';
import{EnvProperties} from '../../../utils/properties/env-properties';
import {LoginErrorCodes} from '../../../login/utils/guardHelper.class';
import { SEOService } from '../../../sharedComponents/SEO/SEO.service';
@Component({
selector: 'displayClaims',
templateUrl: 'displayClaims.component.html',
providers:[ ClaimsService]
})
export class DisplayClaimsComponent {
properties:EnvProperties;
public searchTermStream = new Subject<string>();
constructor (private _claimService: ClaimsService, private route: ActivatedRoute, private _router:Router, private location: Location,
private seoService: SEOService) {
}
ngOnInit() {
this.route.data
.subscribe((data: { envSpecific: EnvProperties }) => {
this.properties = data.envSpecific;
this.url = data.envSpecific.baseLink+this._router.url;
});
this.sub = this.route.queryParams.subscribe(params => {
this.seoService.createLinkForCanonicalURL(this.properties.baseLink+this._router.url, false);
if( this.myClaims){
this.fetchBy = "User";
this.fetchId = Session.getUserEmail();
}else{
this.fetchBy = (this.fetchBy)?this.fetchBy:params['fetchBy'];
this.fetchBy = (this.types.indexOf(this.fetchBy) != -1)? this.fetchBy:'All';
this.fetchId =(this.fetchId)?this.fetchId: params['fetchId'];
this.fetchId = this.fetchId?this.fetchId:'';
}
let page = (params['page']=== undefined)?1:+params['page'];
let size = (params['size']=== undefined)?10:+params['size'];
this.keyword = (params['keyword']?params['keyword']:"");
this.inputkeyword = this.keyword;
this.page = ( page <= 0 ) ? 1 : page;
this.size = ( size <= 0 ) ? 10 : size;
this.entityTypes = []//(params['types']?params['types']:[]);
this.setTypes(params['types']); // check the appropriate checkboxes
this.setSortby(params['sort']);
this.getClaims();
this.searchTermStream.pipe(
debounceTime(300),distinctUntilChanged(),)
.subscribe((term: string) => {
this.keyword = this.inputkeyword;
//console.log("keyword: "+this.keyword + " VS inputkeyword: "+this.inputkeyword);
this.page = 1;
this.goTo();
});
});
}
ngOnDestroy() {
this.sub.unsubscribe();
//this.searchTermStreamSub.unsubscribe();
}
sub: any;
//string because comes as input from component directive
@Input() enableDelete: boolean = false;
@Input() showUserEmail: boolean = true;
@Input() myClaims: boolean= false ;
@Input() isAdmin:boolean = false;
@Input() showLatestClaims:boolean = false;
// recentClaims = [];
page : number;
size:number;
sizes = [10,20,30,50];
keyword:string; // the keyword string to give to the request as parameter
inputkeyword:string; // the string written in the input field (keyword=inputkeyword when its length is bigger than 3 and the user stops typing)
lengths = [10,20,30,50];
types = ["All","Project","Context","Result","User"];
@Input() fetchBy:string;
@Input() fetchId:string;
navigateTo: string = "Claims";
resultsNum: number ;
claims: string[];
@Input() externalPortalUrl:string = null;
@Input() claimsInfoURL:string;// ="https://www.openaire.eu/linking";
@ViewChild (ModalLoading) loading : ModalLoading ;
//checkboxes:
publicationCB = false;
datasetCB = false;
softwareCB = false;
otherCB = false;
contextCB = false;
projectCB = false;
entityTypes : string[] =[] ;
descending = true;
sortby = "date";
selected=[];
deleteMessage:string = "";
showErrorMessage:boolean = false;
showForbiddenMessage:boolean = false;
userValidMessage:string = "";
//params for pagingFormatter to use when navigate to page
params;
@ViewChild(AlertModal) alert;
claimsDeleted:number = 0;
@Input() communityId:string = null;
url=null;
getClaims () {
if(!Session.isLoggedIn()){
this.userValidMessage = "User session has expired. Please login again.";
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
}else{
this.selected=[];
var types = '';
this.showErrorMessage = false;
this.showForbiddenMessage = false;
for (var type of this.entityTypes){
types+=(types.length>0?'&':'')+"types="+type;
}
if(this.fetchBy =="Project" ){
this._claimService.getClaimsByProject(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
data => {
this.manageAPIData(data);
},
err => {
this.handleErrors(err);
this.handleError("Error getting claims for project with id: "+this.fetchId, err);
}
);
}else if(this.fetchBy =="User"){
this._claimService.getClaimsByUser(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types,this.properties.claimsAPIURL).subscribe(
data => {
this.manageAPIData(data);
},
err => {
this.handleErrors(err);
this.handleError("Error getting claims for user with id: "+this.fetchId, err);
}
);
}else if(this.fetchBy =="Result"){
this._claimService.getClaimsByResult(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
data => {
this.manageAPIData(data);
},
err => {
this.handleErrors(err);
this.handleError("Error getting claims for result with id: "+this.fetchId, err);
}
);
}else if(this.fetchBy =="Context"){
this._claimService.getClaimsBycontext(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
data => {
this.manageAPIData(data);
},
err => {
this.handleErrors(err);
this.handleError("Error getting claims for context with id: "+this.fetchId, err);
}
);
}else{
this._claimService.getClaims(this.size,this.page,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
data => {
this.manageAPIData(data);
},
err => {
this.handleErrors(err);
this.handleError("Error getting claims", err);
}
);
}
}
}
manageAPIData(data){
var d = new Date();
var dateTomillis = d.getTime();
var millis24h:number = 24*3600000;
// if(this.showLatestClaims && this.recentClaims.length == 0){
// this.recentClaims = [];
// for(var i=0;i<data.data.length;i++){
// var claimDate = new Date(data.data[i].date);
// var claimDateToMillis = claimDate.getTime()
// // console.log("Claim Date is:"+claimDateToMillis + " "+(dateTomillis - claimDateToMillis));
// if((dateTomillis - claimDateToMillis)<millis24h){
// // console.log("Claim in:"+ " "+(dateTomillis - claimDateToMillis)+" < " +(millis24h));
// this.recentClaims.push(data.data[i]);
// }
// }
// }
this.claims = data.data;
this.resultsNum= data.total;
}
handleErrors(err){
this.showErrorMessage = true;
try{
var error = err.json()
var code = error.code;
if(code == 403){
this.showErrorMessage = false;
this.showForbiddenMessage = true;
}
}catch (e) {
//console.log("Couldn't parse answer as json")
this.handleError("Error parsing answer as json", e);
this.showErrorMessage = true;
}
}
private handleError(message: string, error) {
console.error("Dispaly Claims (component): "+message, error);
}
goTo(page:number = 1){
this.page = page;
this.location.go(location.pathname,this.getParametersString());
this.getClaims();
}
getParameters(){
var params = {}
if(this.myClaims){
params={ page: this.page, size: this.size, types: this.entityTypes, keyword : this.keyword, sort: this.getSortby() };
}else{
params={ page: this.page, size: this.size, types: this.entityTypes, fetchBy: this.fetchBy, fetchId:this.fetchId, keyword : this.keyword, sort: this.getSortby() };
}
return params;
}
getParametersString(){
var params='';
params+=(this.page==1?"":(params.length>0?'&':'')+"page="+this.page);
params+=(this.size==10?"":(params.length>0?'&':'')+"size="+this.size);
// params+=(this.entityTypes==''?"":(params.length>0?'&':'')+"types="+this.entityTypes);
var types="";
for (var type of this.entityTypes){
types+=(types.length>0?',':'')+type;
}
params+=(types.length>0)?"types="+types:"";
if(this.isAdmin ){
params+=(this.fetchBy=='All'?"":(params.length>0?'&':'')+"fetchBy="+this.fetchBy);
params+=(this.fetchId==''?"":(params.length>0?'&':'')+"fetchId="+this.fetchId);
}
params+=(this. getSortby()=='datedesc'?"":(params.length>0?'&':'')+"sort="+this. getSortby());
params+=(this.keyword==''?"":(params.length>0?'&':'')+"keyword="+this.keyword);
if(this.communityId !=null){
params+="&communityId="+this.communityId;
}
return params;
}
changeSize(size: number ){
this.goTo();
}
clearFilters(){
this.keyword = '';
this.inputkeyword = '';
this.publicationCB = false;
this.projectCB = false;
this.datasetCB = false;
this.softwareCB = false;
this.otherCB = false;
this.contextCB = false;
this.entityTypes = [];
this.goTo();
}
changeOrderby(sortby:string){
if(sortby==this.sortby){
this.descending = !this.descending;
}else{
this.sortby = sortby;
this.descending = false;
}
this.goTo();
}
setSortby(sortby:string){
if(!sortby|| sortby == "datedesc"){
this.descending = true;
this.sortby = "date";
}else if(sortby == "dateasc"){
this.descending = false;
this.sortby = "date";
}else if(sortby == "userasc"){
this.descending = false;
this.sortby = "user";
}else if(sortby == "userdesc"){
this.descending = true;
this.sortby = "user";
}if(sortby =="sourceasc"){
this.descending = false;
this.sortby = "source";
}else if(sortby == "sourcedesc"){
this.descending = true;
this.sortby = "source";
}else if(sortby == "targetasc"){
this.descending = false;
this.sortby = "target";
}else if(sortby == "targetdesc"){
this.descending = true;
this.sortby = "target";
}
}
getSortby():string{
if(this.descending){
return this.sortby+"desc";
}else{
return this.sortby+"asc";
}
}
changeType(){
this.entityTypes = [];
if(this.publicationCB){
this.entityTypes.push('publication');
}
if(this.datasetCB){
this.entityTypes.push('dataset');
}
if(this.softwareCB){
this.entityTypes.push('software');
}
if(this.otherCB){
this.entityTypes.push('other');
}
if(this.projectCB){
this.entityTypes.push('project');
}
if(this.contextCB){
this.entityTypes.push('context');
}
this.goTo();
}
setTypes(types:string){
if(!types){
return;
}
if(types.length > 0){
this.entityTypes = [];
if(types.indexOf("publication")!=-1){
this.publicationCB = true;
this.entityTypes.push("publication");
}
if(types.indexOf("dataset")!=-1){
this.datasetCB = true;
this.entityTypes.push("dataset");
}
if(types.indexOf("software")!=-1){
this.softwareCB = true;
this.entityTypes.push("software");
}
if(types.indexOf("other")!=-1){
this.otherCB = true;
this.entityTypes.push("other");
}
if(types.indexOf("project")!=-1){
this.projectCB = true;
this.entityTypes.push("project");
}
if(types.indexOf("context")!=-1){
this.contextCB = true;
this.entityTypes.push("context");
}
}
if(this.publicationCB && this.datasetCB && this.softwareCB && this.otherCB && this.contextCB && this.projectCB){
this.entityTypes=[];
}
}
changekeyword(){
if(this.inputkeyword.length >= 3 || this.inputkeyword.length == 0 ){
this.searchTermStream.next(this.inputkeyword);
}
}
select(item:any,event){
this.deleteMessage="";
var value = event.currentTarget.checked;
if(value){
this.selected.push(item);
}else{
for (var _i = 0; _i < this.selected.length; _i++) {
let claim = this.selected[_i];
if(claim['id'] == item.id){
this.selected.splice(_i, 1);
}
}
}
}
selectAll(event){
var value = event.currentTarget.checked;
if(value){
this.selected = [];
for (var _i = 0; _i < this.claims.length; _i++) {
let claim = this.claims[_i];
this.selected.push(claim);
}
this.deleteMessage = "";
}else{
this.selected = [];
this.deleteMessage="";
}
}
isSelected(id:string){
for (var _i = 0; _i < this.selected.length; _i++) {
let claim = this.selected[_i];
if(claim['id'] == id){
return true;
}
}
return false;
}
confirmOpen(){
if(this.selected.length <= 0){
}else{
this.alert.cancelButton = true;
this.alert.okButton = true;
this.alert.alertTitle = "Delete "+this.selected.length+" claim(s)";
this.alert.message = this.selected.length+" claims will be deleted. Do you want to proceed? ";
this.alert.okButtonText = "Yes";
this.alert.cancelButtonText = "No";
this.alert.open();
}
}
confirmClose(data){
this.delete();
}
delete(){
this.deleteMessage="";
this.loading.open();
this.claimsDeleted = 0;
var ids = [];
for (var i = 0; i < this.selected.length; i++){
var id =this.selected[i].id;
ids.push(id);
// var selected =this.selected[i].id;
// console.warn("Deleting claim with id:"+id);
// this.deleteById(id);
//TODO for multiple concurrent
}
this.batchDeleteById(ids);
}
deleteById(id:string){
if(!Session.isLoggedIn()){
this.userValidMessage = "User session has expired. Please login again.";
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
}else{
//console.log("Deleting claim with id:"+id);
// this._claimService.deleteClaimById(id);
this._claimService.deleteClaimById(id, this.properties.claimsAPIURL).subscribe(
res => {
//console.log('Delete response'+res.code );
//console.log("Deleted claim with id:"+ id);
//remove this claim from the
let newClaims=this.claims;
for (var _i = 0; _i < this.claims.length; _i++) {
let claim = this.claims[_i];
if(claim['id'] == id){
newClaims.splice(_i, 1);
}
}
//TODO should call getClaims???
this.claimsDeleted++;
this.claims = newClaims;
if(this.claimsDeleted == this.selected.length){
this.resultsNum = this.resultsNum - this.selected.length;
this.loading.close();
this.selected = [];
}
},
error => {
this.handleError("Error deleting claim with id: "+id, error);
});
}
}
batchDeleteById(ids:string[]){
if(!Session.isLoggedIn()){
this.userValidMessage = "User session has expired. Please login again.";
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
}else{
//console.warn("Deleting claim with ids:"+ids);
this._claimService.deleteBulk(ids,this.properties.claimsAPIURL).subscribe(
res => {
//console.info('Delete response'+res.code );
//console.warn("Deleted ids:"+ res.deletedIds);
//console.warn("Not found ids:"+ res.notFoundIds);
//remove this claim from the
let newClaims=this.claims;
for(var id of res.deletedIds){
for (var _i = 0; _i < this.claims.length; _i++) {
let claim = this.claims[_i];
if(claim['id'] == id){
newClaims.splice(_i, 1);
}
}
for (var _i = 0; _i < this.selected.length; _i++) {
let claim = this.selected[_i];
if(claim['id'] == id){
this.selected.splice(_i, 1);
}
}
}
this.claims = newClaims;
this.resultsNum = this.resultsNum - res.deletedIds.length;
this.loading.close();
if(res.deletedIds.length>0){
this.deleteMessage=this.deleteMessage+'<div class = "uk-alert uk-alert-primary " >'+res.deletedIds.length+' claim(s) successfully deleted.</div>';
}
if(res.notFoundIds.length>0){
this.deleteMessage=this.deleteMessage+'<div class = "uk-alert uk-alert-warning " >'+res.notFoundIds.length+' claim(s) couldn\'t be deleted.</div>';
}
}, err => {
//console.log(err);
this.handleError("Error deleting claims with ids: "+ids, err);
this.showErrorMessage = true;
this.loading.close();
});
}
}
pageChange($event) {
var page:number = +$event.value
this.goTo(page);
}
getclaimStatus(claim):string{
if(claim.target.collectedFrom == "infrastruct_::openaire"){
return "The link information will be visible in the portal and the APIs after the next content provision workflow.";
}else{
return "The link information is visible in the portal and the APIs.";
}
}
}