Project

General

Profile

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

    
14

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

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

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

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

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

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

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

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

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

    
70
    });
71

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

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

    
101
  @ViewChild (ModalLoading) loading : ModalLoading ;
102

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

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

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

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

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

    
128
  url=null;
129

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

    
214

    
215
}
216
handleErrors(err){
217

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

    
232
}
233

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

    
238
  goTo(page:number = 1){
239

    
240
    this.page = page;
241

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

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

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

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

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

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

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

    
400

    
401
     }
402

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

    
417

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

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

    
445

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

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

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

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

    
507

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

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

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

    
571
    }
572
}
(2-2/3)