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

    
12

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

    
18
})
19
export class DisplayClaimsComponent {
20
  properties:EnvProperties;
21
  public searchTermStream = new Subject<string>();
22
  constructor (private _claimService: ClaimsService,  private route: ActivatedRoute, private _router:Router, private location: Location) {
23
   }
24

    
25
  ngOnInit() {
26
    this.route.data
27
      .subscribe((data: { envSpecific: EnvProperties }) => {
28
         this.properties = data.envSpecific;
29

    
30
      });
31
     this.sub = this.route.queryParams.subscribe(params => {
32
      if( this.myClaims){
33
          this.fetchBy = "User";
34
          this.fetchId = Session.getUserEmail();
35
      }else{
36

    
37
        this.fetchBy = (this.fetchBy)?this.fetchBy:params['fetchBy'];
38
        this.fetchBy = (this.types.indexOf(this.fetchBy) != -1)? this.fetchBy:'All';
39
        this.fetchId =(this.fetchId)?this.fetchId: params['fetchId'];
40
        this.fetchId = this.fetchId?this.fetchId:'';
41
      }
42

    
43
      let page = (params['page']=== undefined)?1:+params['page'];
44
      let size = (params['size']=== undefined)?10:+params['size'];
45

    
46
      this.keyword = (params['keyword']?params['keyword']:"");
47
      this.inputkeyword = this.keyword;
48
      this.page = ( page <= 0 ) ? 1 : page;
49
      this.size = ( size <= 0 ) ? 10 : size;
50
      this.entityTypes = []//(params['types']?params['types']:[]);
51
      this.setTypes(params['types']); // check the appropriate checkboxes
52
      this.setSortby(params['sort']);
53
      this.getClaims();
54
      this.searchTermStream
55
      .debounceTime(300).distinctUntilChanged()
56
      .subscribe((term: string) =>    {
57
        console.log("change!")
58
        this.keyword = this.inputkeyword;
59
        //console.log("keyword: "+this.keyword + " VS inputkeyword: "+this.inputkeyword);
60
        this.page = 1;
61
        this.goTo();
62
      });
63

    
64
    });
65

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

    
87
  navigateTo: string = "Claims";
88
  resultsNum: number ;
89
  claims: string[];
90

    
91
  @ViewChild (ModalLoading) loading : ModalLoading ;
92

    
93
  //checkboxes:
94
  publicationCB = false;
95
  datasetCB = false;
96
  softwareCB = false;
97
  otherCB = false;
98
  contextCB = false;
99
  projectCB = false;
100
  entityTypes : string[] =[] ;
101

    
102
  descending = true;
103
  sortby = "date";
104

    
105
  selected=[];
106
  deleteMessage:string = "";
107
  showErrorMessage:boolean = false;
108
  showForbiddenMessage:boolean = false;
109
  userValidMessage:string = "";
110

    
111
  //params for pagingFormatter to use when navigate to page
112
  params;
113
  @ViewChild(AlertModal) alert;
114

    
115
  claimsDeleted:number = 0;
116
  @Input() communityId:string = null;
117
  getClaims () {
118
    if(!Session.isLoggedIn()){
119
      this.userValidMessage = "User session has expired. Please login again.";
120

    
121
    }else{
122
    this.selected=[];
123
    var types = '';
124
    this.showErrorMessage = false;
125
    this.showForbiddenMessage = false;
126
    for (var type of this.entityTypes){
127
      types+=(types.length>0?'&':'')+"types="+type;
128
    }
129
    if(this.fetchBy =="Project" ){
130
      this._claimService.getClaimsByProject(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
131
        data => {
132
          this.claims = data.data;
133
          this.resultsNum= data.total;
134
          },
135
        err => {
136
          this.handleErrors(err);
137
        }
138
      );
139
    }else if(this.fetchBy =="User"){
140
      this._claimService.getClaimsByUser(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types,this.properties.claimsAPIURL).subscribe(
141
        data => {
142
          this.claims = data.data;
143
          this.resultsNum= data.total;
144
          },
145
          err => {
146
            this.handleErrors(err);
147
          }
148
      );
149
    }else if(this.fetchBy =="Result"){
150
      this._claimService.getClaimsByResult(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
151
        data => {
152
          this.claims = data.data;
153
          this.resultsNum= data.total;
154
          },
155
          err => {
156
            this.handleErrors(err);
157
          }
158
      );
159
    }else if(this.fetchBy =="Context"){
160
      this._claimService.getClaimsBycontext(this.size,this.page,this.fetchId,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
161
        data => {
162
          this.claims = data.data;
163
          this.resultsNum= null;
164
          this.resultsNum= data.total;//data.length; //TODO get the total results num
165
          },
166
          err => {
167
             this.handleErrors(err);
168
          }
169
      );
170
    }else{
171
      this._claimService.getClaims(this.size,this.page,this.keyword,this.sortby,this.descending, types, this.properties.claimsAPIURL).subscribe(
172
        data => {
173
          this.claims = data.data;
174
          this.resultsNum = null;
175
          this.resultsNum= data.total;//data.length; //TODO get the total results num
176
          },
177
          err => {
178
            this.handleErrors(err);
179
          }
180
      );
181
    }
182
  }
183
}
184
handleErrors(err){
185

    
186
  this.showErrorMessage = true;
187
  try{
188
    var error =  err.json()
189
      var code = error.code;
190
      if(code == 403){
191
        this.showErrorMessage = false;
192
        this.showForbiddenMessage = true;
193
      }
194
  }catch (e) {
195
        console.log("Couldn't parse answer as json")
196
        this.showErrorMessage = true;
197
  }
198

    
199
}
200

    
201
  goTo(page:number = 1){
202

    
203
    this.page = page;
204

    
205
    this.location.go(location.pathname,this.getParametersString());
206
    this.getClaims();
207
  }
208
  getParameters(){
209
    var params = {}
210
    if(this.myClaims){
211
       params={ page: this.page, size: this.size, types: this.entityTypes, keyword : this.keyword, sort: this.getSortby()  };
212
    }else{
213
      params={ page: this.page, size: this.size, types: this.entityTypes, fetchBy: this.fetchBy, fetchId:this.fetchId, keyword : this.keyword, sort: this.getSortby()  };
214
    }
215
    return params;
216
  }
217

    
218
  getParametersString(){
219
    var params='';
220
    params+=(this.page==1?"":(params.length>0?'&':'')+"page="+this.page);
221
    params+=(this.size==10?"":(params.length>0?'&':'')+"size="+this.size);
222
    // params+=(this.entityTypes==''?"":(params.length>0?'&':'')+"types="+this.entityTypes);
223
    var types="";
224
    for (var type of this.entityTypes){
225
         types+=(types.length>0?',':'')+type;
226
    }
227
    params+=(types.length>0)?"types="+types:"";
228

    
229
    if(this.isAdmin ){
230
      params+=(this.fetchBy=='All'?"":(params.length>0?'&':'')+"fetchBy="+this.fetchBy);
231
      params+=(this.fetchId==''?"":(params.length>0?'&':'')+"fetchId="+this.fetchId);
232
    }
233
    params+=(this. getSortby()=='datedesc'?"":(params.length>0?'&':'')+"sort="+this. getSortby());
234
    params+=(this.keyword==''?"":(params.length>0?'&':'')+"keyword="+this.keyword);
235
    console.log("AAAA"+this.communityId)
236
    if(this.communityId !=null){
237
      params+="&communityId="+this.communityId;
238
    }
239
    return params;
240
  }
241
  changeSize(size: number ){
242
      this.goTo();
243
  }
244

    
245
  clearFilters(){
246
    this.keyword = '';
247
    this.inputkeyword = '';
248
    this.publicationCB = false;
249
    this.projectCB = false;
250
    this.datasetCB = false;
251
    this.softwareCB = false;
252
    this.otherCB = false;
253
    this.contextCB = false;
254
    this.entityTypes = [];
255
    this.goTo();
256
   }
257

    
258
   changeOrderby(sortby:string){
259
     if(sortby==this.sortby){
260
       this.descending = !this.descending;
261
     }else{
262
       this.sortby = sortby;
263
       this.descending = false;
264
     }
265
     this.goTo();
266
   }
267
   setSortby(sortby:string){
268
     if(!sortby|| sortby == "datedesc"){
269
       this.descending = true;
270
       this.sortby = "date";
271
     }else if(sortby == "dateasc"){
272
       this.descending = false;
273
       this.sortby = "date";
274
     }else if(sortby == "userasc"){
275
       this.descending = false;
276
       this.sortby = "user";
277
     }else if(sortby == "userdesc"){
278
       this.descending = true;
279
       this.sortby = "user";
280
     }if(sortby =="sourceasc"){
281
       this.descending = false;
282
       this.sortby = "source";
283
     }else if(sortby == "sourcedesc"){
284
       this.descending = true;
285
       this.sortby = "source";
286
     }else if(sortby == "targetasc"){
287
       this.descending = false;
288
       this.sortby = "target";
289
     }else if(sortby == "targetdesc"){
290
       this.descending = true;
291
       this.sortby = "target";
292
     }
293
   }
294
   getSortby():string{
295
     if(this.descending){
296
       return this.sortby+"desc";
297
     }else{
298
       return this.sortby+"asc";
299
     }
300

    
301
   }
302
   changeType(){
303
     this.entityTypes = [];
304
     if(this.publicationCB){
305
       this.entityTypes.push('publication');
306
     }
307
     if(this.datasetCB){
308
       this.entityTypes.push('dataset');
309
     }
310
     if(this.softwareCB){
311
       this.entityTypes.push('software');
312
     }
313
     if(this.otherCB){
314
       this.entityTypes.push('other');
315
     }
316
     if(this.projectCB){
317
       this.entityTypes.push('project');
318
     }
319
     if(this.contextCB){
320
       this.entityTypes.push('context');
321
     }
322

    
323
     this.goTo();
324
   }
325
   setTypes(types:string){
326
     if(!types){
327
       return;
328
     }
329
     if(types.length > 0){
330
       this.entityTypes = [];
331
       if(types.indexOf("publication")!=-1){
332
         this.publicationCB = true;
333
         this.entityTypes.push("publication");
334
       }
335
       if(types.indexOf("dataset")!=-1){
336
         this.datasetCB = true;
337
         this.entityTypes.push("dataset");
338
       }
339
       if(types.indexOf("software")!=-1){
340
         this.softwareCB = true;
341
         this.entityTypes.push("software");
342
       }
343
       if(types.indexOf("other")!=-1){
344
         this.otherCB = true;
345
         this.entityTypes.push("other");
346
       }
347
       if(types.indexOf("project")!=-1){
348
         this.projectCB = true;
349
         this.entityTypes.push("project");
350
       }
351
       if(types.indexOf("context")!=-1){
352
         this.contextCB = true;
353
         this.entityTypes.push("context");
354
       }
355
     }
356
     if(this.publicationCB && this.datasetCB && this.softwareCB && this.otherCB && this.contextCB && this.projectCB){
357
       this.entityTypes=[];
358
     }
359
   }
360
   changekeyword(){
361
     console.log("changekeyword")
362
     if(this.inputkeyword.length >= 3 || this.inputkeyword.length == 0 ){
363
       this.searchTermStream.next(this.inputkeyword);
364

    
365

    
366
     }
367

    
368
   }
369
   select(item:any,event){
370
     this.deleteMessage="";
371
     var value = event.currentTarget.checked;
372
     if(value){
373
       this.selected.push(item);
374
     }else{
375
       for (var _i = 0; _i < this.selected.length; _i++) {
376
           let claim = this.selected[_i];
377
           if(claim['id'] == item.id){
378
                 this.selected.splice(_i, 1);
379
           }
380
        }
381

    
382

    
383
     }
384
   }
385
   selectAll(event){
386
     var value = event.currentTarget.checked;
387
     if(value){
388
       this.selected = [];
389
      for (var _i = 0; _i < this.claims.length; _i++) {
390
         let claim = this.claims[_i];
391
         this.selected.push(claim);
392
       }
393
        this.deleteMessage = "";
394
    }else{
395
      this.selected = [];
396
      this.deleteMessage="";
397
    }
398
   }
399

    
400
   isSelected(id:string){
401
     for (var _i = 0; _i < this.selected.length; _i++) {
402
         let claim = this.selected[_i];
403
         if(claim['id'] == id){
404
              return true;
405
         }
406
      }
407
      return false;
408
   }
409

    
410

    
411
     confirmOpen(){
412
       if(this.selected.length <= 0){
413

    
414
       }else{
415
         this.alert.cancelButton = true;
416
         this.alert.okButton = true;
417
         this.alert.alertTitle = "Delete "+this.selected.length+" claim(s)";
418
         this.alert.message = this.selected.length+" claims will be deleted. Do you want to proceed? ";
419
         this.alert.okButtonText = "Yes";
420
         this.alert.cancelButtonText = "No";
421
         this.alert.open();
422
       }
423
     }
424
      confirmClose(data){
425
       this.delete();
426
     }
427
   delete(){
428
     this.deleteMessage="";
429
     this.loading.open();
430
     this.claimsDeleted = 0;
431
     var ids = [];
432
     for (var i = 0; i < this.selected.length; i++){
433
        var id  =this.selected[i].id;
434
        ids.push(id);
435
        // var selected  =this.selected[i].id;
436
        // console.warn("Deleting claim with id:"+id);
437
        //  this.deleteById(id);
438
         //TODO for multiple concurrent
439
        }
440
         this.batchDeleteById(ids);
441
    }
442

    
443
    deleteById(id:string){
444
      if(!Session.isLoggedIn()){
445
        this.userValidMessage = "User session has expired. Please login again.";
446

    
447
      }else{
448
         console.log("Deleting claim with id:"+id);
449
         // this._claimService.deleteClaimById(id);
450
         this._claimService.deleteClaimById(id, this.properties.claimsAPIURL).subscribe(
451
            res =>  {
452
              console.log('Delete response'+res.code );
453
              console.log("Deleted claim with id:"+ id);
454
              //remove this claim from the
455
             let newClaims=this.claims;
456
             for (var _i = 0; _i < this.claims.length; _i++) {
457
                 let claim = this.claims[_i];
458
                 if(claim['id'] == id){
459
                       newClaims.splice(_i, 1);
460
                 }
461
              }
462
              //TODO should call getClaims???
463
              this.claimsDeleted++;
464
              this.claims = newClaims;
465
              if(this.claimsDeleted == this.selected.length){
466
                this.resultsNum = this.resultsNum - this.selected.length;
467
                this.loading.close();
468
                this.selected = [];
469
              }
470

    
471

    
472
           });
473
         }
474
    }
475
    batchDeleteById(ids:string[]){
476
      if(!Session.isLoggedIn()){
477
        this.userValidMessage = "User session has expired. Please login again.";
478

    
479
      }else{
480
         console.warn("Deleting claim with ids:"+ids);
481
         this._claimService.deleteBulk(ids,this.properties.claimsAPIURL).subscribe(
482
            res =>  {
483
              console.info('Delete response'+res.code );
484
              console.warn("Deleted ids:"+ res.deletedIds);
485
              console.warn("Not found ids:"+ res.notFoundIds);
486
              //remove this claim from the
487
             let newClaims=this.claims;
488
             for(var id of res.deletedIds){
489
               for (var _i = 0; _i < this.claims.length; _i++) {
490
                   let claim = this.claims[_i];
491
                   if(claim['id'] == id){
492
                         newClaims.splice(_i, 1);
493
                   }
494
                }
495
                for (var _i = 0; _i < this.selected.length; _i++) {
496
                    let claim = this.selected[_i];
497
                    if(claim['id'] == id){
498
                          this.selected.splice(_i, 1);
499
                    }
500
                 }
501
              }
502
              this.claims = newClaims;
503
              this.resultsNum = this.resultsNum - res.deletedIds.length;
504
              this.loading.close();
505
              if(res.deletedIds.length>0){
506
                  this.deleteMessage=this.deleteMessage+'<div class = "uk-alert uk-alert-primary " >'+res.deletedIds.length+' claim(s) successfully deleted.</div>';
507
              }
508
              if(res.notFoundIds.length>0){
509
                  this.deleteMessage=this.deleteMessage+'<div class = "uk-alert uk-alert-warning " >'+res.notFoundIds.length+' claim(s) couldn\'t be deleted.</div>';
510
              }
511
           }, err => {
512
             console.log(err);
513
             this.showErrorMessage = true;
514
             this.loading.close();
515

    
516
           });
517
         }
518
    }
519
    pageChange($event) {
520
      var page:number = +$event.value
521
      this.goTo(page);
522
    }
523
}
(2-2/3)