Project

General

Profile

1
import {Component, Input, Output, EventEmitter, ViewChild} from '@angular/core';
2
import {Observable}       from 'rxjs';
3
import {Router, ActivatedRoute} from '@angular/router';
4
import {ClaimsService} from '../../claim-utils/service/claims.service';
5

    
6
import {ModalLoading} from '../../../utils/modal/loading.component';
7
import {AlertModal} from '../../../utils/modal/alert';
8
import {Md5} from 'ts-md5/dist/md5';
9
import {Session} from '../../../login/utils/helper.class';
10
import {LoginErrorCodes} from '../../../login/utils/guardHelper.class';
11
import{EnvProperties} from '../../../utils/properties/env-properties';
12

    
13
@Component({
14
    selector: 'claim-insert',
15
    template: `
16

    
17

    
18
  <div class="uk-width-1-1">
19
    <modal-loading [message]= "'Please wait...'"></modal-loading>
20
    <modal-alert (alertOutput)="confirmClose($event)">
21
    </modal-alert>
22
    <div class="uk-clearfix">
23
      <div *ngIf="errorMessage.length > 0">
24
        <div class="uk-alert uk-alert-danger uk-margin-top" role="alert" [innerHTML]="errorMessage"></div>
25
        <div *ngIf="insertedClaims.length>0">{{insertedClaims.length | number}} claims created, follow <a routerLinkActive="router-link-active" routerLink="/myclaims">the link</a> to manage your claims</div>
26
      </div>
27
      <div *ngIf="warningMessage.length > 0">
28
        <div class="uk-alert uk-alert-warning  uk-margin-top" role="alert">{{warningMessage}}</div>
29
      </div>
30
    <div>
31
    <button  *ngIf="!claiming  && showButton" (click)="validateInsertions()"  class="uk-button portal-button uk-float-right"  >Finish</button>
32
  </div>
33
    `
34
})
35
export class ClaimInsertComponent {
36
  constructor (private claimService: ClaimsService, private _router:Router, private route: ActivatedRoute,) {}
37
  ngOnInit() {
38
    this.route.queryParams.subscribe(params => {
39
      this.params = params;
40
    });
41
    // console.info("Inlineentity:" +(this.inlineEntity)?this.inlineEntity+(this.inlineEntity.id)?this.inlineEntity.id:"no id":"null"+ + " show "+ (!this.claiming  && this.showButton) );
42
  }
43

    
44
  params= {};
45
  @Input() public contexts;
46
  @Input() public projects;
47
  @Input() public results;
48
  @Input() public showButton:boolean = true;
49
  @Input() show='claim';
50
  @Input() inlineEntity = null; // the entity from the landing page
51
  @Input() public properties:EnvProperties;
52
  @Output() showChange = new EventEmitter();
53
  @Input() localStoragePrefix:string="";
54
  @ViewChild (ModalLoading) loading : ModalLoading ;
55
  @ViewChild(AlertModal) alert;
56

    
57
  public claiming =false;
58
  public error = false;
59
  public errorMessage = "";
60
  public warningMessage = "";
61
  public claimsTODO:number = 0;
62
  public claims:number = 0;
63

    
64
  private servicesRespond:number = 0;
65
  private insertedClaims=[];
66
  private errorInClaims=[];
67
  private insertedRecords=[];
68
  private errorInRecords=[];
69
public validateInsertions(){
70
  // console.info("Inlineentity:" +(this.inlineEntity)?this.inlineEntity+(this.inlineEntity.id)?this.inlineEntity.id:"no id":"null"+ + " show "+ (!this.claiming  && this.showButton) );
71
    if(this.validate()){
72
      if(this.validateDates()){
73
        this.insertActions();
74
        return true;
75
      }
76
    }
77
    return false;
78
}
79
private insertActions(){
80
  this.servicesRespond = 0;
81
   this.insertedClaims=[];
82
   this.errorInClaims=[];
83
  this.insertedRecords=[];
84
  this.errorInRecords=[];
85
  if(!Session.isLoggedIn()){
86
    this.showButton = false;
87
    localStorage.setItem(this.localStoragePrefix + "projects", JSON.stringify(this.projects));
88
    localStorage.setItem(this.localStoragePrefix + "contexts", JSON.stringify(this.contexts));
89
    localStorage.setItem(this.localStoragePrefix + "results", JSON.stringify(this.results));
90
    if(this.inlineEntity != null){
91
      localStorage.setItem(this.localStoragePrefix + "inlineEntity", JSON.stringify(this.inlineEntity));
92
    }
93

    
94
    this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
95

    
96
  }else{
97
      this.claiming = true;
98
      var user=Session.getUserEmail();
99
       this.loading.open();
100
      var claims = [];
101
      var directclaims = [];
102
      if(this.results ){
103

    
104
          for (var i = 0; i < this.results.length; i++) {
105
              var result=this.results[i];
106
              if(["crossref","datacite","orcid"].indexOf(result.source) != -1){
107
                directclaims.push({"id":result.id, "record":this.createDirectClaim(result,this.projects,this.contexts)});
108
              }
109
              if(this.contexts){
110
                for (var j = 0; j < this.contexts.length; j++) {
111
                  var context = this.contexts[j];
112
                  var claim = this.createContextClaim(result, context, user);
113
                  claims.push(claim);
114
                }
115
              }
116
              if(this.projects){
117
                for (var k = 0; k < this.projects.length; k++) {
118
                  var project = this.projects[k];
119
                  var projectClaim = this.createProjectClaim(result, project, user);
120
                  claims.push(projectClaim);
121
                }
122
              }
123
               if(this.inlineEntity != null){
124
                var resultClaim = this.createResultClaim(this.inlineEntity, result, user);
125
                claims.push(resultClaim);
126
              }
127

    
128
          }
129
        }
130
        if(this.inlineEntity ){
131

    
132
                if(this.contexts){
133
                  for (var j = 0; j < this.contexts.length; j++) {
134
                    var context = this.contexts[j];
135
                    var claim = this.createContextClaim(this.inlineEntity, context, user);
136
                    claims.push(claim);
137
                  }
138
                }
139
                if(this.projects){
140
                  for (var k = 0; k < this.projects.length; k++) {
141
                    var project = this.projects[k];
142
                    var projectClaim = this.createProjectClaim(this.inlineEntity, project, user);
143
                    claims.push(projectClaim);
144
                  }
145
                }
146
          }
147
        //first call direct index service - when call is done (success or error) call isertBulkClaims method to insert claims in DB
148
        if(directclaims.length > 0){
149
          this.claimService.insertDirectRecords(directclaims,this.properties.claimsAPIURL).subscribe(
150
            data => {
151
              this.insertedRecords = data.insertedIds;
152

    
153
                this.errorInRecords = data.errorInClaims;
154
                this.isertBulkClaims(claims);
155
            },
156
            err =>  {
157
              err=err.json();
158
              if(err.insertedIds && err.insertedIds.length >0){
159
                this.insertedRecords = err.insertedIds;
160
              }
161
              if(err.errorInClaims && err.errorInClaims.length >0){
162
                this.errorInRecords = err.errorInClaims;
163
              }
164
              this.isertBulkClaims(claims);
165

    
166
              this.handleError("Error inserting direct records: "+JSON.stringify(directclaims), err);
167
            }
168
          );
169
      }else{
170
        this.isertBulkClaims(claims);
171
      }
172
  }
173

    
174
}
175

    
176
private isertBulkClaims(claims){
177
  this.claimService.insertBulkClaims(claims,this.properties.claimsAPIURL).subscribe(
178
    data => {
179
      this.insertedClaims = data.insertedIds;
180
      this.errorInClaims = data.errorInClaims;
181
      this.afterclaimsInsertion();
182
    },
183
    err =>  {
184
      err=err.json();
185
      if(err.insertedIds && err.insertedIds.length >0){
186
        this.insertedClaims = err.insertedIds;
187
      }
188
      if(err.errorInClaims && err.errorInClaims.length >0){
189
        this.errorInClaims = err.errorInClaims;
190
      }
191
      if(this.projects != null){
192
       localStorage.setItem(this.localStoragePrefix + "projects", JSON.stringify(this.projects));
193
     }
194
     localStorage.setItem(this.localStoragePrefix + "contexts", JSON.stringify(this.contexts));
195
     if(this.results != null){
196
       localStorage.setItem(this.localStoragePrefix + "results", JSON.stringify(this.results));
197
     }
198
     if(this.inlineEntity != null){
199
       localStorage.setItem(this.localStoragePrefix + "inlineEntity", JSON.stringify(this.inlineEntity));
200
     }
201
      this.afterclaimsInsertion();
202

    
203
      this.handleError("Error inserting bulk claims: "+JSON.stringify(claims), err);
204
    }
205
  );
206
}
207
private validate(){
208
  this.warningMessage = "";
209
  this.errorMessage = "";
210
  if( this.results && this.results.length == 0 &&  ( this.inlineEntity == null)){
211
   this.warningMessage = "There are no research results selected.";
212
 }else if((!this.contexts|| this.contexts.length==0 )&&(!this.projects|| this.projects.length==0 )&&  ( this.inlineEntity == null)){
213
   this.warningMessage = "There are no projects or communities to link.";
214
 // }else if (this.inline && !this.inlineEntity){
215
 //   this.errorMessage = "No inline entity";
216
 //   console.log(this.inline + "   "+ this.inlineEntity);
217
 }else{
218
   return true;
219
 }
220
 return false;
221
}
222
private validateDates(){
223
  if(this.projects){
224
    for (var k = 0; k < this.projects.length; k++) {
225
      var project = this.projects[k];
226
      if(this.results){
227
        for (var i = 0; i < this.results.length; i++) {
228
          var result = this.results[i];
229
          if(result.date && result.date != null){
230
            if((project.startDate && result.date < project.startDate) || ( project.endDate && result.date > (project.endDate+5)) ){
231
              this.confirmOpen();
232
              return false;
233
            }
234
          }
235
        }
236
      }
237

    
238

    
239
    }
240
  }
241
  if(this.results){
242
    for (var i = 0; i < this.results.length; i++) {
243
      var result = this.results[i];
244
      if(result.date && result.date != null){
245
         if((result.embargoEndDate && result.embargoEndDate != null) && result.date >result.embargoEndDate ){
246
          this.confirmOpen();
247
          return false;
248
        }
249
      }
250
    }
251
  }
252

    
253
 return true;
254
}
255
private afterclaimsInsertion(){
256

    
257
    this.loading.close();
258
    this.claiming = false;
259

    
260
    if(this.errorInClaims.length == 0 && this.insertedClaims.length > 0  && this.errorInRecords.length == 0){
261
      localStorage.removeItem(this.localStoragePrefix + "projects");
262
      localStorage.removeItem(this.localStoragePrefix + "contexts");
263
      localStorage.removeItem(this.localStoragePrefix + "results");
264
      this._router.navigate( ['/myclaims'],{ queryParams:  this.params } );
265
      this.showChange.emit({
266
        value: this.show
267
      });
268
    }else{
269
      this.errorsInClaimsInsertion();
270
    }
271
}
272
private errorsInClaimsInsertion(){
273
  this.errorMessage = "";
274
  this.loading.close();
275
  this.error =  true;
276
  this.claiming = false;
277
  this.showButton = false;
278
  var text =""
279
  //console.log("Errors: this.errorInRecords.length: "+this.errorInRecords.length+" - this.errorInClaims.length: "+this.errorInClaims.length);
280
  if(this.errorInRecords.length>0){
281
    text+="<div>The following results couldn't automatically inserted to the Openaire Info space: <ul>";
282
    for(var i=0; i< this.errorInRecords.length ; i++){
283
      for(var k=0; k< this.results.length ; k++){
284
        if(this.results[k].id == this.errorInRecords[i]){
285
          text+="<li>Title: \""+this.results[i].title+"\" ("+this.results[i].source+")</li>";
286
        }
287
      }
288
    }
289
    text+="</ul></div>";
290

    
291
  }
292
  if(this.errorInClaims.length > 0){
293
    text+="<div>The following links couldn't be saved: <ul>";
294
    for(var i=0; i< this.errorInClaims.length ; i++){
295
      // var claim =  { claimedBy : user, sourceId : context.concept.id, sourceType : "context", sourceCollectedFrom:"openaire", sourceAccessRights:"OPEN", sourceEmbargoEndDate:"no", targetId :  result.id , targetType : result.type, targetCollectedFrom: result.source, targetAccessRights:result.accessRights, targetEmbargoEndDate: (result.embargoEndDate == null?"":result.embargoEndDate)};
296

    
297
      text+="<li>"+this.errorInClaims[i].sourceType+": "+this.errorInClaims[i].sourceId +" ("+this.errorInClaims[i].sourceCollectedFrom+") link to "+this.errorInClaims[i].targetType+": "+this.errorInClaims[i].targetId +" ("+this.errorInClaims[i].targetCollectedFrom+") </li>";
298

    
299
    }
300
    text+="</ul></div>";
301
  }
302
  this.errorMessage+="<div>An error occured:</div>"+text;
303
  //console.log(text);
304
  //   if(this.inline){
305
  //     this.show = "error";
306
  //     this.showChange.emit({
307
  //       value: this.show
308
  //     });
309
  // }
310

    
311
}
312

    
313

    
314
private createClaim(inlineResult:any, result:any, user:any){
315

    
316
}
317
  private createContextClaim(result:any, context:any, user:any){
318
    var claim =  { claimedBy : user, sourceId : context.concept.id, sourceType : "context", sourceCollectedFrom:"openaire", sourceAccessRights:"OPEN", sourceEmbargoEndDate:"", targetId :  result.id , targetType : result.type, targetCollectedFrom: result.source, targetAccessRights:result.accessRights, targetEmbargoEndDate: (result.embargoEndDate == null?"":result.embargoEndDate)};
319
    return claim;
320
  }
321
  private createProjectClaim(result:any, project:any, user:any){
322
    //project.projectId
323
    // var dummyID = "dummyID";
324
    var claim =  { claimedBy : user, sourceId : project.projectId, sourceType : "project", sourceCollectedFrom:"openaire", sourceAccessRights:"OPEN", sourceEmbargoEndDate:"", targetId :  result.id , targetType : result.type, targetCollectedFrom: result.source, targetAccessRights:result.accessRights, targetEmbargoEndDate: (result.embargoEndDate == null?"":result.embargoEndDate)};
325
    return claim;
326
  }
327
  private createResultClaim(inlineResult:any, result:any, user:any){
328
    var claim =  { claimedBy : user, sourceId : result.id, sourceType : result.type, sourceCollectedFrom: result.source, sourceAccessRights: result.accessRights, sourceEmbargoEndDate: (result.embargoEndDate == null?"":result.embargoEndDate), targetId :  inlineResult.id , targetType : inlineResult.type, targetCollectedFrom: inlineResult.source, targetAccessRights: inlineResult.accessRights, targetEmbargoEndDate: (inlineResult.embargoEndDate == null?"":inlineResult.embargoEndDate)};
329
    return claim;
330
  }
331
createDirectClaim(result, projects, contexts){
332
  var entity = {};
333
  var md5_id = Md5.hashStr(result.id);
334
  entity["originalId"]="userclaim___::"+md5_id;
335
  entity["openaireId"]="userclaim___::"+md5_id;
336
  entity["title"]=result.title;
337
  entity["title"] =(Array.isArray(result.title) && result.title.length > 0 )?result.title[0]:result.title;
338

    
339
  if(result.authors && result.authors.length > 0){
340
    entity["authors"]=result.authors;
341
  }
342
  if(result.publisher){
343
    entity["publisher"]=result.publisher;
344
  }
345
  if(result.description){
346
    entity["description"]=result.description;
347
  }
348
  // entity["language"]=""; no info
349
  entity["type"]=result.type;
350
  if(result.source == "crossref" || result.source == "datacite"){
351
    entity["pids"]= [];//{type:string, value:string}[];
352
    entity["pids"].push({type:"doi",value:result.id})
353
  }
354
  entity["licenseCode"]=result.accessRights;
355
  if(result.accessRights == "EMBARGO"){
356
    entity["embargoEndDate"]=result.embargoEndDate;
357
  }
358
  if(result.type =="publication"){
359
    entity["resourceType"]="0001";
360
  }else if(result.type =="dataset"){
361
    entity["resourceType"]="0021";
362
  }else if(result.type =="software"){
363
    entity["resourceType"]="0029";
364
  }else if(result.type =="other"){
365
    entity["resourceType"]="0020";
366
  }
367
  entity["url"]=result.url;
368
  entity["hostedById"]="openaire____::1256f046-bf1f-4afc-8b47-d0b147148b18";
369
  if(result.source == "crossref"){
370
    entity["collectedFromId"]="openaire____::crossref";
371
  }else if(result.source == "datacite"){
372
    entity["collectedFromId"]="openaire____::datacite";
373
  }else if(result.source == "orcid"){
374
    entity["collectedFromId"]="openaire____::orcid";
375
  }else if(result.source == "orpenaire"){
376
    entity["collectedFromId"]="openaire____::driver";
377
  }
378

    
379
  if(projects.length>0){
380
    entity["linksToProjects"]=[];
381
    for(var i =0; i < projects.length; i++){
382
      // "info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus",
383
      entity["linksToProjects"].push("info:eu-repo/grantAgreement/"+projects[i].funderName+"/"+projects[i].fundingLevel0+"/"+projects[i].code+"/"+projects[i].jurisdiction+"/"+projects[i].projectName+"/"+projects[i].projectAcronym);
384
    }
385
  }
386
  if(contexts.length > 0){
387
    entity["contexts"]=[];
388
    for(var i =0; i < contexts.length; i++){
389
      entity["contexts"].push(contexts[i].concept.id);
390
    }
391
  }
392
  var json = JSON.stringify(entity);
393
  //console.log("\nJSON:\n"+json);
394
  return entity;
395

    
396

    
397

    
398
}
399
  confirmOpen(){
400
    this.alert.cancelButton = true;
401
    this.alert.okButton = true;
402
    this.alert.alertTitle = "Invalid dates";
403
    this.alert.message = "There is a research result whose  publication date  is after project end date or before project start date. Or embargo end date of a research result is before research result's publication date.";
404
    this.alert.okButtonText = "Proceed anyway";
405
    this.alert.cancelButtonText = "Cancel";
406
    this.alert.open();
407
  }
408
   confirmClose(data){
409
    this.insertActions();
410
  }
411

    
412
  private handleError(message: string, error) {
413
      console.error("Insert Claim (component): "+message, error);
414
  }
415
}
(1-1/2)