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
        this.page = 1;
60
        this.goTo();
61
      });
62

    
63
    });
64

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

    
85
  navigateTo: string = "Claims";
86
  resultsNum: number ;
87
  claims: string[];
88

    
89
  @ViewChild (ModalLoading) loading : ModalLoading ;
90

    
91
  //checkboxes:
92
  publicationCB = false;
93
  datasetCB = false;
94
  softwareCB = false;
95
  contextCB = false;
96
  projectCB = false;
97
  entityTypes : string[] =[] ;
98

    
99
  descending = true;
100
  sortby = "date";
101

    
102
  selected=[];
103
  deleteMessage:string = "";
104
  showErrorMessage:boolean = false;
105
  showForbiddenMessage:boolean = false;
106
  userValidMessage:string = "";
107

    
108
  //params for pagingFormatter to use when navigate to page
109
  params;
110
  @ViewChild(AlertModal) alert;
111

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

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

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

    
196
}
197

    
198
  goTo(page:number = 1){
199

    
200
    this.page = page;
201

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

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

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

    
242
  clearFilters(){
243
    this.keyword = '';
244
    this.inputkeyword = '';
245
    this.publicationCB = false;
246
    this.projectCB = false;
247
    this.datasetCB = false;
248
    this.softwareCB = false;
249
    this.contextCB = false;
250
    this.entityTypes = [];
251
    this.goTo();
252
   }
253

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

    
297
   }
298
   changeType(){
299
     this.entityTypes = [];
300
     if(this.publicationCB){
301
       this.entityTypes.push('publication');
302
     }
303
     if(this.datasetCB){
304
       this.entityTypes.push('dataset');
305
     }
306
     if(this.softwareCB){
307
       this.entityTypes.push('software');
308
     }
309
     if(this.projectCB){
310
       this.entityTypes.push('project');
311
     }
312
     if(this.contextCB){
313
       this.entityTypes.push('context');
314
     }
315

    
316
     this.goTo();
317
   }
318
   setTypes(types:string){
319
     if(!types){
320
       return;
321
     }
322
     if(types.length > 0){
323
       this.entityTypes = [];
324
       if(types.indexOf("publication")!=-1){
325
         this.publicationCB = true;
326
         this.entityTypes.push("publication");
327
       }
328
       if(types.indexOf("dataset")!=-1){
329
         this.datasetCB = true;
330
         this.entityTypes.push("dataset");
331
       }
332
       if(types.indexOf("software")!=-1){
333
         this.softwareCB = true;
334
         this.entityTypes.push("software");
335
       }
336
       if(types.indexOf("project")!=-1){
337
         this.projectCB = true;
338
         this.entityTypes.push("project");
339
       }
340
       if(types.indexOf("context")!=-1){
341
         this.contextCB = true;
342
         this.entityTypes.push("context");
343
       }
344
     }
345
     if(this.publicationCB && this.datasetCB && this.softwareCB && this.contextCB && this.projectCB){
346
       this.entityTypes=[];
347
     }
348
   }
349
   changekeyword(){
350
     console.log("changekeyword")
351
     if(this.inputkeyword.length >= 3 || this.inputkeyword.length == 0 ){
352
       this.searchTermStream.next(this.keyword);
353

    
354

    
355
     }
356

    
357
   }
358
   select(item:any,event){
359
     this.deleteMessage="";
360
     var value = event.currentTarget.checked;
361
     if(value){
362
       this.selected.push(item);
363
     }else{
364
       for (var _i = 0; _i < this.selected.length; _i++) {
365
           let claim = this.selected[_i];
366
           if(claim['id'] == item.id){
367
                 this.selected.splice(_i, 1);
368
           }
369
        }
370

    
371

    
372
     }
373
   }
374
   selectAll(event){
375
     var value = event.currentTarget.checked;
376
     if(value){
377
       this.selected = [];
378
      for (var _i = 0; _i < this.claims.length; _i++) {
379
         let claim = this.claims[_i];
380
         this.selected.push(claim);
381
       }
382
        this.deleteMessage = "";
383
    }else{
384
      this.selected = [];
385
      this.deleteMessage="";
386
    }
387
   }
388

    
389
   isSelected(id:string){
390
     for (var _i = 0; _i < this.selected.length; _i++) {
391
         let claim = this.selected[_i];
392
         if(claim['id'] == id){
393
              return true;
394
         }
395
      }
396
      return false;
397
   }
398

    
399

    
400
     confirmOpen(){
401
       if(this.selected.length <= 0){
402

    
403
       }else{
404
         this.alert.cancelButton = true;
405
         this.alert.okButton = true;
406
         this.alert.alertTitle = "Delete "+this.selected.length+" claim(s)";
407
         this.alert.message = this.selected.length+" claims will be deleted. Do you want to proceed? ";
408
         this.alert.okButtonText = "Yes";
409
         this.alert.cancelButtonText = "No";
410
         this.alert.open();
411
       }
412
     }
413
      confirmClose(data){
414
       this.delete();
415
     }
416
   delete(){
417
     this.deleteMessage="";
418
     this.loading.open();
419
     this.claimsDeleted = 0;
420
     var ids = [];
421
     for (var i = 0; i < this.selected.length; i++){
422
        var id  =this.selected[i].id;
423
        ids.push(id);
424
        // var selected  =this.selected[i].id;
425
        // console.warn("Deleting claim with id:"+id);
426
        //  this.deleteById(id);
427
         //TODO for multiple concurrent
428
        }
429
         this.batchDeleteById(ids);
430
    }
431

    
432
    deleteById(id:string){
433
      if(!Session.isLoggedIn()){
434
        this.userValidMessage = "User session has expired. Please login again.";
435

    
436
      }else{
437
         console.log("Deleting claim with id:"+id);
438
         // this._claimService.deleteClaimById(id);
439
         this._claimService.deleteClaimById(id, this.properties.claimsAPIURL).subscribe(
440
            res =>  {
441
              console.log('Delete response'+res.code );
442
              console.log("Deleted claim with id:"+ id);
443
              //remove this claim from the
444
             let newClaims=this.claims;
445
             for (var _i = 0; _i < this.claims.length; _i++) {
446
                 let claim = this.claims[_i];
447
                 if(claim['id'] == id){
448
                       newClaims.splice(_i, 1);
449
                 }
450
              }
451
              //TODO should call getClaims???
452
              this.claimsDeleted++;
453
              this.claims = newClaims;
454
              if(this.claimsDeleted == this.selected.length){
455
                this.resultsNum = this.resultsNum - this.selected.length;
456
                this.loading.close();
457
                this.selected = [];
458
              }
459

    
460

    
461
           });
462
         }
463
    }
464
    batchDeleteById(ids:string[]){
465
      if(!Session.isLoggedIn()){
466
        this.userValidMessage = "User session has expired. Please login again.";
467

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

    
505
           });
506
         }
507
    }
508
    pageChange($event) {
509
      var page:number = +$event.value
510
      this.goTo(page);
511
    }
512
}
(2-2/3)