Project

General

Profile

1

    
2
import {distinctUntilChanged, debounceTime} from 'rxjs/operators';
3
import {Component, ViewChild, Input} from '@angular/core';
4
import {Location} from '@angular/common';
5
import {Observable, Subject}       from 'rxjs';
6
import {ActivatedRoute, Router} from '@angular/router';
7
import {ClaimsService} from '../service/claims.service';
8
import {ModalLoading} from '../../../utils/modal/loading.component';
9
import {AlertModal} from '../../../utils/modal/alert';
10
import {Session} from '../../../login/utils/helper.class';
11
import{EnvProperties} from '../../../utils/properties/env-properties';
12
import {LoginErrorCodes} from '../../../login/utils/guardHelper.class';
13
import { SEOService } from '../../../sharedComponents/SEO/SEO.service';
14

    
15

    
16
@Component({
17
    selector: 'displayClaims',
18
    templateUrl: 'displayClaims.component.html',
19
    providers:[ ClaimsService]
20

    
21
})
22
export class DisplayClaimsComponent {
23
  properties:EnvProperties;
24
  public searchTermStream = new Subject<string>();
25

    
26
  constructor (private _claimService: ClaimsService,  private route: ActivatedRoute, private _router:Router, private location: Location,
27
private seoService: SEOService) {
28
   }
29

    
30
  ngOnInit() {
31
    this.route.data
32
      .subscribe((data: { envSpecific: EnvProperties }) => {
33
         this.properties = data.envSpecific;
34
         this.url = data.envSpecific.baseLink+this._router.url;
35

    
36
      });
37
     this.sub = this.route.queryParams.subscribe(params => {
38
      this.seoService.createLinkForCanonicalURL(this.properties.baseLink+this._router.url, false);
39

    
40
      if( this.myClaims){
41
          this.fetchBy = "User";
42
          this.fetchId = Session.getUserEmail();
43
      }else{
44

    
45
        this.fetchBy = (this.fetchBy)?this.fetchBy:params['fetchBy'];
46
        this.fetchBy = (this.types.indexOf(this.fetchBy) != -1)? this.fetchBy:'All';
47
        this.fetchId =(this.fetchId)?this.fetchId: params['fetchId'];
48
        this.fetchId = this.fetchId?this.fetchId:'';
49
      }
50

    
51
      let page = (params['page']=== undefined)?1:+params['page'];
52
      let size = (params['size']=== undefined)?10:+params['size'];
53

    
54
      this.keyword = (params['keyword']?params['keyword']:"");
55
      this.inputkeyword = this.keyword;
56
      this.page = ( page <= 0 ) ? 1 : page;
57
      this.size = ( size <= 0 ) ? 10 : size;
58
      this.entityTypes = []//(params['types']?params['types']:[]);
59
      this.setTypes(params['types']); // check the appropriate checkboxes
60
      this.setSortby(params['sort']);
61
      this.getClaims();
62
      this.searchTermStream.pipe(
63
      debounceTime(300),distinctUntilChanged(),)
64
      .subscribe((term: string) =>    {
65
        this.keyword = this.inputkeyword;
66
        //console.log("keyword: "+this.keyword + " VS inputkeyword: "+this.inputkeyword);
67
        this.page = 1;
68
        this.goTo();
69
      });
70

    
71
    });
72

    
73
  }
74
  ngOnDestroy() {
75
    this.sub.unsubscribe();
76
    //this.searchTermStreamSub.unsubscribe();
77
  }
78
    sub: any;
79
  //string because comes as input from component directive
80
  @Input() enableDelete: boolean = false;
81
  @Input() showUserEmail: boolean = true;
82
  @Input() myClaims: boolean= false ;
83
  @Input() isAdmin:boolean = false;
84
  @Input() showLatestClaims:boolean = false;
85
  // recentClaims = [];
86
  page : number;
87
  size:number;
88
  sizes = [10,20,30,50];
89
  keyword:string; // the keyword string to give to the request as parameter
90
  inputkeyword:string; // the string written in the input field (keyword=inputkeyword when its length is bigger than 3 and the user stops typing)
91
  lengths = [10,20,30,50];
92
  types = ["All","Project","Context","Result","User"];
93
  @Input() fetchBy:string;
94
  @Input() fetchId:string;
95

    
96
  navigateTo: string = "Claims";
97
  resultsNum: number ;
98
  claims: string[];
99
  @Input() externalPortalUrl:string = null;
100
  @Input() claimsInfoURL:string;// ="https://www.openaire.eu/linking";
101

    
102
  @ViewChild (ModalLoading) loading : ModalLoading ;
103

    
104
  //checkboxes:
105
  publicationCB = false;
106
  datasetCB = false;
107
  softwareCB = false;
108
  otherCB = false;
109
  contextCB = false;
110
  projectCB = false;
111
  entityTypes : string[] =[] ;
112

    
113
  descending = true;
114
  sortby = "date";
115

    
116
  selected=[];
117
  deleteMessage:string = "";
118
  showErrorMessage:boolean = false;
119
  showForbiddenMessage:boolean = false;
120
  userValidMessage:string = "";
121

    
122
  //params for pagingFormatter to use when navigate to page
123
  params;
124
  @ViewChild(AlertModal) alert;
125

    
126
  claimsDeleted:number = 0;
127
  @Input() communityId:string = null;
128

    
129
  url=null;
130

    
131
  getClaims () {
132
    if(!Session.isLoggedIn()){
133
      this.userValidMessage = "User session has expired. Please login again.";
134
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
135
    }else{
136
    this.selected=[];
137
    var types = '';
138
    this.showErrorMessage = false;
139
    this.showForbiddenMessage = false;
140
    for (var type of this.entityTypes){
141
      types+=(types.length>0?'&':'')+"types="+type;
142
    }
143
    if(this.fetchBy =="Project" ){
144
      this._claimService.getClaimsByProject(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
145
        data => {
146
          this.manageAPIData(data);
147
          },
148
        err => {
149
          this.handleErrors(err);
150
          this.handleError("Error getting claims for project with id: "+this.fetchId, err);
151
        }
152
      );
153
    }else if(this.fetchBy =="User"){
154
      this._claimService.getClaimsByUser(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types,this.properties.claimsAPIURL).subscribe(
155
        data => {
156
          this.manageAPIData(data);
157
          },
158
          err => {
159
            this.handleErrors(err);
160
            this.handleError("Error getting claims for user with id: "+this.fetchId, err);
161
          }
162
      );
163
    }else if(this.fetchBy =="Result"){
164
      this._claimService.getClaimsByResult(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
165
        data => {
166
          this.manageAPIData(data);
167
          },
168
          err => {
169
            this.handleErrors(err);
170
            this.handleError("Error getting claims for result with id: "+this.fetchId, err);
171
          }
172
      );
173
    }else if(this.fetchBy =="Context"){
174
      this._claimService.getClaimsBycontext(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
175
        data => {
176
          this.manageAPIData(data);
177
          },
178
          err => {
179
             this.handleErrors(err);
180
             this.handleError("Error getting claims for context with id: "+this.fetchId, err);
181
          }
182
      );
183
    }else{
184
      this._claimService.getClaims(this.size,this.page,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
185
        data => {
186
          this.manageAPIData(data);
187
          },
188
          err => {
189
            this.handleErrors(err);
190
            this.handleError("Error getting claims", err);
191
          }
192
      );
193
    }
194
  }
195
}
196
manageAPIData(data){
197
   var d = new Date();
198
  var dateTomillis = d.getTime();
199
  var millis24h:number = 24*3600000;
200
  // if(this.showLatestClaims && this.recentClaims.length == 0){
201
  //   this.recentClaims = [];
202
  //   for(var i=0;i<data.data.length;i++){
203
  //     var claimDate = new Date(data.data[i].date);
204
  //     var claimDateToMillis = claimDate.getTime()
205
  //     // console.log("Claim Date is:"+claimDateToMillis + " "+(dateTomillis - claimDateToMillis));
206
  //     if((dateTomillis - claimDateToMillis)<millis24h){
207
  //       // console.log("Claim in:"+  " "+(dateTomillis - claimDateToMillis)+" < " +(millis24h));
208
  //       this.recentClaims.push(data.data[i]);
209
  //     }
210
  //   }
211
  // }
212
  this.claims = data.data;
213
  this.resultsNum= data.total;
214

    
215

    
216
}
217
handleErrors(err){
218

    
219
  this.showErrorMessage = true;
220
  try{
221
    var error =  err.json()
222
      var code = error.code;
223
      if(code == 403){
224
        this.showErrorMessage = false;
225
        this.showForbiddenMessage = true;
226
      }
227
  }catch (e) {
228
        //console.log("Couldn't parse answer as json")
229
        this.handleError("Error parsing answer as json", e);
230
        this.showErrorMessage = true;
231
  }
232

    
233
}
234

    
235
  private handleError(message: string, error) {
236
    console.error("Dispaly Claims (component): "+message, error);
237
  }
238

    
239
  goTo(page:number = 1){
240

    
241
    this.page = page;
242

    
243
    this.location.go(location.pathname,this.getParametersString());
244
    this.getClaims();
245
  }
246
  getParameters(){
247
    var params = {}
248
    if(this.myClaims){
249
       params={ page: this.page, size: this.size, types: this.entityTypes, keyword : this.keyword, sort: this.getSortby()  };
250
    }else{
251
      params={ page: this.page, size: this.size, types: this.entityTypes, fetchBy: this.fetchBy, fetchId:this.fetchId, keyword : this.keyword, sort: this.getSortby()  };
252
    }
253
    return params;
254
  }
255

    
256
  getParametersString(){
257
    var params='';
258
    params+=(this.page==1?"":(params.length>0?'&':'')+"page="+this.page);
259
    params+=(this.size==10?"":(params.length>0?'&':'')+"size="+this.size);
260
    // params+=(this.entityTypes==''?"":(params.length>0?'&':'')+"types="+this.entityTypes);
261
    var types="";
262
    for (var type of this.entityTypes){
263
         types+=(types.length>0?',':'')+type;
264
    }
265
    params+=(types.length>0)?"types="+types:"";
266

    
267
    if(this.isAdmin ){
268
      params+=(this.fetchBy=='All'?"":(params.length>0?'&':'')+"fetchBy="+this.fetchBy);
269
      params+=(this.fetchId==''?"":(params.length>0?'&':'')+"fetchId="+this.fetchId);
270
    }
271
    params+=(this. getSortby()=='datedesc'?"":(params.length>0?'&':'')+"sort="+this. getSortby());
272
    params+=(this.keyword==''?"":(params.length>0?'&':'')+"keyword="+this.keyword);
273
    if(this.communityId !=null){
274
      params+="&communityId="+this.communityId;
275
    }
276
    return params;
277
  }
278
  changeSize(size: number ){
279
      this.goTo();
280
  }
281

    
282
  clearFilters(){
283
    this.keyword = '';
284
    this.inputkeyword = '';
285
    this.publicationCB = false;
286
    this.projectCB = false;
287
    this.datasetCB = false;
288
    this.softwareCB = false;
289
    this.otherCB = false;
290
    this.contextCB = false;
291
    this.entityTypes = [];
292
    this.goTo();
293
   }
294

    
295
   changeOrderby(sortby:string){
296
     if(sortby==this.sortby){
297
       this.descending = !this.descending;
298
     }else{
299
       this.sortby = sortby;
300
       this.descending = false;
301
     }
302
     this.goTo();
303
   }
304
   setSortby(sortby:string){
305
     if(!sortby|| sortby == "datedesc"){
306
       this.descending = true;
307
       this.sortby = "date";
308
     }else if(sortby == "dateasc"){
309
       this.descending = false;
310
       this.sortby = "date";
311
     }else if(sortby == "userasc"){
312
       this.descending = false;
313
       this.sortby = "user";
314
     }else if(sortby == "userdesc"){
315
       this.descending = true;
316
       this.sortby = "user";
317
     }if(sortby =="sourceasc"){
318
       this.descending = false;
319
       this.sortby = "source";
320
     }else if(sortby == "sourcedesc"){
321
       this.descending = true;
322
       this.sortby = "source";
323
     }else if(sortby == "targetasc"){
324
       this.descending = false;
325
       this.sortby = "target";
326
     }else if(sortby == "targetdesc"){
327
       this.descending = true;
328
       this.sortby = "target";
329
     }
330
   }
331
   getSortby():string{
332
     if(this.descending){
333
       return this.sortby+"desc";
334
     }else{
335
       return this.sortby+"asc";
336
     }
337

    
338
   }
339
   changeType(){
340
     this.entityTypes = [];
341
     if(this.publicationCB){
342
       this.entityTypes.push('publication');
343
     }
344
     if(this.datasetCB){
345
       this.entityTypes.push('dataset');
346
     }
347
     if(this.softwareCB){
348
       this.entityTypes.push('software');
349
     }
350
     if(this.otherCB){
351
       this.entityTypes.push('other');
352
     }
353
     if(this.projectCB){
354
       this.entityTypes.push('project');
355
     }
356
     if(this.contextCB){
357
       this.entityTypes.push('context');
358
     }
359

    
360
     this.goTo();
361
   }
362
   setTypes(types:string){
363
     if(!types){
364
       return;
365
     }
366
     if(types.length > 0){
367
       this.entityTypes = [];
368
       if(types.indexOf("publication")!=-1){
369
         this.publicationCB = true;
370
         this.entityTypes.push("publication");
371
       }
372
       if(types.indexOf("dataset")!=-1){
373
         this.datasetCB = true;
374
         this.entityTypes.push("dataset");
375
       }
376
       if(types.indexOf("software")!=-1){
377
         this.softwareCB = true;
378
         this.entityTypes.push("software");
379
       }
380
       if(types.indexOf("other")!=-1){
381
         this.otherCB = true;
382
         this.entityTypes.push("other");
383
       }
384
       if(types.indexOf("project")!=-1){
385
         this.projectCB = true;
386
         this.entityTypes.push("project");
387
       }
388
       if(types.indexOf("context")!=-1){
389
         this.contextCB = true;
390
         this.entityTypes.push("context");
391
       }
392
     }
393
     if(this.publicationCB && this.datasetCB && this.softwareCB && this.otherCB && this.contextCB && this.projectCB){
394
       this.entityTypes=[];
395
     }
396
   }
397
   changekeyword(){
398
     if(this.inputkeyword.length >= 3 || this.inputkeyword.length == 0 ){
399
       this.searchTermStream.next(this.inputkeyword);
400

    
401

    
402
     }
403

    
404
   }
405
   select(item:any,event){
406
     this.deleteMessage="";
407
     var value = event.currentTarget.checked;
408
     if(value){
409
       this.selected.push(item);
410
     }else{
411
       for (var _i = 0; _i < this.selected.length; _i++) {
412
           let claim = this.selected[_i];
413
           if(claim['id'] == item.id){
414
                 this.selected.splice(_i, 1);
415
           }
416
        }
417

    
418

    
419
     }
420
   }
421
   selectAll(event){
422
     var value = event.currentTarget.checked;
423
     if(value){
424
       this.selected = [];
425
      for (var _i = 0; _i < this.claims.length; _i++) {
426
         let claim = this.claims[_i];
427
         this.selected.push(claim);
428
       }
429
        this.deleteMessage = "";
430
    }else{
431
      this.selected = [];
432
      this.deleteMessage="";
433
    }
434
   }
435

    
436
   isSelected(id:string){
437
     for (var _i = 0; _i < this.selected.length; _i++) {
438
         let claim = this.selected[_i];
439
         if(claim['id'] == id){
440
              return true;
441
         }
442
      }
443
      return false;
444
   }
445

    
446

    
447
     confirmOpen(){
448
       if(this.selected.length <= 0){
449

    
450
       }else{
451
         this.alert.cancelButton = true;
452
         this.alert.okButton = true;
453
         this.alert.alertTitle = "Delete "+this.selected.length+" claim(s)";
454
         this.alert.message = this.selected.length+" claims will be deleted. Do you want to proceed? ";
455
         this.alert.okButtonText = "Yes";
456
         this.alert.cancelButtonText = "No";
457
         this.alert.open();
458
       }
459
     }
460
      confirmClose(data){
461
       this.delete();
462
     }
463
   delete(){
464
     this.deleteMessage="";
465
     this.loading.open();
466
     this.claimsDeleted = 0;
467
     var ids = [];
468
     for (var i = 0; i < this.selected.length; i++){
469
        var id  =this.selected[i].id;
470
        ids.push(id);
471
        // var selected  =this.selected[i].id;
472
        // console.warn("Deleting claim with id:"+id);
473
        //  this.deleteById(id);
474
         //TODO for multiple concurrent
475
        }
476
         this.batchDeleteById(ids);
477
    }
478

    
479
    deleteById(id:string){
480
      if(!Session.isLoggedIn()){
481
        this.userValidMessage = "User session has expired. Please login again.";
482
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
483

    
484
      }else{
485
         //console.log("Deleting claim with id:"+id);
486
         // this._claimService.deleteClaimById(id);
487
         this._claimService.deleteClaimById(id, this.properties.claimsAPIURL).subscribe(
488
            res =>  {
489
              //console.log('Delete response'+res.code );
490
              //console.log("Deleted claim with id:"+ id);
491
              //remove this claim from the
492
             let newClaims=this.claims;
493
             for (var _i = 0; _i < this.claims.length; _i++) {
494
                 let claim = this.claims[_i];
495
                 if(claim['id'] == id){
496
                       newClaims.splice(_i, 1);
497
                 }
498
              }
499
              //TODO should call getClaims???
500
              this.claimsDeleted++;
501
              this.claims = newClaims;
502
              if(this.claimsDeleted == this.selected.length){
503
                this.resultsNum = this.resultsNum - this.selected.length;
504
                this.loading.close();
505
                this.selected = [];
506
              }
507

    
508

    
509
           },
510
            error => {
511
              this.handleError("Error deleting claim with id: "+id, error);
512
            });
513
         }
514
    }
515
    batchDeleteById(ids:string[]){
516
      if(!Session.isLoggedIn()){
517
        this.userValidMessage = "User session has expired. Please login again.";
518
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
519
      }else{
520
         //console.warn("Deleting claim with ids:"+ids);
521
         this._claimService.deleteBulk(ids,this.properties.claimsAPIURL).subscribe(
522
            res =>  {
523
              //console.info('Delete response'+res.code );
524
              //console.warn("Deleted ids:"+ res.deletedIds);
525
              //console.warn("Not found ids:"+ res.notFoundIds);
526
              //remove this claim from the
527
             let newClaims=this.claims;
528
             for(var id of res.deletedIds){
529
               for (var _i = 0; _i < this.claims.length; _i++) {
530
                   let claim = this.claims[_i];
531
                   if(claim['id'] == id){
532
                         newClaims.splice(_i, 1);
533
                   }
534
                }
535
                for (var _i = 0; _i < this.selected.length; _i++) {
536
                    let claim = this.selected[_i];
537
                    if(claim['id'] == id){
538
                          this.selected.splice(_i, 1);
539
                    }
540
                 }
541
              }
542
              this.claims = newClaims;
543
              this.resultsNum = this.resultsNum - res.deletedIds.length;
544
              this.loading.close();
545
              if(res.deletedIds.length>0){
546
                  this.deleteMessage=this.deleteMessage+'<div class = "uk-alert uk-alert-primary " >'+res.deletedIds.length+' claim(s) successfully deleted.</div>';
547
              }
548
              if(res.notFoundIds.length>0){
549
                  this.deleteMessage=this.deleteMessage+'<div class = "uk-alert uk-alert-warning " >'+res.notFoundIds.length+' claim(s) couldn\'t be deleted.</div>';
550
              }
551
           }, err => {
552
             //console.log(err);
553
             this.handleError("Error deleting claims with ids: "+ids, err);
554
             this.showErrorMessage = true;
555
             this.loading.close();
556

    
557
           });
558
         }
559
    }
560
    pageChange($event) {
561
      var page:number = +$event.value
562
      this.goTo(page);
563
    }
564

    
565
    getclaimStatus(claim):string{
566
      if(claim.target.collectedFrom == "infrastruct_::openaire"){
567
         return "The link information will be visible in the portal and the APIs after the next content provision workflow.";
568
      }else{
569
        return "The link information is visible in the portal and the APIs.";
570
      }
571

    
572
    }
573
}
(2-2/3)