Project

General

Profile

1
import {Component, Input, ViewChild} from '@angular/core';
2
import {ActivatedRoute, Router} from "@angular/router";
3
import {Subscriber, Subscription} from "rxjs";
4
import {OrcidService} from "./orcid.service";
5
import {ResultLandingInfo} from "../utils/entities/resultLandingInfo";
6
import {ResultLandingService} from "../landingPages/result/resultLanding.service";
7
import {properties} from "../../../environments/environment";
8
import {Session} from "../login/utils/helper.class";
9
import {LoginErrorCodes} from "../login/utils/guardHelper.class";
10
import {ExternalIDV3_0, WorkV3_0} from "./orcidWork";
11
import {EnvProperties} from "../utils/properties/env-properties";
12

    
13
declare var UIkit: any;
14

    
15
@Component({
16
  styles: [
17
    '.add-orcid-button { background-color: #a6ce39; color: #fff; border: 1px solid #a6ce39; } ' +
18
    '.add-orcid-button:hover { background-color: #b6d65c; border-color: #b6d65c; } ' +
19
    '.delete-orcid-button { background-color: #fff; color: #ff3d33; border: 1px solid #ff3d33 }' +
20
    '.delete-orcid-button:hover { color: #ff0d00; border-color: #ff0d00; } ' +
21
    ' a:not(:hover) .orcid-color { color: #a6ce39; }' +
22

    
23
    '.loading-action-button { width: 36px; height: 36px; }' +
24

    
25
    '.orcid-button { background-color: #fff; border: 1px solid #a6ce39; } ' +
26
    '.orcid-button:hover { background-color: #e0f0d5; } ' +
27

    
28
    'a.orcid_icon_opacity:hover > .uk-icon { opacity: 0.8; } '
29
  ],
30
  selector: 'orcid-work',
31
  template: `
32
    <ng-container *ngIf="pageType == 'search'">
33
      <span *ngIf="!putCodes || putCodes.length == 0"
34
            [attr.uk-tooltip]="(!isLoggedIn) 
35
                      ? 'Only logged in users can add or delete a work from their ORCID record '
36
                    : ('Add this work to your ORCID record' + 
37
                        ((properties.environment == 'beta') ? '. The action will affect your real ORCID iD.' : ''))"
38
            class="uk-align-right uk-margin-remove-bottom">
39

    
40
      <a (click)="currentAction='add'; saveWorkPreparation();"
41
           [class]="'uk-flex uk-flex-middle uk-flex-right uk-margin-right '+ ((showLoading || !isLoggedIn) ? 'uk-disabled ' : '') + (!isLoggedIn ? 'half-opacity' : '')">
42
          <icon *ngIf="!showLoading" name="add" ratio="1"></icon>
43
          <span *ngIf="showLoading" class="uk-icon icon-button"><loading [top_margin]="false"></loading></span>
44
          <span class="uk-margin-small-left uk-flex uk-flex-middle">Add to 
45
            <span class="orcid-color space uk-flex uk-flex-middle">
46
              <span>ORCID</span>
47
              <img  class="space" src="assets/common-assets/common/ORCIDiD_icon16x16.png" alt="" loading="lazy">{{" "}}
48
            </span>
49
          </span>
50
        </a>
51
      </span>
52

    
53
      <span *ngIf="putCodes && putCodes.length > 0"
54
            [attr.uk-tooltip]="(!isLoggedIn) 
55
                      ? 'Only logged in users can add or delete a work from their ORCID record '
56
                    : ('Delete this work from your ORCID record' + 
57
                        ((properties.environment == 'beta') ? '. The action will affect your real ORCID iD.' : ''))"
58
            class="uk-align-right uk-margin-remove-bottom">
59
        <a (click)="currentAction='delete'; deleteWorks();"
60
            [class]="'uk-flex uk-flex-middle uk-flex-right uk-margin-right '+ (showLoading ? 'uk-disabled' : '')">
61
          <icon *ngIf="!showLoading" name="remove" ratio="0.8"></icon>
62
          <span *ngIf="showLoading" class="uk-icon icon-button"><loading [top_margin]="false"></loading></span>
63
          <span class="uk-margin-small-left uk-flex uk-flex-middle">Delete from 
64
            <span class="orcid-color space uk-flex uk-flex-middle">
65
              <span>ORCID</span>
66
              <img class="space" src="assets/common-assets/common/ORCIDiD_icon16x16.png" alt="" loading="lazy">{{" "}}
67
            </span>
68
          </span>
69
        </a>
70
      </span>
71
    </ng-container>
72

    
73
    <ng-container *ngIf="pageType == 'landing'">
74
      <span *ngIf="!putCodes || putCodes.length == 0"
75
            [attr.uk-tooltip]="(!pids || !isLoggedIn) 
76
                      ? (!pids?'Only resources with a PID (persistent identifier) like DOI, handle, PMID can be added or deleted from your ORCID record'
77
                      : 'Only logged in users can add or delete a work from their ORCID record ')
78
                    : ('Add this work to your ORCID record' + ((properties.environment == 'beta') ? '. The action will affect your real ORCID iD.' : ''))"
79
            [class]="(!pids || !isLoggedIn) ? 'half-opacity' : ''">
80
        <a (click)="currentAction='add'; saveWorkPreparation();"
81
           [class]="'orcid_icon_opacity uk-link-text uk-text-bold uk-text-uppercase '+ (showLoading ? 'uk-disabled' : '') + (!isLoggedIn || !pids ? 'uk-disabled uk-text-muted' : '')">
82
          <span *ngIf="!showLoading" class="uk-icon">
83
            <img src="assets/common-assets/common/orcid_add.svg" style="width: 42px; height: 42px" loading="lazy">
84
          </span>
85
          <span *ngIf="showLoading" class="uk-icon icon-button loading-action-button"><loading
86
            [top_margin]="false"></loading></span>
87
          <span [class]="showLoading ? 'uk-margin-small-left' : 'space'">Add to 
88
            <span class="orcid-color">
89
              ORCID
90
            </span>
91
          </span>
92
        </a>
93
      </span>
94

    
95
      <span *ngIf="putCodes && putCodes.length > 0"
96
            [attr.uk-tooltip]="(!pids || !isLoggedIn) 
97
                    ? (!pids?'Only resources with a PID (persistent identifier) like DOI, handle, PMID can be added or deleted from your ORCID record'
98
                    : 'Only logged in users can add or delete a work from their ORCID record ')
99
                  : ('Delete this work from your ORCID record' + ((properties.environment == 'beta') ? '. The action will affect your real ORCID iD.' : ''))"
100
            [class]="(!pids || !isLoggedIn) ? 'half-opacity' : ''">
101
      <a (click)="currentAction='delete'; deleteWorks();"
102
         [class]="'orcid_icon_opacity uk-link-text uk-text-bold uk-text-uppercase '+ (showLoading ? 'uk-disabled' : '') + (!isLoggedIn || !pids ? 'uk-disabled uk-text-muted' : '')">
103
        <span *ngIf="!showLoading" class="uk-icon uk-preserve">
104
          <img src="assets/common-assets/common/orcid_bin.svg" style="width: 42px; height: 42px" loading="lazy">
105
        </span>
106
        <span *ngIf="showLoading" class="uk-icon icon-button loading-action-button"><loading
107
          [top_margin]="false"></loading></span>
108
        <span [class]="showLoading ? 'uk-margin-small-left' : 'space'">Delete from
109
            <span class="orcid-color">
110
              ORCID
111
            </span>
112
          </span>
113
      </a>
114
    </span>
115
    </ng-container>
116

    
117
    <modal-alert #grantModal [classTitle]="'landing-modal-header uk-padding-small'"
118
                 [classBody]="'landing-modal uk-padding-remove'">
119
      <div class="uk-text-center uk-padding-small">
120
        <div>{{requestGrantMessage}}</div>
121

    
122
        <div class="uk-margin-medium-top uk-align-right">
123
          <button (click)="closeGrantModal()" type="submit"
124
                  class="uk-button uk-padding-small uk-padding-remove-vertical uk-button-default">
125
            <span>Cancel</span>
126
          </button>
127

    
128
          <button (click)="openGrantWindow()" type="submit"
129
                  class="uk-button uk-padding-small uk-padding-remove-vertical uk-margin-left uk-button-primary">
130
            <span>Grant OpenAIRE</span>
131
          </button>
132

    
133
<!--          <button (click)="openGrantWindow()" type="submit"-->
134
<!--                  class="uk-button uk-padding-small uk-padding-remove-vertical uk-margin-left orcid-button">-->
135
<!--            <img src="assets/common-assets/common/ORCIDiD_icon16x16.png" alt="">{{" "}}-->
136
<!--            <span>Create or Connect your ORCID iD</span>-->
137
<!--          </button>-->
138
        </div>
139
      </div>
140
    </modal-alert>
141

    
142

    
143
    <ng-container *ngIf="pageType == 'my_search'">
144
      <span class="uk-margin-bottom uk-flex uk-flex-middle uk-flex-center">
145
        <span>ORCID</span>
146
        <img class="space" src="assets/common-assets/common/ORCIDiD_icon16x16.png" alt="" loading="lazy">
147
        <span class="space">ACTIONS</span>
148
      </span>
149
      
150
      <span [attr.uk-tooltip]="(!putCodes || putCodes.length == 0) 
151
                      ? 'This work is currently deleted.'
152
                    : 'View this work from your ORCID record'">
153
        <a (click)="currentAction='get'; getOrcidWorks()"
154
           [class]="'uk-button action uk-flex uk-flex-middle '+ ((showLoading || !putCodes || putCodes.length == 0) ? 'uk-disabled' : '')">
155
          <icon *ngIf="!showLoading || currentAction!='get'" name="preview" ratio="1"></icon>
156
          
157
          <span *ngIf="showLoading && currentAction=='get'" class="uk-icon icon-button"><loading [top_margin]="false"></loading></span>
158
          <span class="uk-margin-small-left">View ORCID work</span>
159
        </a>
160
      </span>
161

    
162
      <span [attr.uk-tooltip]="(!putCodes || putCodes.length == 0) 
163
                      ? 'This work is currently deleted.'
164
                    : ('Update this work to your ORCID record' + ((properties.environment == 'beta') ? '. The action will affect your real ORCID iD.' : '') 
165
                    + showUpdateDatesInTooltip())">
166
        <a (click)="currentAction='update'; updateWorkPreparation()"
167
           [class]="'uk-button action uk-margin-top uk-flex uk-flex-middle '+ ((showLoading || !putCodes || putCodes.length == 0) ? 'uk-disabled' : '')">
168
          <icon *ngIf="!showLoading || currentAction!='update'" name="refresh" ratio="1"></icon>
169
          <span *ngIf="showLoading && currentAction=='update'" class="uk-icon icon-button"><loading [top_margin]="false"></loading></span>
170
          <span class="uk-margin-small-left">Update ORCID work</span>
171
        </a>
172
      </span>
173

    
174
      <span *ngIf="!putCodes || putCodes.length == 0"
175
            [attr.uk-tooltip]="'Add this work to your ORCID record' + ((properties.environment == 'beta') ? '. The action will affect your real ORCID iD.' : '')">
176
        <a (click)="currentAction='add'; saveWorkPreparation();"
177
           [class]="'uk-button action uk-margin-top uk-flex uk-flex-middle '+ (showLoading ? 'uk-disabled' : '')">
178
          <icon *ngIf="!showLoading || currentAction!='add'" name="add" ratio="1"></icon>
179
          <span *ngIf="showLoading && currentAction=='add'" class="uk-icon icon-button"><loading [top_margin]="false"></loading></span>
180
          <span class="uk-margin-small-left">Add to ORCID</span>
181
        </a>
182
      </span>
183

    
184
      <span *ngIf="putCodes && putCodes.length > 0"
185
            [attr.uk-tooltip]="'Delete this work from your ORCID record' + ((properties.environment == 'beta') ? '. The action will affect your real ORCID iD.' : '')">
186
        <a (click)="currentAction='delete'; deleteWorks();"
187
           [class]="'uk-button action uk-margin-top uk-flex uk-flex-middle '+ (showLoading ? 'uk-disabled' : '')">
188
          <icon *ngIf="!showLoading || currentAction!='delete'" name="remove" ratio="1"></icon>
189
          <span *ngIf="showLoading && currentAction=='delete'" class="uk-icon icon-button"><loading [top_margin]="false"></loading></span>
190
          <span class="uk-margin-small-left">Delete from ORCID</span>
191
        </a>
192
      </span>
193
    </ng-container>
194

    
195
    <modal-alert #workModal [classTitle]="'landing-modal-header uk-padding-small'"
196
                 [classBody]="'landing-modal uk-padding-remove'">
197
      <div *ngIf="orcidWorks" class="uk-padding-small">
198
        <div *ngFor="let work of orcidWorks['bulk']">
199
          <ng-container *ngTemplateOutlet="orcidWorkPreview; context:{work: work['work']}"></ng-container>
200
        </div>
201
      </div>
202
    </modal-alert>
203

    
204
    <ng-template #orcidWorkPreview let-work="work">
205
      <div class="uk-card uk-card-default uk-padding uk-card-hover">
206
        <div>{{work.title?.title?.value}}</div>
207
        <div>{{work.title?.subtitle?.value}}</div>
208
  
209
        <div class="uk-text-uppercase">{{work['journal-title']?.value}}</div>
210
        
211
        <div *ngIf="work['publication-date'] || work['type']" class="uk-text-small uk-margin-small-bottom">
212
          <span *ngIf="work['publication-date']">
213
            <span *ngIf="work['publication-date']['year'] && work['publication-date']['year'].value">
214
              {{work['publication-date']?.year?.value}}
215
            </span>
216
            <span *ngIf="work['publication-date']['year'] && work['publication-date']['year'].value
217
                          && (
218
              (work['publication-date']['month'] && work['publication-date']['month'].value) || (work['publication-date']['day'] && work['publication-date']['day'].value))">
219
              -
220
            </span>
221
            <span *ngIf="work['publication-date']['month'] && work['publication-date']['month'].value">
222
              {{work['publication-date']?.month?.value}}
223
            </span>
224
            <span *ngIf="work['publication-date']['month'] && work['publication-date']['month'].value
225
                          && (work['publication-date']['day'] && work['publication-date']['day'].value) ">
226
              -
227
            </span>
228
            <span *ngIf="work['publication-date']['day'] && work['publication-date']['day'].value">
229
              {{work['publication-date']?.day?.value}}
230
            </span>
231
            
232
            <span *ngIf="work['type']"> | </span>
233
          </span>
234

    
235
          <span>{{work['type']}}</span>
236
        </div>
237

    
238
        <!-- Description -->
239
        <div *ngIf="work['short-description']" class="uk-margin-small-bottom multi-line-ellipsis lines-3">
240
          <p class="uk-text-muted uk-text-small">
241
            {{work['short-description']}}
242
          </p>
243
        </div>
244
        
245
        <div *ngIf="work['external-ids'] && work['external-ids']['external-id']" class="uk-margin-small-bottom">
246
          <showIdentifiers [identifiers]="parseIdentifiers(work['external-ids']['external-id'])"></showIdentifiers>
247
        </div>
248
        
249
        <div *ngIf="work['contributors'] && work['contributors']['contributor']">
250
          <div *ngFor="let contributor of work['contributors']['contributor']">
251
            <span *ngIf="contributor['credit-name'] && contributor['credit-name'].value">
252
              {{contributor['credit-name']?.value}}
253
            </span>
254
            <span *ngIf="(contributor['credit-name'] && contributor['credit-name'].value) && (
255
                  (contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-role'])
256
                  ||
257
                  (contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-sequence'])
258
                  || 
259
                  (contributor['contributor-orcid'] && contributor['contributor-orcid']['path'])
260
            )">
261
              (
262
            </span>
263
            <span *ngIf="contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-role']">
264
              {{contributor['contributor-attributes']['contributor-role']}}
265
            </span>
266
            <span *ngIf="(contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-role']) 
267
                        && (contributor['contributor-attributes']['contributor-sequence'] || (contributor['contributor-orcid'] && contributor['contributor-orcid']['path']))">
268
              ,
269
            </span>
270
            <span *ngIf="contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-sequence']">
271
              {{contributor['contributor-attributes']['contributor-sequence']}}
272
            </span>
273
            <span *ngIf="contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-sequence'] 
274
                        && contributor['contributor-orcid'] && contributor['contributor-orcid']['path']">
275
              , 
276
            </span>
277
            <span *ngIf="contributor['contributor-orcid'] && contributor['contributor-orcid']['path']">
278
              {{contributor['contributor-orcid']?.path}}
279
            </span>
280
            <span *ngIf="(contributor['credit-name'] && contributor['credit-name'].value) && (
281
                  (contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-role'])
282
            ||
283
            (contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-sequence'])
284
            ||
285
            (contributor['contributor-orcid'] && contributor['contributor-orcid']['path'])
286
            )">
287
            )
288
            </span>
289
          </div>
290
        </div>
291
      </div>
292
    </ng-template>
293

    
294
    <modal-alert #propagationModal [classTitle]="'landing-modal-header uk-padding-small'"
295
                 [classBody]="'landing-modal uk-padding-remove'">
296
      <div class="uk-padding-small">
297
        <div>
298
          This research outcome is the result of <span class="uk-text-bold"> merged  research outcomes in OpenAIRE</span>. 
299
          <br><br>
300
          You have already added <span class="uk-text-bold">{{this.putCodes?.length}} works</span> in your ORCID record related to the merged research outcome.
301
          <div *ngIf="currentAction == 'delete'">
302
            If you continue with delete action, <span class="uk-text-bold">all these works will be deleted</span>.
303
          </div>
304
          <div *ngIf="currentAction == 'update'">
305
            If you continue with update action, <span class="uk-text-bold">all these works will be deleted and a new merged work will be added</span> instead.
306
          </div>
307
        </div>
308

    
309
        <div class="uk-margin-medium-top uk-align-right">
310
          <button (click)="closePropagationModal()" type="submit"
311
                  class="uk-button uk-padding-small uk-padding-remove-vertical uk-button-default">
312
            <span>Cancel</span>
313
          </button>
314

    
315
          <button (click)="confirmedPropagation()" type="submit"
316
                  class="uk-button uk-padding-small uk-padding-remove-vertical uk-margin-left uk-button-primary">
317
            <span>Continue</span>
318
          </button>
319
        </div>
320
      </div>
321
    </modal-alert>
322
  `
323
})
324

    
325
export class OrcidWorkComponent {
326
  @Input() resultId: string = "";
327
  @Input() resultTitle: string = "";
328
  @Input() resultLandingInfo: ResultLandingInfo;
329
  @Input() pids: string = "";
330
  @Input() identifiers: Map<string, string[]>;
331
  @Input() type: string;
332
  @Input() putCodes: string[] = [];
333
  @Input() creationDates: string[] = [];
334
  @Input() updateDates: string[] = [];
335
  @Input() givenPutCode: boolean = false;
336
  @Input() pageType: string = "search";
337

    
338
  public subscriptions: Subscription[] = [];
339
  @ViewChild('workModal') workModal;
340
  @ViewChild('saveWorkModal') saveWorkModal;
341
  @ViewChild('grantModal') grantModal;
342
  @ViewChild('messageModal') messageModal;
343
  @ViewChild('propagationModal') propagationModal;
344

    
345
  public requestGrant: boolean = false;
346
  public requestGrantMessage: string = "Please grant OpenAIRE to access and update your ORCID works.";
347
  private tokenUrl: string;
348
  public message: string = "";
349
  public showLoading: boolean = false;
350

    
351
  public works: any[] = [];
352
  public orcidWorks: any[] = [];
353
  public window: any;
354

    
355
  public isLoggedIn: boolean = Session.isLoggedIn();
356

    
357
  public currentAction: string = "";
358

    
359
  public properties: EnvProperties = properties;
360

    
361
  constructor(private route: ActivatedRoute,
362
              private _router: Router,
363
              private orcidService: OrcidService,
364
              private resultLandingService: ResultLandingService) {
365
    if(typeof document !== 'undefined') {
366
      this.tokenUrl = properties.orcidTokenURL
367
        + "client_id="+properties.orcidClientId
368
        // + "&response_type=code&scope=/activities/update"
369
        // + "&response_type=code&scope=/authenticate /activities/update /person/update /read-limited"
370
        + "&response_type=code&scope=/activities/update /read-limited"
371
        + "&redirect_uri="+location.origin+"/orcid?source=openaire";
372
    }
373
  }
374

    
375
  ngOnInit() {
376
    if(!this.givenPutCode && this.isLoggedIn) {
377
      this.getPutCode();
378
    }
379
  }
380

    
381
  ngOnDestroy() {
382
    this.subscriptions.forEach(subscription => {
383
      if (subscription instanceof Subscriber) {
384
        // console.debug("subscription closing...");
385
        subscription.unsubscribe();
386
      }
387
    });
388
  }
389

    
390
  public showUpdateDatesInTooltip() {
391
    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
392
    let response: string = "";
393
    if(this.updateDates != null && this.updateDates.length > 0) {
394
      response += "<br><br> Last update in ORCID<br>";
395
      for(let i=0; i<this.updateDates.length; i++) {
396
        let date: Date = new Date(this.updateDates[i]);
397
        response += "<span>"+date.getDate() + " " + monthNames[date.getMonth()] + " " + date.getFullYear();
398
        if(i < this.updateDates.length - 1) {
399
          response += "& ";
400
        }
401
        response += "</span>";
402
      }
403
    }
404
    return response;
405
  }
406

    
407
  public parseIdentifiers(identifiers: ExternalIDV3_0[]): Map<string, string[]> {
408
    let identifiersMap: Map<string, string[]> = new Map<string, string[]>();
409
    for(let identifier of identifiers) {
410
      if(!identifiersMap.has(identifier['external-id-type'])) {
411
        identifiersMap.set(identifier['external-id-type'], new Array<string>());
412
      }
413
      identifiersMap.get(identifier['external-id-type']).push(identifier['external-id-value']);
414
    }
415
    return identifiersMap;
416
  }
417

    
418
  openGrantWindow() {
419
    if(!Session.isLoggedIn()){
420
      //this.userValidMessage = "User session has expired. Please login again.";
421
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
422
    } else {
423
      // this.tokenUrl = location.origin+"/orcid";
424
      this.window = window.open(this.tokenUrl, '_blank',
425
        'location=yes,height=700,width=540,left=500,top=100,scrollbars=yes,status=yes');
426
      // this.requestGrant = false;
427
      this.closeGrantModal();
428

    
429
      let self = this;
430
      window.onmessage = function (ev) {
431
        if (ev.isTrusted && ev.origin !== location.origin && ev.data !== 'success')
432
          return;
433
        self.requestGrant = false;
434
        UIkit.notification({
435
          message: 'Thank you for <strong>connecting your ORCID iD</strong> with OpenAIRE!',
436
          status: 'success',
437
          timeout: 6000,
438
          pos: 'bottom-right'
439
        });
440
        if (self.currentAction == "add") {
441
          self.saveWorkPreparation();
442
        } else if (self.currentAction == "delete") {
443
          self.deleteWorks();
444
        } else if(self.currentAction == "update") {
445
          self.updateWorkPreparation();
446
        }
447
      };
448
    }
449
  }
450

    
451
  private getPutCode() {
452
    this.subscriptions.push(this.orcidService.getPutCode(this.pids).subscribe(
453
      putCodes => {
454
        this.putCodes = putCodes;
455
      }, error => {
456

    
457
      }
458
    ))
459
  }
460

    
461
  private getResultLandingInfo(action: string) {
462
    this.subscriptions.push(this.resultLandingService.getResultLandingInfo(this.resultId, null, this.type, null, properties).subscribe(
463
      resultLandingInfo => {
464
        this.resultLandingInfo = resultLandingInfo;
465
        if (this.resultLandingInfo && this.resultLandingInfo.identifiers) {
466
          let pidsArray: string[] = [];
467
          for (let key of Array.from(this.resultLandingInfo.identifiers.keys())) {
468
            pidsArray = pidsArray.concat(this.resultLandingInfo.identifiers.get(key));
469
          }
470
          this.pids = pidsArray.join();
471
        }
472
        if(action == "save") {
473
          this.saveWork();
474
        } else if (action == "update") {
475
          this.updateWork();
476
        }
477
      },
478
      error => {
479
        this.handleError(error);
480
        console.error("Error getting landing info: ", error);
481
      }
482
    ))
483
  }
484

    
485
  private saveWorkPreparation() {
486
    if(!Session.isLoggedIn()){
487
      //this.userValidMessage = "User session has expired. Please login again.";
488
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
489
    } else {
490

    
491
      if (this.requestGrant) {
492
        this.openGrantModal("Add, delete or edit work in your ORCID record");
493
      } else {
494
        this.showLoading = true;
495

    
496
        if (this.resultLandingInfo) {
497
          this.saveWork();
498
        } else {
499
          this.getResultLandingInfo("save");
500
        }
501
      }
502
    }
503
  }
504

    
505
  private saveWork() {
506
    this.subscriptions.push(this.orcidService.saveWork(this.resultLandingInfo, this.pids).subscribe(
507
      response => {
508

    
509
        // for testing only
510
        // this.openGrantModal("Add work in your ORCID record");
511
        // this.requestGrant = true;
512
        // this.requestGrantMessage = "Please grant OpenAIRE to access and update your ORCID record and works.";
513

    
514
        if(response == null) {
515
          this.handleError(null);
516
          console.error("Error posting landing info: null");
517
        } else {
518
          this.putCodes.push(""+response['put-code']);
519
          this.creationDates.push(response['created-date']['value']);
520
          this.updateDates.push(response['last-modified-date']['value']);
521

    
522
          // this.closeGrantModal();
523
          // this.message = "You have successfully added work with pids: "+this.pids+" in your ORCID record!";
524
          this.message = "You have successfully added work \""+this.resultTitle+"\" in your ORCID record!";
525
          // this.openMessageModal("Work added successfully");
526

    
527
          // message: 'You have <strong>successfully added</strong> work with pids: <strong>'+this.pids+'</strong> in your ORCID record!',
528
          UIkit.notification({
529
            message: 'You have <strong>successfully added</strong> work "<strong>'+this.resultTitle+'</strong>" in your ORCID record!'
530
              // +
531
              // '<br><br><a class="uk-link" [href]="goToOrcidLinksPage()">Manager your ORCID links</a>'
532
            ,
533
              // '<br><br><a class="uk-link" (click)="goToOrcidLinksPage()">Manager your ORCID links</a>',
534
              // '<br><br><a class="uk-link" routerLinkActive="router-link-active" [routerLink]="myOrcidLinksPage">Manager your ORCID links</a>',
535
            status: 'success',
536
            timeout: 6000,
537
            pos: 'bottom-right'
538
          });
539

    
540
          this.showLoading = false;
541
        }
542
      },
543
      error => {
544
        this.handleError(error);
545
        console.error("Error posting landing info", error);
546
      }
547
    ));
548
  }
549

    
550
  goToOrcidLinksPage() {
551
    this._router.navigate([this.properties.myOrcidLinksPage]);
552
  }
553

    
554
  private updateWorkPreparation() {
555
    if(!Session.isLoggedIn()){
556
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
557
    } else {
558

    
559
      if (this.requestGrant) {
560
        this.openGrantModal("Add, delete or edit work in your ORCID record");
561
      } else if(this.putCodes.length > 1) {
562
        this.openPropagationModal("Update ORCID work");
563
      } else {
564
        this.showLoading = true;
565

    
566
        if (this.resultLandingInfo) {
567
          this.updateWork();
568
        } else {
569
          this.getResultLandingInfo("update");
570
        }
571
      }
572
    }
573
  }
574

    
575
  private updateWork() {
576
    this.subscriptions.push(this.orcidService.updateWork(this.resultLandingInfo, this.pids, this.putCodes[0]).subscribe(
577
      response => {
578
        if(response) {
579
          this.updateDates[0] = response['last-modified-date'].value;
580

    
581
          // message: 'You have <strong>successfully updated</strong> work with pids: <strong>' + this.pids + '</strong> in your ORCID record!',
582
          UIkit.notification({
583
            message: 'You have <strong>successfully updated</strong> work "<strong>' + this.resultTitle + '</strong>" in your ORCID record!'
584
              // +
585
              // '<br><br><a routerLinkActive="router-link-active" [routerLink]="myOrcidLinksPage">Manager your ORCID links</a>'
586
            ,
587
            status: 'success',
588
            timeout: 6000,
589
            pos: 'bottom-right'
590
          });
591
        }
592
        this.showLoading = false;
593
      },
594
      error => {
595
        this.handleError(error);
596
        console.error("Error updating landing info", error);
597
      }
598
    ));
599
  }
600

    
601
  public confirmedPropagation() {
602
    this.propagationModal.cancel();
603

    
604
    this.deleteWorks(true);
605
    //}
606
    // if(this.currentAction == "update") {
607
    //   this.saveWork();
608
    // }
609
  }
610

    
611
  private getOrcidWorks() {
612
    if(!Session.isLoggedIn()){
613
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
614
    } else {
615
      this.showLoading = true;
616
      this.subscriptions.push(this.orcidService.getOrcidWorks(this.putCodes).subscribe(
617
        (response: WorkV3_0[]) => {
618
          this.orcidWorks = response;
619

    
620
          this.openWorkModal();
621
          this.showLoading = false;
622
        },
623
        error => {
624
          this.handleError(error);
625
          console.error("Error getting work", error);
626
        }
627
      ));
628
    }
629
  }
630

    
631

    
632
  private deleteWorks(confirmed: boolean = false) {
633
    if(!Session.isLoggedIn()){
634
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
635
    } else {
636

    
637
      if (this.requestGrant) {
638
        this.openGrantModal("Add, delete or edit work in your ORCID record");
639
      } else if(this.putCodes.length > 1 && !confirmed) {
640
        this.openPropagationModal("Delete ORCID work");
641
      } else {
642
        this.showLoading = true;
643

    
644
        if (!this.resultLandingInfo && this.identifiers) {
645
          let pidsArray: string[] = [];
646
          for (let key of Array.from(this.identifiers.keys())) {
647
            pidsArray = pidsArray.concat(this.identifiers.get(key));
648
          }
649
          this.pids = pidsArray.join();
650
        }
651

    
652
        this.subscriptions.push(this.orcidService.deleteWorks(this.putCodes).subscribe(
653
          deletedPutCodes => {
654
            let deletedAll: boolean = true;
655

    
656
            if (deletedPutCodes) {
657
              for (let i = 0; i < deletedPutCodes.length; i++) {
658
                let deletedPutCode = deletedPutCodes[i];
659
                if (deletedPutCode == null) {
660
                  deletedAll = false;
661
                } else {
662
                  this.putCodes.splice(i, 1);
663
                  this.creationDates.splice(i, 1);
664
                  this.updateDates.splice(i, 1);
665
                  // this.works.splice(i, 1);
666
                }
667
              }
668
            } else {
669
              deletedAll = false;
670
            }
671

    
672
            if (!deletedAll) {
673
              this.handleError(null);
674
              console.error("Error deleting landing info: null");
675
            } else {
676
              if(this.currentAction == "update") {
677
                this.saveWork();
678
              } else {
679
                // this.closeGrantModal();
680
                // this.message = "You have successfully deleted work with pids: " + this.pids + " from your ORCID record!";
681
                this.message = "You have successfully deleted work \"" + this.resultTitle + "\" from your ORCID record!";
682
                // this.openMessageModal("Work deleted successfully");
683

    
684
                // message: 'You have <strong>successfully deleted</strong> work with pids: <strong>' + this.pids + '</strong> from your ORCID record!',
685
                UIkit.notification({
686
                  message: 'You have <strong>successfully deleted</strong> work "<strong>' + this.resultTitle + '</strong>" from your ORCID record!'
687
                    // +
688
                    // '<br><br><a routerLinkActive="router-link-active" [routerLink]="myOrcidLinksPage">Manager your ORCID links</a>'
689
                  ,
690
                  status: 'success',
691
                  timeout: 6000,
692
                  pos: 'bottom-right'
693
                });
694
                this.showLoading = false;
695
              }
696
            }
697
          },
698
          error => {
699
            this.handleError(error);
700
            console.error("Error deleting work", error);
701
          }
702
        ));
703
      }
704
    }
705
  }
706

    
707
  openGrantModal(title: string) {
708
    this.grantModal.cancelButton = false;
709
    this.grantModal.okButton = false;
710
    this.grantModal.alertTitle = title;
711
    this.grantModal.open();
712
  }
713

    
714
  closeGrantModal() {
715
    this.grantModal.cancel();
716
  }
717

    
718
  openWorkModal() {
719
    this.workModal.cancelButton = false;
720
    this.workModal.okButton = false;
721
    this.workModal.alertTitle = "Work in your ORCID record";
722
    this.workModal.open();
723
  }
724

    
725
  closeWorkModal() {
726
    this.workModal.cancel();
727
  }
728

    
729
  openMessageModal(title: string) {
730
    this.messageModal.cancelButton = false;
731
    this.messageModal.okButton = false;
732
    this.messageModal.alertTitle = title;
733
    this.messageModal.open();
734
  }
735

    
736
  closeMessageModal() {
737
    this.messageModal.cancel();
738
  }
739

    
740
  openPropagationModal(title: string) {
741
    this.propagationModal.cancelButton = false;
742
    this.propagationModal.okButton = false;
743
    this.propagationModal.alertTitle = title;
744
    this.propagationModal.open();
745
  }
746

    
747
  closePropagationModal() {
748
    this.propagationModal.cancel();
749
  }
750

    
751
  handleError(error) {
752
    if(error && error.status == "401") {
753
      this.openGrantModal("Add, delete or edit work in your ORCID record");
754
      this.requestGrant = true;
755
      this.requestGrantMessage = "Please grant OpenAIRE to access and update your ORCID record and works. ";
756
        // + "If you have already granted OpenAIRE, you just need to login again to ORCID!";
757
    } else if(error && error.status == "403") {
758
      this.openGrantModal("Add, delete or edit work in your ORCID record");
759
      this.requestGrant = true;
760
      this.requestGrantMessage = "Please login again to ORCID."
761
      // this.openGrantModal();
762
    } else {
763
      this.message = "";
764
      if(error && error.status == "409") {
765
        this.message = "There is <span class='uk-text-bold'>already a work in your ORCID record</span> with the same information of the work you are trying to add now. <br><br>";
766
      }
767
      if(this.currentAction == "get") {
768
        // this.message += "There was an <span class='uk-text-bold'>error getting</span> work with pids: <span class='uk-text-bold'>" + this.pids + "</span> from your ORCID record. <br> Please try again later.";
769
        this.message += "There was an <span class='uk-text-bold'>error getting</span> work \"<span class='uk-text-bold'>" + this.resultTitle + "</span>\" from your ORCID record. <br> Please try again later.";
770
      } else if(this.currentAction == "add") {
771
        // this.message += "There was an <span class='uk-text-bold'>error adding</span> work with pids: <span class='uk-text-bold'>"+this.pids+"</span> to your ORCID record. <br> Please try again later.";
772
        this.message += "There was an <span class='uk-text-bold'>error adding</span> work with pids: \"<span class='uk-text-bold'>"+this.resultTitle+"</span>\" to your ORCID record. <br> Please try again later.";
773
      } else if(this.currentAction == "update") {
774
        // this.message += "There was an <span class='uk-text-bold'>error updating</span> work with pids: <span class='uk-text-bold'>"+this.pids+"</span> to your ORCID record. <br> Please try again later.";
775
        this.message += "There was an <span class='uk-text-bold'>error updating</span> work with pids: \"<span class='uk-text-bold'>"+this.resultTitle+"</span>\" to your ORCID record. <br> Please try again later.";
776
      } else if(this.currentAction == "delete") {
777
        // this.message += "There was an <span class='uk-text-bold'>error deleting</span> work with pids: <span class='uk-text-bold'>"+this.pids+"</span> from your ORCID record. <br> Please try again later.";
778
        this.message += "There was an <span class='uk-text-bold'>error deleting</span> work with pids: \"<span class='uk-text-bold'>"+this.resultTitle+"</span>\" from your ORCID record. <br> Please try again later.";
779
      } else {
780
        this.message += "There was an error. Please try again later."
781
      }
782

    
783
      UIkit.notification({
784
        message: this.message,
785
        status: 'danger',
786
        timeout: 6000,
787
        pos: 'bottom-right'
788
      });
789
      // this.openMessageModal("An error occured");
790
    }
791
    this.showLoading = false;
792
  }
793
}
(1-1/5)