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
  contextCB = false;
79
  projectCB = false;
80
  entityTypes : string[] =[] ;
81

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

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

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

    
95
  claimsDeleted:number = 0;
96

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

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

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

    
180
}
181

    
182
  goTo(page:number = 1){
183

    
184
    this.page = page;
185

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

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

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

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

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

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

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

    
323
     if(this.inputkeyword.length >= 3 || this.inputkeyword.length == 0 ){
324
       this.keyword = this.inputkeyword;
325
       this.page = 1;
326
       this.goTo();
327
     }
328

    
329
   }
330
   select(item:any,event){
331
     this.deleteMessage="";
332
     var value = event.currentTarget.checked;
333
     if(value){
334
       this.selected.push(item);
335
     }else{
336
       for (var _i = 0; _i < this.selected.length; _i++) {
337
           let claim = this.selected[_i];
338
           if(claim['id'] == item.id){
339
                 this.selected.splice(_i, 1);
340
           }
341
        }
342

    
343

    
344
     }
345
   }
346
   selectAll(event){
347
     var value = event.currentTarget.checked;
348
     if(value){
349
       this.selected = [];
350
      for (var _i = 0; _i < this.claims.length; _i++) {
351
         let claim = this.claims[_i];
352
         this.selected.push(claim);
353
       }
354
        this.deleteMessage = "";
355
    }else{
356
      this.selected = [];
357
      this.deleteMessage="";
358
    }
359
   }
360

    
361
   isSelected(id:string){
362
     for (var _i = 0; _i < this.selected.length; _i++) {
363
         let claim = this.selected[_i];
364
         if(claim['id'] == id){
365
              return true;
366
         }
367
      }
368
      return false;
369
   }
370

    
371

    
372
     confirmOpen(){
373
       if(this.selected.length <= 0){
374

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

    
404
    deleteById(id:string){
405
      if(!Session.isValidAndRemove()){
406
        this.userValidMessage = "User session has expired. Please login again.";
407

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

    
433

    
434
           });
435
         }
436
    }
437
    batchDeleteById(ids:string[]){
438
      if(!Session.isValidAndRemove()){
439
        this.userValidMessage = "User session has expired. Please login again.";
440

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

    
479
           });
480
         }
481
    }
482
    pageChange($event) {
483
      var page:number = +$event.value
484
      this.goTo(page);
485
    }
486
}
(2-2/3)