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 {ClaimsService} from '../service/claims.service';
6
import {ModalLoading} from '../../../utils/modal/loading.component';
7
import {AlertModal} from '../../../utils/modal/alert';
8
import {Session} from '../../../login/utils/helper.class';
9

    
10

    
11
@Component({
12
    selector: 'displayClaims',
13
    templateUrl: 'displayClaims.component.html',
14
    providers:[ ClaimsService]
15

    
16
})
17
export class DisplayClaimsComponent {
18
  constructor (private _claimService: ClaimsService,  private route: ActivatedRoute, private _router:Router, private location: Location) {
19
   }
20

    
21
  ngOnInit() {
22
     this.sub = this.route.queryParams.subscribe(params => {
23
      if( this.myClaims){
24
          this.fetchBy = "User";
25
          this.fetchId = Session.getUserEmail();
26
      }else{
27

    
28
        this.fetchBy = params['fetchBy'];
29
        this.fetchBy = (this.types.indexOf(this.fetchBy) != -1)? this.fetchBy:'All';
30
        this.fetchId = params['fetchId'];
31
        this.fetchId = this.fetchId?this.fetchId:'';
32

    
33
      }
34

    
35
      let page = (params['page']=== undefined)?1:+params['page'];
36
      let size = (params['size']=== undefined)?10:+params['size'];
37

    
38
      this.keyword = (params['keyword']?params['keyword']:"");
39
      this.inputkeyword = this.keyword;
40
      this.page = ( page <= 0 ) ? 1 : page;
41
      this.size = ( size <= 0 ) ? 10 : size;
42
      this.entityTypes = []//(params['types']?params['types']:[]);
43
      this.setTypes(params['types']); // check the appropriate checkboxes
44
      this.setSortby(params['sort']);
45
      this.getClaims();
46

    
47
    });
48

    
49
  }
50
  ngOnDestroy() {
51
    this.sub.unsubscribe();
52
  }
53
    sub: any;
54
  //string because comes as input from component directive
55
  @Input() enableDelete: boolean = false;
56
  @Input() showUserEmail: boolean = true;
57
  @Input() myClaims: boolean= false ;
58
  @Input() isAdmin:boolean = false;
59
  page : number;
60
  size:number;
61
  sizes = [10,20,30,50];
62
  keyword:string; // the keyword string to give to the request as parameter
63
  inputkeyword:string; // the string written in the input field (keyword=inputkeyword when its length is bigger than 3 and the user stops typing)
64
  lengths = [10,20,30,50];
65
  types = ["All","Project","Context","Result","User"];
66
  @Input() fetchBy:string;
67
  @Input() fetchId:string;
68

    
69
  navigateTo: string = "Claims";
70
  resultsNum: number ;
71
  claims: string[];
72

    
73
  @ViewChild (ModalLoading) loading : ModalLoading ;
74

    
75
  //checkboxes:
76
  publicationCB = false;
77
  datasetCB = false;
78
  softwareCB = false;
79
  contextCB = false;
80
  projectCB = false;
81
  entityTypes : string[] =[] ;
82

    
83
  descending = true;
84
  sortby = "date";
85

    
86
  selected=[];
87
  deleteMessage:string = "";
88
  showErrorMessage:boolean = false;
89
  showForbiddenMessage:boolean = false;
90
  userValidMessage:string = "";
91

    
92
  //params for pagingFormatter to use when navigate to page
93
  params;
94
  @ViewChild(AlertModal) alert;
95

    
96
  claimsDeleted:number = 0;
97

    
98
  getClaims () {
99
    if(!Session.isValidAndRemove()){
100
      this.userValidMessage = "User session has expired. Please login again.";
101

    
102
    }else{
103
      var token=Session.getUserJwt();
104
    this.selected=[];
105
    var types = '';
106
    this.showErrorMessage = false;
107
    this.showForbiddenMessage = false;
108
    for (var type of this.entityTypes){
109
      types+=(types.length>0?'&':'')+"types="+type;
110
    }
111
    if(this.fetchBy =="Project" ){
112
      this._claimService.getClaimsByProject(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types).subscribe(
113
        data => {
114
          this.claims = data.data;
115
          this.resultsNum= data.total;
116
          },
117
        err => {
118
          this.handleErrors(err);
119
        }
120
      );
121
    }else if(this.fetchBy =="User"){
122
      this._claimService.getClaimsByUser(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types).subscribe(
123
        data => {
124
          this.claims = data.data;
125
          this.resultsNum= data.total;
126
          },
127
          err => {
128
            this.handleErrors(err);
129
          }
130
      );
131
    }else if(this.fetchBy =="Result"){
132
      this._claimService.getClaimsByResult(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types).subscribe(
133
        data => {
134
          this.claims = data.data;
135
          this.resultsNum= data.total;
136
          },
137
          err => {
138
            this.handleErrors(err);
139
          }
140
      );
141
    }else if(this.fetchBy =="Context"){
142
      this._claimService.getClaimsBycontext(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types).subscribe(
143
        data => {
144
          this.claims = data.data;
145
          this.resultsNum= null;
146
          this.resultsNum= data.total;//data.length; //TODO get the total results num
147
          },
148
          err => {
149
             this.handleErrors(err);
150
          }
151
      );
152
    }else{
153
      this._claimService.getClaims(this.size,this.page,this.keyword,this.sortby,this.descending, types).subscribe(
154
        data => {
155
          this.claims = data.data;
156
          this.resultsNum = null;
157
          this.resultsNum= data.total;//data.length; //TODO get the total results num
158
          },
159
          err => {
160
            this.handleErrors(err);
161
          }
162
      );
163
    }
164
  }
165
}
166
handleErrors(err){
167

    
168
  this.showErrorMessage = true;
169
  try{
170
    var error =  err.json()
171
      var code = error.code;
172
      if(code == 403){
173
        this.showErrorMessage = false;
174
        this.showForbiddenMessage = true;
175
      }
176
  }catch (e) {
177
        console.log("Couldn't parse answer as json")
178
        this.showErrorMessage = true;
179
  }
180

    
181
}
182

    
183
  goTo(page:number = 1){
184

    
185
    this.page = page;
186

    
187
    this.location.go(location.pathname,this.getParametersString());
188
    this.getClaims();
189
  }
190
  getParameters(){
191
    var params = {}
192
    if(this.myClaims){
193
       params={ page: this.page, size: this.size, types: this.entityTypes, keyword : this.keyword, sort: this.getSortby()  };
194
    }else{
195
      params={ page: this.page, size: this.size, types: this.entityTypes, fetchBy: this.fetchBy, fetchId:this.fetchId, keyword : this.keyword, sort: this.getSortby()  };
196
    }
197
    return params;
198
  }
199

    
200
  getParametersString(){
201
    var params='';
202
    params+=(this.page==1?"":(params.length>0?'&':'')+"page="+this.page);
203
    params+=(this.size==10?"":(params.length>0?'&':'')+"size="+this.size);
204
    // params+=(this.entityTypes==''?"":(params.length>0?'&':'')+"types="+this.entityTypes);
205
    var types="";
206
    for (var type of this.entityTypes){
207
         types+=(types.length>0?',':'')+type;
208
    }
209
    params+=(types.length>0)?"types="+types:"";
210

    
211
    if(this.isAdmin ){
212
      params+=(this.fetchBy=='All'?"":(params.length>0?'&':'')+"fetchBy="+this.fetchBy);
213
      params+=(this.fetchId==''?"":(params.length>0?'&':'')+"fetchId="+this.fetchId);
214
    }
215
    params+=(this. getSortby()=='datedesc'?"":(params.length>0?'&':'')+"sort="+this. getSortby());
216
    params+=(this.keyword==''?"":(params.length>0?'&':'')+"keyword="+this.keyword);
217
    return params;
218
  }
219
  changeSize(size: number ){
220
      this.goTo();
221
  }
222

    
223
  clearFilters(){
224
    this.keyword = '';
225
    this.inputkeyword = '';
226
    this.publicationCB = false;
227
    this.projectCB = false;
228
    this.datasetCB = false;
229
    this.softwareCB = false;
230
    this.contextCB = false;
231
    this.entityTypes = [];
232
    this.goTo();
233
   }
234

    
235
   changeOrderby(sortby:string){
236
     if(sortby==this.sortby){
237
       this.descending = !this.descending;
238
     }else{
239
       this.sortby = sortby;
240
       this.descending = false;
241
     }
242
     this.goTo();
243
   }
244
   setSortby(sortby:string){
245
     if(!sortby|| sortby == "datedesc"){
246
       this.descending = true;
247
       this.sortby = "date";
248
     }else if(sortby == "dateasc"){
249
       this.descending = false;
250
       this.sortby = "date";
251
     }else if(sortby == "userasc"){
252
       this.descending = false;
253
       this.sortby = "user";
254
     }else if(sortby == "userdesc"){
255
       this.descending = true;
256
       this.sortby = "user";
257
     }if(sortby =="sourceasc"){
258
       this.descending = false;
259
       this.sortby = "source";
260
     }else if(sortby == "sourcedesc"){
261
       this.descending = true;
262
       this.sortby = "source";
263
     }else if(sortby == "targetasc"){
264
       this.descending = false;
265
       this.sortby = "target";
266
     }else if(sortby == "targetdesc"){
267
       this.descending = true;
268
       this.sortby = "target";
269
     }
270
   }
271
   getSortby():string{
272
     if(this.descending){
273
       return this.sortby+"desc";
274
     }else{
275
       return this.sortby+"asc";
276
     }
277

    
278
   }
279
   changeType(){
280
     this.entityTypes = [];
281
     if(this.publicationCB){
282
       this.entityTypes.push('publication');
283
     }
284
     if(this.datasetCB){
285
       this.entityTypes.push('dataset');
286
     }
287
     if(this.softwareCB){
288
       this.entityTypes.push('software');
289
     }
290
     if(this.projectCB){
291
       this.entityTypes.push('project');
292
     }
293
     if(this.contextCB){
294
       this.entityTypes.push('context');
295
     }
296

    
297
     this.goTo();
298
   }
299
   setTypes(types:string){
300
     if(!types){
301
       return;
302
     }
303
     if(types.length > 0){
304
       this.entityTypes = [];
305
       if(types.indexOf("publication")!=-1){
306
         this.publicationCB = true;
307
         this.entityTypes.push("publication");
308
       }
309
       if(types.indexOf("dataset")!=-1){
310
         this.datasetCB = true;
311
         this.entityTypes.push("dataset");
312
       }
313
       if(types.indexOf("software")!=-1){
314
         this.softwareCB = true;
315
         this.entityTypes.push("software");
316
       }
317
       if(types.indexOf("project")!=-1){
318
         this.projectCB = true;
319
         this.entityTypes.push("project");
320
       }
321
       if(types.indexOf("context")!=-1){
322
         this.contextCB = true;
323
         this.entityTypes.push("context");
324
       }
325
     }
326
     if(this.publicationCB && this.datasetCB && this.softwareCB && this.contextCB && this.projectCB){
327
       this.entityTypes=[];
328
     }
329
   }
330
   changekeyword(){
331

    
332
     if(this.inputkeyword.length >= 3 || this.inputkeyword.length == 0 ){
333
       this.keyword = this.inputkeyword;
334
       this.page = 1;
335
       this.goTo();
336
     }
337

    
338
   }
339
   select(item:any,event){
340
     this.deleteMessage="";
341
     var value = event.currentTarget.checked;
342
     if(value){
343
       this.selected.push(item);
344
     }else{
345
       for (var _i = 0; _i < this.selected.length; _i++) {
346
           let claim = this.selected[_i];
347
           if(claim['id'] == item.id){
348
                 this.selected.splice(_i, 1);
349
           }
350
        }
351

    
352

    
353
     }
354
   }
355
   selectAll(event){
356
     var value = event.currentTarget.checked;
357
     if(value){
358
       this.selected = [];
359
      for (var _i = 0; _i < this.claims.length; _i++) {
360
         let claim = this.claims[_i];
361
         this.selected.push(claim);
362
       }
363
        this.deleteMessage = "";
364
    }else{
365
      this.selected = [];
366
      this.deleteMessage="";
367
    }
368
   }
369

    
370
   isSelected(id:string){
371
     for (var _i = 0; _i < this.selected.length; _i++) {
372
         let claim = this.selected[_i];
373
         if(claim['id'] == id){
374
              return true;
375
         }
376
      }
377
      return false;
378
   }
379

    
380

    
381
     confirmOpen(){
382
       if(this.selected.length <= 0){
383

    
384
       }else{
385
         this.alert.cancelButton = true;
386
         this.alert.okButton = true;
387
         this.alert.alertTitle = "Delete "+this.selected.length+" claim(s)";
388
         this.alert.message = this.selected.length+" claims will be deleted. Do you want to proceed? ";
389
         this.alert.okButtonText = "Yes";
390
         this.alert.cancelButtonText = "No";
391
         this.alert.open();
392
       }
393
     }
394
      confirmClose(data){
395
       this.delete();
396
     }
397
   delete(){
398
     this.deleteMessage="";
399
     this.loading.open();
400
     this.claimsDeleted = 0;
401
     var ids = [];
402
     for (var i = 0; i < this.selected.length; i++){
403
        var id  =this.selected[i].id;
404
        ids.push(id);
405
        // var selected  =this.selected[i].id;
406
        // console.warn("Deleting claim with id:"+id);
407
        //  this.deleteById(id);
408
         //TODO for multiple concurrent
409
        }
410
         this.batchDeleteById(ids);
411
    }
412

    
413
    deleteById(id:string){
414
      if(!Session.isValidAndRemove()){
415
        this.userValidMessage = "User session has expired. Please login again.";
416

    
417
      }else{
418
        var token=Session.getUserJwt();
419
         console.log("Deleting claim with id:"+id);
420
         // this._claimService.deleteClaimById(id);
421
         this._claimService.deleteClaimById(id).subscribe(
422
            res =>  {
423
              console.log('Delete response'+res.code );
424
              console.log("Deleted claim with id:"+ id);
425
              //remove this claim from the
426
             let newClaims=this.claims;
427
             for (var _i = 0; _i < this.claims.length; _i++) {
428
                 let claim = this.claims[_i];
429
                 if(claim['id'] == id){
430
                       newClaims.splice(_i, 1);
431
                 }
432
              }
433
              //TODO should call getClaims???
434
              this.claimsDeleted++;
435
              this.claims = newClaims;
436
              if(this.claimsDeleted == this.selected.length){
437
                this.resultsNum = this.resultsNum - this.selected.length;
438
                this.loading.close();
439
                this.selected = [];
440
              }
441

    
442

    
443
           });
444
         }
445
    }
446
    batchDeleteById(ids:string[]){
447
      if(!Session.isValidAndRemove()){
448
        this.userValidMessage = "User session has expired. Please login again.";
449

    
450
      }else{
451
        var token=Session.getUserJwt();
452
         console.warn("Deleting claim with ids:"+ids);
453
         this._claimService.deleteBulk(ids).subscribe(
454
            res =>  {
455
              console.info('Delete response'+res.code );
456
              console.warn("Deleted ids:"+ res.deletedIds);
457
              console.warn("Not found ids:"+ res.notFoundIds);
458
              //remove this claim from the
459
             let newClaims=this.claims;
460
             for(var id of res.deletedIds){
461
               for (var _i = 0; _i < this.claims.length; _i++) {
462
                   let claim = this.claims[_i];
463
                   if(claim['id'] == id){
464
                         newClaims.splice(_i, 1);
465
                   }
466
                }
467
                for (var _i = 0; _i < this.selected.length; _i++) {
468
                    let claim = this.selected[_i];
469
                    if(claim['id'] == id){
470
                          this.selected.splice(_i, 1);
471
                    }
472
                 }
473
              }
474
              this.claims = newClaims;
475
              this.resultsNum = this.resultsNum - res.deletedIds.length;
476
              this.loading.close();
477
              if(res.deletedIds.length>0){
478
                  this.deleteMessage=this.deleteMessage+'<div class = "uk-alert uk-alert-primary " >'+res.deletedIds.length+' claim(s) successfully deleted.</div>';
479
              }
480
              if(res.notFoundIds.length>0){
481
                  this.deleteMessage=this.deleteMessage+'<div class = "uk-alert uk-alert-warning " >'+res.notFoundIds.length+' claim(s) couldn\'t be deleted.</div>';
482
              }
483
           }, err => {
484
             console.log(err);
485
             this.showErrorMessage = true;
486
             this.loading.close();
487

    
488
           });
489
         }
490
    }
491
    pageChange($event) {
492
      var page:number = +$event.value
493
      this.goTo(page);
494
    }
495
}
(2-2/3)