Project

General

Profile

1
import {Component, Input, ViewChild} from '@angular/core';
2
import {Location} from '@angular/common';
3
import {ActivatedRoute, Router} from '@angular/router';
4
import {Subject} from 'rxjs';
5
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
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
import {IndexInfoService} from "../../../utils/indexInfo.service";
14
import {ClaimDBRecord} from "../claimHelper.class";
15
import {Dates} from "../../../utils/string-utils.class";
16

    
17

    
18
@Component({
19
  selector: 'displayClaims',
20
  templateUrl: 'displayClaims.component.html',
21
  // providers: [ClaimsService]
22

    
23
})
24
export class DisplayClaimsComponent {
25
  properties: EnvProperties;
26
  public searchTermStream = new Subject<string>();
27
  sub: any;
28
  //string because comes as input from component directive
29
  @Input() enableDelete: boolean = false;
30
  @Input() showUserEmail: boolean = true;
31
  @Input() myClaims: boolean = false;
32
  @Input() isAdmin: boolean = false;
33
  page: number=1;
34
  size: number=10;
35
  sizes = [10, 20, 30, 50];
36
  keyword: string; // the keyword string to give to the request as parameter
37
  inputkeyword: string; // the string written in the input field (keyword=inputkeyword when its length is bigger than 3 and the user stops typing)
38
  types = ["All", "Project", "Context", "Result", "User"];
39
  @Input() fetchBy: string;
40
  @Input() fetchId: string;
41

    
42
  resultsNum: number;
43
  claims: ClaimDBRecord[];
44
  @Input() externalPortalUrl: string = null;
45
  @Input() claimsInfoURL: string;// ="https://www.openaire.eu/linking";
46
  lastIndexDate = null;
47

    
48
  @ViewChild(ModalLoading) loading: ModalLoading;
49

    
50
  //checkboxes:
51
  publicationCB = false;
52
  datasetCB = false;
53
  softwareCB = false;
54
  otherCB = false;
55
  contextCB = false;
56
  projectCB = false;
57
  entityTypes: string[] = [];
58

    
59
  descending = true;
60
  sortby = "date";
61

    
62
  selected = [];
63
  deleteMessage: string = "";
64
  showErrorMessage: boolean = false;
65
  showForbiddenMessage: boolean = false;
66
  userValidMessage: string = "";
67

    
68
  //params for pagingFormatter to use when navigate to page
69
  params;
70
  @ViewChild(AlertModal) alert;
71

    
72
  claimsDeleted: number = 0;
73
  @Input() communityId: string = null;
74

    
75
  url = null;
76

    
77
  constructor(private _claimService: ClaimsService, private route: ActivatedRoute, private _router: Router, private location: Location,
78
              private seoService: SEOService, private indexInfoService:IndexInfoService) {
79
  }
80

    
81
  ngOnInit() {
82
    this.route.data
83
      .subscribe((data: { envSpecific: EnvProperties }) => {
84
        this.properties = data.envSpecific;
85
        this.url = data.envSpecific.baseLink + this._router.url;
86
        this.indexInfoService.getLastIndexDate(this.properties).subscribe(res => {
87
          this.lastIndexDate = res;
88
        });
89
        this.sub = this.route.queryParams.subscribe(params => {
90
          this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this._router.url, false);
91

    
92
          if (this.myClaims) {
93
            this.fetchBy = "User";
94
            this.fetchId = Session.getUserEmail();
95
          } else {
96

    
97
            this.fetchBy = (this.fetchBy) ? this.fetchBy : params['fetchBy'];
98
            this.fetchBy = (this.types.indexOf(this.fetchBy) != -1) ? this.fetchBy : 'All';
99
            this.fetchId = (this.fetchId) ? this.fetchId : params['fetchId'];
100
            this.fetchId = this.fetchId ? this.fetchId : '';
101
          }
102

    
103
          let page = (params['page'] === undefined) ? 1 : +params['page'];
104
          let size = (params['size'] === undefined) ? 10 : +params['size'];
105

    
106
          this.keyword = (params['keyword'] ? params['keyword'] : "");
107
          this.inputkeyword = this.keyword;
108
          this.page = (page <= 0) ? 1 : page;
109
          this.size = (size <= 0) ? 10 : size;
110
          this.entityTypes = [];//(params['types']?params['types']:[]);
111
          this.setTypes(params['types']); // check the appropriate checkboxes
112
          this.setSortby(params['sort']);
113
          this.getClaims();
114
          this.searchTermStream
115
            .pipe(debounceTime(300),distinctUntilChanged())
116
            .subscribe((term: string) => {
117
              this.keyword = term;
118
              this.page = 1;
119
              this.goTo();
120
            });
121

    
122
        });
123
      });
124

    
125

    
126
  }
127

    
128
  ngOnDestroy() {
129
    this.sub.unsubscribe();
130
    //this.searchTermStreamSub.unsubscribe();
131
  }
132

    
133
  getClaims() {
134
    if (!Session.isLoggedIn()) {
135
      this.userValidMessage = "User session has expired. Please login again.";
136
      this._router.navigate(['/user-info'], {
137
        queryParams: {
138
          "errorCode": LoginErrorCodes.NOT_VALID,
139
          "redirectUrl": this._router.url
140
        }
141
      });
142
    } else {
143
      this.selected = [];
144
      let types = '';
145
      this.showErrorMessage = false;
146
      this.showForbiddenMessage = false;
147
      for (let type of this.entityTypes) {
148
        types += (types.length > 0 ? '&' : '') + "types=" + type;
149
      }
150
      if (this.fetchBy == "Project") {
151
        this._claimService.getClaimsByProject(this.size, this.page, this.fetchId, this.keyword, this.sortby, this.descending, types, this.properties.claimsAPIURL).subscribe(
152
          data => {
153
            this.manageAPIData(data);
154
          },
155
          err => {
156
            this.handleErrors(err);
157
            DisplayClaimsComponent.handleError("Error getting claims for project with id: " + this.fetchId, err);
158
          }
159
        );
160
      } else if (this.fetchBy == "User") {
161
        this._claimService.getClaimsByUser(this.size, this.page, this.fetchId, this.keyword, this.sortby, this.descending, types, this.properties.claimsAPIURL).subscribe(
162
          data => {
163
            this.manageAPIData(data);
164
          },
165
          err => {
166
            this.handleErrors(err);
167
            DisplayClaimsComponent.handleError("Error getting claims for user with id: " + this.fetchId, err);
168
          }
169
        );
170
      } else if (this.fetchBy == "Result") {
171
        this._claimService.getClaimsByResult(this.size, this.page, this.fetchId, this.keyword, this.sortby, this.descending, types, this.properties.claimsAPIURL).subscribe(
172
          data => {
173
            this.manageAPIData(data);
174
          },
175
          err => {
176
            this.handleErrors(err);
177
            DisplayClaimsComponent.handleError("Error getting claims for entity with id: " + this.fetchId, err);
178
          }
179
        );
180
      } else if (this.fetchBy == "Context") {
181
        this._claimService.getClaimsBycontext(this.size, this.page, this.fetchId, this.keyword, this.sortby, this.descending, types, this.properties.claimsAPIURL).subscribe(
182
          data => {
183
            this.manageAPIData(data);
184
          },
185
          err => {
186
            this.handleErrors(err);
187
            DisplayClaimsComponent.handleError("Error getting claims for context with id: " + this.fetchId, err);
188
          }
189
        );
190
      } else {
191
        this._claimService.getClaims(this.size, this.page, this.keyword, this.sortby, this.descending, types, this.properties.claimsAPIURL).subscribe(
192
          data => {
193
            this.manageAPIData(data);
194
          },
195
          err => {
196
            this.handleErrors(err);
197
            DisplayClaimsComponent.handleError("Error getting claims", err);
198
          }
199
        );
200
      }
201
    }
202
  }
203

    
204
  manageAPIData(data) {
205
    // let d = new Date();
206
    // let dateTomillis = d.getTime();
207
    // let millis24h: number = 24 * 3600000;
208
    // if(this.showLatestClaims && this.recentClaims.length == 0){
209
    //   this.recentClaims = [];
210
    //   for(var i=0;i<data.data.length;i++){
211
    //     var claimDate = new Date(data.data[i].date);
212
    //     var claimDateToMillis = claimDate.getTime()
213
    //     // console.log("Claim Date is:"+claimDateToMillis + " "+(dateTomillis - claimDateToMillis));
214
    //     if((dateTomillis - claimDateToMillis)<millis24h){
215
    //       // console.log("Claim in:"+  " "+(dateTomillis - claimDateToMillis)+" < " +(millis24h));
216
    //       this.recentClaims.push(data.data[i]);
217
    //     }
218
    //   }
219
    // }
220
    this.claims = data.data;
221
    this.resultsNum = data.total;
222

    
223

    
224
  }
225

    
226
  handleErrors(err) {
227

    
228
    this.showErrorMessage = true;
229
    try {
230
      let error = err.json();
231
      let code = error.code;
232
      if (code == 403) {
233
        this.showErrorMessage = false;
234
        this.showForbiddenMessage = true;
235
      }
236
    } catch (e) {
237
      //console.log("Couldn't parse answer as json")
238
      DisplayClaimsComponent.handleError("Error parsing answer as json", e);
239
      this.showErrorMessage = true;
240
    }
241

    
242
  }
243

    
244
  private static handleError(message: string, error) {
245
    console.error("Dispaly Claims (component): " + message, error);
246
  }
247

    
248
  goTo(page: number = 1) {
249

    
250
    this.page = page;
251

    
252
    this.location.go(location.pathname, this.getParametersString());
253
    this.getClaims();
254
  }
255
/*
256
  getParameters() {
257
    var params = {}
258
    if (this.myClaims) {
259
      params = {
260
        page: this.page,
261
        size: this.size,
262
        types: this.entityTypes,
263
        keyword: this.keyword,
264
        sort: this.getSortby()
265
      };
266
    } else {
267
      params = {
268
        page: this.page,
269
        size: this.size,
270
        types: this.entityTypes,
271
        fetchBy: this.fetchBy,
272
        fetchId: this.fetchId,
273
        keyword: this.keyword,
274
        sort: this.getSortby()
275
      };
276
    }
277
    return params;
278
  }*/
279

    
280
  getParametersString() {
281
    let params = '';
282
    params += (this.page == 1 ? "" : (params.length > 0 ? '&' : '') + "page=" + this.page);
283
    params += (this.size == 10 ? "" : (params.length > 0 ? '&' : '') + "size=" + this.size);
284
    // params+=(this.validEntityTypes==''?"":(params.length>0?'&':'')+"types="+this.validEntityTypes);
285
    let types = "";
286
    for (let type of this.entityTypes) {
287
      types += (types.length > 0 ? ',' : '') + type;
288
    }
289
    params += (types.length > 0) ? "types=" + types : "";
290

    
291
    if (this.isAdmin) {
292
      params += (this.fetchBy == 'All' ? "" : (params.length > 0 ? '&' : '') + "fetchBy=" + this.fetchBy);
293
      params += (this.fetchId == '' ? "" : (params.length > 0 ? '&' : '') + "fetchId=" + this.fetchId);
294
    }
295
    params += (this.getSortby() == 'datedesc' ? "" : (params.length > 0 ? '&' : '') + "sort=" + this.getSortby());
296
    params += (this.keyword == '' ? "" : (params.length > 0 ? '&' : '') + "keyword=" + this.keyword);
297
    if (this.communityId != null) {
298
      params += "&communityId=" + this.communityId;
299
    }
300
    return params;
301
  }
302

    
303
  changeSize() {
304
    this.goTo();
305
  }
306

    
307

    
308

    
309
  changeOrderby(sortby: string) {
310
    if (sortby == this.sortby) {
311
      this.descending = !this.descending;
312
    } else {
313
      this.sortby = sortby;
314
      this.descending = false;
315
    }
316
    this.goTo();
317
  }
318

    
319
  setSortby(sortby: string) {
320
    if (!sortby || sortby == "datedesc") {
321
      this.descending = true;
322
      this.sortby = "date";
323
    } else if (sortby == "dateasc") {
324
      this.descending = false;
325
      this.sortby = "date";
326
    } else if (sortby == "userasc") {
327
      this.descending = false;
328
      this.sortby = "user";
329
    } else if (sortby == "userdesc") {
330
      this.descending = true;
331
      this.sortby = "user";
332
    }
333
    if (sortby == "sourceasc") {
334
      this.descending = false;
335
      this.sortby = "source";
336
    } else if (sortby == "sourcedesc") {
337
      this.descending = true;
338
      this.sortby = "source";
339
    } else if (sortby == "targetasc") {
340
      this.descending = false;
341
      this.sortby = "target";
342
    } else if (sortby == "targetdesc") {
343
      this.descending = true;
344
      this.sortby = "target";
345
    }
346
  }
347

    
348
  getSortby(): string {
349
    if (this.descending) {
350
      return this.sortby + "desc";
351
    } else {
352
      return this.sortby + "asc";
353
    }
354

    
355
  }
356

    
357
  changeType() {
358
    this.entityTypes = [];
359
    if (this.publicationCB) {
360
      this.entityTypes.push('publication');
361
    }
362
    if (this.datasetCB) {
363
      this.entityTypes.push('dataset');
364
    }
365
    if (this.softwareCB) {
366
      this.entityTypes.push('software');
367
    }
368
    if (this.otherCB) {
369
      this.entityTypes.push('other');
370
    }
371
    if (this.projectCB) {
372
      this.entityTypes.push('project');
373
    }
374
    if (this.contextCB) {
375
      this.entityTypes.push('context');
376
    }
377

    
378
    this.goTo();
379
  }
380

    
381
  setTypes(types: string) {
382
    if (!types) {
383
      return;
384
    }
385
    if (types.length > 0) {
386
      this.entityTypes = [];
387
      if (types.indexOf("publication") != -1) {
388
        this.publicationCB = true;
389
        this.entityTypes.push("publication");
390
      }
391
      if (types.indexOf("dataset") != -1) {
392
        this.datasetCB = true;
393
        this.entityTypes.push("dataset");
394
      }
395
      if (types.indexOf("software") != -1) {
396
        this.softwareCB = true;
397
        this.entityTypes.push("software");
398
      }
399
      if (types.indexOf("other") != -1) {
400
        this.otherCB = true;
401
        this.entityTypes.push("other");
402
      }
403
      if (types.indexOf("project") != -1) {
404
        this.projectCB = true;
405
        this.entityTypes.push("project");
406
      }
407
      if (types.indexOf("context") != -1) {
408
        this.contextCB = true;
409
        this.entityTypes.push("context");
410
      }
411
    }
412
    if (this.publicationCB && this.datasetCB && this.softwareCB && this.otherCB && this.contextCB && this.projectCB) {
413
      this.entityTypes = [];
414
    }
415
  }
416

    
417
  changekeyword() {
418
    if (this.inputkeyword.length >= 3 || this.inputkeyword.length == 0) {
419
      this.searchTermStream.next(this.inputkeyword);
420

    
421

    
422
    }
423

    
424
  }
425

    
426
  select(item: any, event) {
427
    this.deleteMessage = "";
428
    let value = event.currentTarget.checked;
429
    if (value) {
430
      this.selected.push(item);
431
    } else {
432
      for (var _i = 0; _i < this.selected.length; _i++) {
433
        let claim = this.selected[_i];
434
        if (claim['id'] == item.id) {
435
          this.selected.splice(_i, 1);
436
        }
437
      }
438

    
439

    
440
    }
441
  }
442

    
443
  selectAll(event) {
444
    let value = event.currentTarget.checked;
445
    if (value) {
446
      this.selected = [];
447
      for (let _i = 0; _i < this.claims.length; _i++) {
448
        let claim = this.claims[_i];
449
        this.selected.push(claim);
450
      }
451
      this.deleteMessage = "";
452
    } else {
453
      this.selected = [];
454
      this.deleteMessage = "";
455
    }
456
  }
457

    
458
  isSelected(id: string) {
459
    for (let _i = 0; _i < this.selected.length; _i++) {
460
      let claim = this.selected[_i];
461
      if (claim['id'] == id) {
462
        return true;
463
      }
464
    }
465
    return false;
466
  }
467

    
468

    
469
  confirmOpen() {
470
    if (this.selected.length <= 0) {
471

    
472
    } else {
473
      this.alert.cancelButton = true;
474
      this.alert.okButton = true;
475
      this.alert.alertTitle ="";// "Delete " + this.selected.length + " links(s)";
476
      this.alert.okButtonLeft = false;
477
      // this.alert.message = this.selected.length + " links will be deleted. Do you want to proceed? ";
478
      this.alert.okButtonText = "Delete";
479
      this.alert.cancelButtonText = "Cancel";
480
      this.alert.open();
481
    }
482
  }
483

    
484
  confirmClose() {
485
    this.delete();
486
  }
487

    
488
  delete() {
489
    this.deleteMessage = "";
490
    this.loading.open();
491
    this.claimsDeleted = 0;
492
    let ids = [];
493
    for (let i = 0; i < this.selected.length; i++) {
494
      let id = this.selected[i].id;
495
      ids.push(id);
496

    
497
    }
498
    this.batchDeleteById(ids);
499
  }
500

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

    
553
        });
554
    }
555
  }
556

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

    
562
  isClaimAvailable(claim:ClaimDBRecord): boolean {
563
  //claim.target.collectedFrom == "infrastruct_::openaire" &&
564
    let lastUpdateDate = new Date( (this.lastIndexDate != null)?this.lastIndexDate:this.properties.lastIndexUpdate);
565
    let lastUpdateDateStr = Dates.getDateToString(lastUpdateDate);
566
    let claimDate = new Date( claim.date);
567
    let claimDateStr = Dates.getDateToString(claimDate);
568
    if (claimDateStr< lastUpdateDateStr) {
569
      return true;
570
    } else {
571
      if(claim.target.collectedFrom != "infrastruct_::openaire" && claim.indexed){
572
      //  check if direct index succeded
573
      return true
574
      }
575
    }
576
    return false;
577
  }
578
  totalPages(totalResults: number): number {
579
    let totalPages:any = totalResults/(this.size);
580
    if(!(Number.isInteger(totalPages))) {
581
      totalPages = (parseInt(totalPages, 10) + 1);
582
    }
583
    return totalPages;
584
  }
585
}
(2-2/3)