Project

General

Profile

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

    
5
import {DataTableDirective}          from 'angular-datatables';
6
import {Subject, Subscriber} from 'rxjs';
7

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

    
13
import {ModalSelect}                 from '../../utils/modal/selectModal.component';
14
import {ModalLoading}                from '../../utils/modal/loading.component';
15

    
16
import {ClaimsByTokenService}        from './claimsByToken.service';
17

    
18
import {Session}                     from '../../login/utils/helper.class';
19
import {LoginErrorCodes}             from '../../login/utils/guardHelper.class';
20
import {properties} from "../../../../environments/environment";
21

    
22

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

    
32
  `],
33
  encapsulation: ViewEncapsulation.None // this used in order styles to work
34

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

    
50
  private errorCodes: ErrorCodes;
51
  private errorMessages: ErrorMessagesComponent;
52
  public pending_status: number;
53
  public curated_status: number;
54

    
55
  // when 'valid' show proper claims, when 'invalid' show no matched entry-wanna retry
56
  public accessStatus: string;// = "empty";
57

    
58
  public mode: string = "pending";
59
  public showTables: boolean = true;
60
  public rowsOnPage = 5;
61
  public sortOrder = "asc";
62
  public keyword1:string = "";
63
  public keyword2:string = "";
64

    
65
  public activePendingPage:any = {page: 1};
66
  public totalPendingResults:any = {count: 0};
67
  public activeCuratedPage:any = {page: 1};
68
  public totalCuratedResults:any = {count: 0};
69
  dtTrigger: Subject<any>[] = [];
70
  private triggered: boolean = false;
71

    
72
  dtOptions: DataTables.Settings[] = [];
73
  @ViewChildren(DataTableDirective)
74
  dtElements: QueryList<any>;
75
  //@ViewChild("table1") table1: DataTableDirective;
76
  //@ViewChild("table2") table2: DataTableDirective;
77

    
78
  @ViewChild (ModalSelect) selectModal : ModalSelect;
79
  @ViewChild (ModalLoading) loading : ModalLoading ;
80

    
81
  properties:EnvProperties = properties;
82

    
83
  public routerHelper:RouterHelper = new RouterHelper();
84

    
85
  constructor (private route: ActivatedRoute,
86
               private _router: Router,
87
               private claimsByTokenService: ClaimsByTokenService,
88
               private _meta: Meta, private _title: Title) {
89
    this.errorCodes = new ErrorCodes();
90
    this.errorMessages = new ErrorMessagesComponent();
91
    this.pending_status = this.errorCodes.LOADING;
92
    this.curated_status = this.errorCodes.LOADING;
93
  }
94
  ngOnInit() {
95
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
96
        this.mode = "pending";
97
        this.openaireId = params['openaireId'];
98
        this.selectedRight_PendingMode = new Set<string>();
99
        this.selectedWrong_PendingMode = new Set<string>();
100
        this.selectedRight_CuratedMode = new Set<string>();
101
        this.selectedWrong_CuratedMode = new Set<string>();
102
        this.editable = new Set<number>();
103
        this.validateJWTandToken();
104
        this.updateTitle("Claims For Project Managers");
105
      }
106
    ));
107

    
108
    this.dtOptions[0] = {
109
      //"paging": false,
110
      //"searching": false,
111
      //"lengthChange": false,
112
      "pageLength": this.rowsOnPage,
113
      "columnDefs": [ {
114
        "type": "date",
115
        "targets": 2
116
      } ],
117
      "order": [[ 2, 'desc' ]]
118
      //"pagingType": 'full_numbers',
119
      /*"language": {
120
          "search": "",
121
          "searchPlaceholder": "Search projects..."
122
      }*/
123
    };
124

    
125
    this.dtOptions[1] = {
126
      "pageLength": this.rowsOnPage,
127
      "columnDefs": [ {
128
        "type": "date",
129
        "targets": [2,4]
130
      } ],
131
      "order": [[ 4, 'desc' ]]
132
    };
133

    
134

    
135
    this.dtTrigger[0] = new Subject<any>();
136
    this.dtTrigger[1] = new Subject<any>();
137
  }
138

    
139
  ngAfterViewInit(): void {
140
    $.fn['dataTable'].ext.search.push((settings, data, dataIndex) => {
141
      if(settings.sTableId == 'table1') {
142
        if (this.filterData(data, this.keyword1)) {
143
          return true;
144
        }
145
        return false;
146
      } else if(settings.sTableId == 'table2') {
147
        if (this.filterData(data, this.keyword2)) {
148
          return true;
149
        }
150
        return false;
151
      }
152
    });
153
  }
154

    
155
  ngOnDestroy(): void {
156
    $.fn['dataTable'].ext.search.pop();
157
    // Do not forget to unsubscribe the event
158
    this.dtTrigger[0].unsubscribe();
159
    this.dtTrigger[1].unsubscribe();
160
    this.subscriptions.forEach(subscription => {
161
      if (subscription instanceof Subscriber) {
162
        subscription.unsubscribe();
163
      }
164
    });
165
  }
166

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

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

    
185
  }
186

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

    
194
        // Call the dtTrigger to rerender again
195
        this.dtTrigger[index].next();
196
      });
197
    });
198
  }
199

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

    
206
      if(query) {
207
        for(var i=0; i <3; i++){
208
          var r= this.filterQuery(row[i], query);
209
          if(r) {
210
            returnValue = true;
211
            break;
212
          }
213
        }
214

    
215
        if(!returnValue) {
216
          return false;
217
        }
218
      }
219

    
220
      return true;
221
    }
222
  }
223

    
224
  filterQuery(data, query){
225
    if(data.toLowerCase().indexOf(query.toLowerCase()) > -1){
226
      return true;
227
    }else{
228
      return false;
229
    }
230
  }
231

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

    
240
        var info = table.page.info();
241

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

    
248
        var info = table.page.info();
249

    
250
        this.activeCuratedPage.page = page;//$event.value;
251
        this.totalCuratedResults.count = info.recordsDisplay;
252
      }
253
    }
254

    
255
    //table.mfActivePage=$event.value;
256
    //table.setPage(table.mfActivePage, this.rowsOnPage);
257
  }
258

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

    
267
        this.showTables = false;
268
        this.pending_claims = [];
269
        this.curated_claims = [];
270

    
271
        this.activePendingPage.page = 1;
272
        this.totalPendingResults.count = 0;
273
        this.activeCuratedPage.page = 1;
274
        this.totalCuratedResults.count = 0;
275

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

    
294
            this.totalPendingResults.count = this.pending_claims.length;
295
            this.totalCuratedResults.count = this.curated_claims.length;
296

    
297
            if(this.project) {
298
              this.updateTitle("Claims For Project Managers - "+this.project.name);
299
            }
300
            this.showTables = true;
301

    
302
            if(!this.triggered) {
303
              //console.info("initial load");
304
              this.triggerInitialLoad();
305
            } else {
306
              //console.info("rerender");
307
              var table1 = $('#table1').DataTable();
308
              table1.clear();
309

    
310
              var table2 = $('#table2').DataTable();
311
              table2.clear();
312

    
313
              this.rerender();
314
            }
315

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

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

    
336
            if(!this.triggered) {
337
              this.triggerInitialLoad();
338
            } else {
339
              var table1 = $('#table1').DataTable();
340
              table1.clear();
341

    
342
              var table2 = $('#table2').DataTable();
343
              table2.clear();
344

    
345
              this.rerender();
346
            }
347

    
348
            this.accessStatus = "invalid";
349
            //console.log(err);
350
          }
351
        ));
352
      } else {
353
        this.accessStatus = "invalid";
354
      }
355
    }
356
  }
357

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

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

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

    
423
    return false;
424
  }
425

    
426
  isWrong_CuratedMode(claim: any) {
427
    if(this.isSelected(claim.id, this.selectedWrong_CuratedMode)) {
428
      return true;
429
    } else if(claim.approved == false && !this.isSelected(claim.id, this.selectedRight_CuratedMode)) {
430
      return true;
431
    }
432

    
433
    return false;
434
  }
435

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

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

    
456
      let approved: boolean = this.isRight_CuratedMode(claim);
457

    
458
      if(approved == claim.approved) {
459
        this.selectedRight_CuratedMode.delete(claim.id);
460
        this.selectedWrong_CuratedMode.delete(claim.id);
461
        this.editable.delete(editable_index);
462

    
463
        this.curated_status = this.errorCodes.DONE;
464
      } else {
465
        let claimCurationInfo: {"id": string, "approved": boolean} = {"id": claim.id, "approved": approved};
466

    
467
        this.subscriptions.push(this.claimsByTokenService.updateClaimCuration(claimCurationInfo, this.properties.claimsAPIURL).subscribe(
468
          data => {
469
            this.selectedRight_CuratedMode.delete(claim.id);
470
            this.selectedWrong_CuratedMode.delete(claim.id);
471
            this.editable.delete(editable_index);
472

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

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

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

    
520
  public openLoading(){
521
    if(this.loading){
522
      this.loading.open();
523
    }
524
  }
525
  public closeLoading(){
526
    if(this.loading){
527
      this.loading.close();
528
    }
529
  }
530

    
531
  curatorSelected(selected: string) {
532
    //console.info("selected curator: "+selected);
533
  }
534

    
535
  public openSelect(){
536
    if(this.selectModal){
537
      this.selectModal.open();
538
    }
539
  }
540

    
541
  public setMessageSelect(message: string){
542
    if(this.selectModal){
543
      this.selectModal.message = message;
544
    }
545
  }
546

    
547
  public setOptionsSelect(options: string[]){
548
    if(this.selectModal){
549
      this.selectModal.options = options;
550
    }
551
  }
552

    
553
  totalPages(totalResults: number): number {
554
    let totalPages:any = totalResults/(this.rowsOnPage);
555
    if(!(Number.isInteger(totalPages))) {
556
      totalPages = (parseInt(totalPages, 10) + 1);
557
    }
558
    return totalPages;
559
  }
560

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

    
567
  }
568

    
569
  private handleError(message: string, error) {
570
    console.error("Claims Project Manager Page: "+message, error);
571
  }
572
}
(2-2/4)