Project

General

Profile

1
import {Component, ViewChild, ViewChildren, QueryList, Input, ViewEncapsulation} from '@angular/core';
2
import {Location}                    from '@angular/common';
3
import {ActivatedRoute, Params, Router}      from '@angular/router';
4
import {Title, Meta}                 from '@angular/platform-browser';
5

    
6
import {DataTableDirective}          from 'angular-datatables';
7
import {Observable,  Subject }                  from 'rxjs';
8

    
9
import{EnvProperties}                from '../../utils/properties/env-properties';
10
import {ErrorCodes}                  from '../../utils/properties/errorCodes';
11
import {ErrorMessagesComponent}      from '../../utils/errorMessages.component';
12

    
13
import {ClaimsDatatablePipe}         from '../../utils/pipes/claimsDatatable.pipe';
14

    
15
import {RouterHelper}                from '../../utils/routerHelper.class';
16

    
17
import {ModalSelect}                 from '../../utils/modal/selectModal.component';
18
import {ModalLoading}                from '../../utils/modal/loading.component';
19

    
20
import {ClaimsByTokenService}        from './claimsByToken.service';
21

    
22
import {Session}                     from '../../login/utils/helper.class';
23
import {LoginErrorCodes}             from '../../login/utils/guardHelper.class';
24

    
25

    
26
@Component({
27
    selector: 'claims-project-manager',
28
    templateUrl: 'claimsByToken.component.html',
29
    styles: [`
30
      #table1_info, #table1_paginate,  #table1_length,  #table1_filter,
31
      #table2_info, #table2_paginate,  #table2_length,  #table2_filter{
32
        display: none;
33
      }
34

    
35
    `],
36
    encapsulation: ViewEncapsulation.None // this used in order styles to work
37

    
38
})
39
export class ClaimsByTokenComponent {
40
  public openaireId: string = "";
41
  public sub: any;
42
  public project: any;
43
  private claims:any = [];
44
  public pending_claims: any = [];
45
  public curated_claims: any = [];
46
  public selectedRight_PendingMode: Set<string>;
47
  public selectedWrong_PendingMode: Set<string>;
48
  public selectedRight_CuratedMode: Set<string>;
49
  public selectedWrong_CuratedMode: Set<string>;
50
  public editable: Set<number>;
51
  public contact_person: string[] = ["Konstantina", "Argiro", "Katerina"];
52

    
53
  private errorCodes: ErrorCodes;
54
  private errorMessages: ErrorMessagesComponent;
55
  public pending_status: number;
56
  public curated_status: number;
57

    
58
  // when 'valid' show proper claims, when 'invalid' show no matched entry-wanna retry
59
  public accessStatus: string;// = "empty";
60

    
61
  public mode: string = "pending";
62
  public showTables: boolean = true;
63
  public rowsOnPage = 5;
64
  public sortOrder = "asc";
65
  public keyword1:string = "";
66
  public keyword2:string = "";
67

    
68
  public activePendingPage:any = {page: 1};
69
  public totalPendingResults:any = {count: 0};
70
  public activeCuratedPage:any = {page: 1};
71
  public totalCuratedResults:any = {count: 0};
72

    
73
  dtTrigger: Subject<any>[] = [];
74
  private triggered: boolean = false;
75

    
76
  dtOptions: DataTables.Settings[] = [];
77
  @ViewChildren(DataTableDirective)
78
  dtElements: QueryList<any>;
79
  //@ViewChild("table1") table1: DataTableDirective;
80
  //@ViewChild("table2") table2: DataTableDirective;
81

    
82
  @ViewChild (ModalSelect) selectModal : ModalSelect;
83
  @ViewChild (ModalLoading) loading : ModalLoading ;
84

    
85
  properties:EnvProperties;
86

    
87
  public routerHelper:RouterHelper = new RouterHelper();
88

    
89
  constructor (private route: ActivatedRoute,
90
               private _router: Router,
91
               private claimsByTokenService: ClaimsByTokenService,
92
               private _meta: Meta, private _title: Title) {
93
      this.errorCodes = new ErrorCodes();
94
      this.errorMessages = new ErrorMessagesComponent();
95
      this.pending_status = this.errorCodes.LOADING;
96
      this.curated_status = this.errorCodes.LOADING;
97
  }
98
  ngOnInit() {
99
    this.route.data
100
      .subscribe((data: { envSpecific: EnvProperties }) => {
101
         this.properties = data.envSpecific;
102

    
103
      });
104
    this.sub =  this.route.queryParams.subscribe(params => {
105
        this.mode = "pending";
106
        this.openaireId = params['openaireId'];
107
        this.selectedRight_PendingMode = new Set<string>();
108
        this.selectedWrong_PendingMode = new Set<string>();
109
        this.selectedRight_CuratedMode = new Set<string>();
110
        this.selectedWrong_CuratedMode = new Set<string>();
111
        this.editable = new Set<number>();
112
        this.validateJWTandToken();
113
        this.updateTitle("Claims For Project Managers");
114
      }
115
    );
116

    
117
    this.dtOptions[0] = {
118
      //"paging": false,
119
      //"searching": false,
120
      //"lengthChange": false,
121
      "pageLength": this.rowsOnPage,
122
      "columnDefs": [ {
123
            "type": "date",
124
            "targets": 2
125
        } ],
126
      "order": [[ 2, 'desc' ]]
127
      //"pagingType": 'full_numbers',
128
      /*"language": {
129
          "search": "",
130
          "searchPlaceholder": "Search projects..."
131
      }*/
132
    };
133

    
134
    this.dtOptions[1] = {
135
      "pageLength": this.rowsOnPage,
136
      "columnDefs": [ {
137
            "type": "date",
138
            "targets": [2,4]
139
        } ],
140
      "order": [[ 4, 'desc' ]]
141
    };
142

    
143

    
144
    this.dtTrigger[0] = new Subject<any>();
145
    this.dtTrigger[1] = new Subject<any>();
146
  }
147

    
148
  ngAfterViewInit(): void {
149
     $.fn['dataTable'].ext.search.push((settings, data, dataIndex) => {
150
        if(settings.sTableId == 'table1') {
151
          if (this.filterData(data, this.keyword1)) {
152
            return true;
153
          }
154
          return false;
155
        } else if(settings.sTableId == 'table2') {
156
          if (this.filterData(data, this.keyword2)) {
157
            return true;
158
          }
159
          return false;
160
        }
161
      });
162
  }
163

    
164
  ngOnDestroy(): void {
165
    $.fn['dataTable'].ext.search.pop();
166
    // Do not forget to unsubscribe the event
167
    this.dtTrigger[0].unsubscribe();
168
    this.dtTrigger[1].unsubscribe();
169
  }
170

    
171
  /*
172
  Trigger a table draw in order to get the initial filtering
173
  */
174
  triggerInitialLoad(){
175
      this.triggered = true;
176
      //console.info("triggerInitialLoad");
177
      setTimeout(function(){
178
        /*var table1 = <any>$('#table1').DataTable();
179
        table1.page( 0 ).draw( false );
180

    
181
        var table2 = <any>$('#table2').DataTable();
182
        table2.page( 0 ).draw( false );*/
183
      }, 500);
184
      setTimeout(() => {
185
        this.dtTrigger[0].next();
186
        this.dtTrigger[1].next();
187
      });
188

    
189
  }
190

    
191
  rerender(): void {
192
    //console.info("RERENDER");
193
    this.dtElements.forEach((dtElement: DataTableDirective, index: number) => {
194
      dtElement.dtInstance.then((dtInstance: any) => {
195
        // Destroy the table first
196
        dtInstance.destroy();
197

    
198
        // Call the dtTrigger to rerender again
199
        this.dtTrigger[index].next();
200
      });
201
    });
202
  }
203

    
204
  filterData(row: any, query: string) {
205
    if(!Session.isLoggedIn()){
206
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
207
    } else {
208
      let returnValue: boolean = false;
209

    
210
      if(query) {
211
        for(var i=0; i <3; i++){
212
          var r= this.filterQuery(row[i], query);
213
          if(r) {
214
            returnValue = true;
215
            break;
216
          }
217
        }
218

    
219
        if(!returnValue) {
220
          return false;
221
        }
222
      }
223

    
224
      return true;
225
    }
226
  }
227

    
228
  filterQuery(data, query){
229
    if(data.toLowerCase().indexOf(query.toLowerCase()) > -1){
230
      return true;
231
    }else{
232
      return false;
233
    }
234
  }
235

    
236
refreshTable(page:number, whichTable: string) {
237
  if(!Session.isLoggedIn()){
238
    this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
239
  } else {
240
    if(whichTable == "pending") {
241
      var table = $('#table1').DataTable();
242
      table.page( page - 1  ).draw( false );
243

    
244
      var info = table.page.info();
245

    
246
      this.activePendingPage.page = page;//$event.value;
247
      this.totalPendingResults.count = info.recordsDisplay;
248
    } else if(whichTable == 'curated') {
249
      var table = $('#table2').DataTable();
250
      table.page( page - 1  ).draw( false );
251

    
252
      var info = table.page.info();
253

    
254
      this.activeCuratedPage.page = page;//$event.value;
255
      this.totalCuratedResults.count = info.recordsDisplay;
256
    }
257
  }
258

    
259
  //table.mfActivePage=$event.value;
260
  //table.setPage(table.mfActivePage, this.rowsOnPage);
261
}
262

    
263
  validateJWTandToken() {
264
    if(!Session.isLoggedIn()){
265
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
266
    } else {
267
      if(this.openaireId) {
268
        this.pending_status = this.errorCodes.LOADING;
269
        this.curated_status = this.errorCodes.LOADING;
270

    
271
        this.showTables = false;
272
        this.pending_claims = [];
273
        this.curated_claims = [];
274

    
275
        this.activePendingPage.page = 1;
276
        this.totalPendingResults.count = 0;
277
        this.activeCuratedPage.page = 1;
278
        this.totalCuratedResults.count = 0;
279

    
280
        this.claimsByTokenService.getClaims(this.openaireId,  this.properties.claimsAPIURL).subscribe(
281
            data => {
282
              //this.closeLoading();
283
              this.accessStatus = "valid";
284
                this.claims = data.data;
285
                for(let claim of this.claims) {
286
                  if(claim.targetType == "project") {
287
                    this.project = claim.target;
288
                  } else {
289
                    this.project = claim.source;
290
                  }
291
                  if(claim.curatedBy) {
292
                    this.curated_claims.push(claim);
293
                  } else {
294
                    this.pending_claims.push(claim);
295
                  }
296
                }
297

    
298
                this.totalPendingResults.count = this.pending_claims.length;
299
                this.totalCuratedResults.count = this.curated_claims.length;
300

    
301
                if(this.project) {
302
                  this.updateTitle("Claims For Project Managers - "+this.project.name);
303
                }
304
                this.showTables = true;
305

    
306
                if(!this.triggered) {
307
                  //console.info("initial load");
308
                  this.triggerInitialLoad();
309
                } else {
310
                  //console.info("rerender");
311
                  var table1 = $('#table1').DataTable();
312
                  table1.clear();
313

    
314
                  var table2 = $('#table2').DataTable();
315
                  table2.clear();
316

    
317
                  this.rerender();
318
                }
319

    
320
                this.pending_status = this.errorCodes.DONE;
321
                this.curated_status = this.errorCodes.DONE;
322
            },
323
            err => {
324
              this.handleError("Error getting claims for openaire id: "+this.openaireId, err);
325
              this.pending_status = this.errorMessages.getErrorCode(err.status);
326
              this.curated_status = this.pending_status;
327

    
328
              /*if(err.status == '404') {
329
                this.pending_status = this.errorCodes.NOT_FOUND;
330
                this.curated_status = this.errorCodes.NOT_FOUND;
331
              } else if(err.status == '500') {
332
                this.pending_status = this.errorCodes.ERROR;
333
                this.curated_status = this.errorCodes.ERROR;
334
              } else {
335
                this.pending_status = this.errorCodes.NOT_AVAILABLE;
336
                this.curated_status = this.errorCodes.NOT_AVAILABLE;
337
              }*/
338
              this.showTables = true;
339

    
340
              if(!this.triggered) {
341
                this.triggerInitialLoad();
342
              } else {
343
                var table1 = $('#table1').DataTable();
344
                table1.clear();
345

    
346
                var table2 = $('#table2').DataTable();
347
                table2.clear();
348

    
349
                this.rerender();
350
              }
351

    
352
              this.accessStatus = "invalid";
353
              //console.log(err);
354
            }
355
          );
356
      } else {
357
          this.accessStatus = "invalid";
358
      }
359
    }
360
  }
361

    
362
  selectApprove(id:string, event, mode: string) {
363
    if(!Session.isLoggedIn()){
364
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
365
    } else {
366
      var value = event.currentTarget.checked;
367
      if(value){
368
        if(mode == "pending") {
369
          this.selectedRight_PendingMode.add(id);
370
          this.selectedWrong_PendingMode.delete(id);
371
        } else {
372
          this.selectedRight_CuratedMode.add(id);
373
          this.selectedWrong_CuratedMode.delete(id);
374
        }
375
      }else{
376
        if(mode == "pending") {
377
          this.selectedRight_PendingMode.delete(id);
378
        }
379
        // } else {
380
        //   this.selectedRight_CuratedMode.delete(id);
381
        //   this.selectedWrong_CuratedMode.add(id);
382
        // }
383
      }
384
    }
385
  }
386

    
387
  selectDisapprove(id:string, event, mode: string) {
388
    if(!Session.isLoggedIn()){
389
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
390
    } else {
391
      var value = event.currentTarget.checked;
392
      if(value){
393
        if(mode == "pending") {
394
          this.selectedWrong_PendingMode.add(id);
395
          this.selectedRight_PendingMode.delete(id);
396
        } else {
397
          this.selectedWrong_CuratedMode.add(id);
398
          this.selectedRight_CuratedMode.delete(id);
399
        }
400
      }else{
401
        if(mode == "pending") {
402
          this.selectedWrong_PendingMode.delete(id);
403
        }
404
        // } else {
405
        //   this.selectedWrong_CuratedMode.delete(id);
406
        //   this.selectedRight_CuratedMode.add(id);
407
        // }
408
      }
409
    }
410
  }
411

    
412
  isSelected(id:string, set:Set<string>) {
413
    return set.has(id);
414
  }
415
/*
416
  isSelectedWrong(id:string) {
417
    return this.selectedWrong.has(id);
418
  }
419
*/
420
  isRight_CuratedMode(claim: any) {
421
    if(this.isSelected(claim.id, this.selectedRight_CuratedMode)) {
422
      return true;
423
    } else if(claim.approved == true && !this.isSelected(claim.id, this.selectedWrong_CuratedMode)) {
424
      return true;
425
    }
426

    
427
    return false;
428
  }
429

    
430
  isWrong_CuratedMode(claim: any) {
431
    if(this.isSelected(claim.id, this.selectedWrong_CuratedMode)) {
432
      return true;
433
    } else if(claim.approved == false && !this.isSelected(claim.id, this.selectedRight_CuratedMode)) {
434
      return true;
435
    }
436

    
437
    return false;
438
  }
439

    
440
  cancelEditOfCuration(claim: any) {
441
    if(!Session.isLoggedIn()){
442
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
443
    } else {
444
      if(claim.approved) {
445
        //this.selectedRight_CuratedMode.add(claim.id);
446
        this.selectedWrong_CuratedMode.delete(claim.id);
447
      } else {
448
        this.selectedRight_CuratedMode.delete(claim.id);
449
        //this.selectedWrong_CuratedMode.add(claim.id);
450
      }
451
    }
452
  }
453

    
454
  saveEdited(claim: any, editable_index: number) {
455
    if(!Session.isLoggedIn()){
456
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
457
    } else {
458
      this.curated_status = this.errorCodes.LOADING;
459

    
460
      let approved: boolean = this.isRight_CuratedMode(claim);
461

    
462
      if(approved == claim.approved) {
463
        this.selectedRight_CuratedMode.delete(claim.id);
464
        this.selectedWrong_CuratedMode.delete(claim.id);
465
        this.editable.delete(editable_index);
466

    
467
        this.curated_status = this.errorCodes.DONE;
468
      } else {
469
        let claimCurationInfo: {"id": string, "approved": boolean} = {"id": claim.id, "approved": approved};
470

    
471
        this.claimsByTokenService.updateClaimCuration(claimCurationInfo, this.properties.claimsAPIURL).subscribe(
472
            data => {
473
              this.selectedRight_CuratedMode.delete(claim.id);
474
              this.selectedWrong_CuratedMode.delete(claim.id);
475
              this.editable.delete(editable_index);
476

    
477
              this.validateJWTandToken();
478
            },
479
            err => {
480
              //console.log(err);
481
              this.handleError("Error updating claim curation: "+JSON.stringify(claimCurationInfo), err);
482
              this.curated_status = this.errorCodes.NOT_SAVED;
483
            }
484
          );
485
      }
486
    }
487
  }
488

    
489
  saveChanges() {
490
    if(!Session.isLoggedIn()){
491
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
492
    } else {
493
      this.pending_status = this.errorCodes.LOADING;
494
      //this.openLoading();
495
      //console.info("Changes Saved!, right-wrong", this.selectedRight_PendingMode, this.selectedWrong_PendingMode);
496
      this.claimsByTokenService.updateClaimsCuration(this.selectedRight_PendingMode, this.selectedWrong_PendingMode, this.properties.claimsAPIURL).subscribe(
497
          data => {
498
            //this.closeLoading();
499
            this.mode = "curated";
500
            this.clearCheckboxes();
501
            this.validateJWTandToken();
502
          },
503
          err => {
504
            //this.closeLoading();
505
            //console.log(err);
506
            this.handleError("Error updating claims: right: "+JSON.stringify(this.selectedRight_PendingMode)+" and wrong: "+JSON.stringify(this.selectedWrong_PendingMode), err);
507
            this.pending_status = this.errorCodes.NOT_SAVED;
508
          }
509
        );
510
    }
511
  }
512

    
513
  clearCheckboxes() {
514
    if(!Session.isLoggedIn()){
515
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
516
    } else {
517
      this.pending_status = this.errorCodes.LOADING;
518
      this.selectedRight_PendingMode.clear();
519
      this.selectedWrong_PendingMode.clear();
520
      this.pending_status = this.errorCodes.DONE;
521
    }
522
  }
523

    
524
  public openLoading(){
525
    if(this.loading){
526
      this.loading.open();
527
    }
528
  }
529
  public closeLoading(){
530
    if(this.loading){
531
      this.loading.close();
532
    }
533
  }
534

    
535
  curatorSelected(selected: string) {
536
    //console.info("selected curator: "+selected);
537
  }
538

    
539
  public openSelect(){
540
    if(this.selectModal){
541
      this.selectModal.open();
542
    }
543
  }
544

    
545
  public setMessageSelect(message: string){
546
    if(this.selectModal){
547
      this.selectModal.message = message;
548
    }
549
  }
550

    
551
  public setOptionsSelect(options: string[]){
552
    if(this.selectModal){
553
      this.selectModal.options = options;
554
    }
555
  }
556

    
557
  totalPages(totalResults: number): number {
558
      let totalPages:any = totalResults/(this.rowsOnPage);
559
      if(!(Number.isInteger(totalPages))) {
560
          totalPages = (parseInt(totalPages, 10) + 1);
561
      }
562
      return totalPages;
563
  }
564

    
565
  updateTitle(title:string){
566
    var _prefix ="OpenAIRE | ";
567
    var _title = _prefix + ((title.length> 50 ) ?title.substring(0,50):title);
568
    this._meta.updateTag({content:_title},"property='og:title'");
569
    this._title.setTitle(_title);
570

    
571
  }
572

    
573
  private handleError(message: string, error) {
574
      console.error("Claims Project Manager Page: "+message, error);
575
  }
576
}
(2-2/4)