Project

General

Profile

1
import {Component, Input, Output, EventEmitter, ViewChild} from '@angular/core';
2
import {Observable}       from 'rxjs/Observable';
3
import {Router} 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 {ErrorCodes} from '../../../login/utils/guardHelper.class';
11
import{EnvProperties} from '../../../utils/properties/env-properties';
12

    
13
@Component({
14
    selector: 'claim-insert',
15
    template: `
16
    <div *ngIf="errorMessage.length > 0">
17
      <div class="uk-alert uk-alert-danger" role="alert" [innerHTML]="errorMessage"></div>
18
      <div *ngIf="insertedClaims.length>0">There are {{insertedClaims.length}} claims, follow <a routerLinkActive="router-link-active" routerLink="/myclaims">the link</a> to manage your claims</div>
19
    </div>
20
    <div *ngIf="warningMessage.length > 0">
21
      <div class="uk-alert uk-alert-warning" role="alert">{{warningMessage}}</div>
22
    </div>
23

    
24

    
25
    <modal-loading [message]= "'Please wait...'"></modal-loading>
26
    <modal-alert (alertOutput)="confirmClose($event)">
27
    </modal-alert>
28
    <button  *ngIf="!claiming  && showButton" (click)="validateInsertions()"  class="uk-button uk-button-primary"  >Finish</button>
29
    `
30
})
31
export class ClaimInsertComponent {
32
  constructor (private claimService: ClaimsService, private _router:Router) {}
33
  ngOnInit() {
34
    // console.info("Inlineentity:" +(this.inlineEntity)?this.inlineEntity+(this.inlineEntity.id)?this.inlineEntity.id:"no id":"null"+ + " show "+ (!this.claiming  && this.showButton) );
35
  }
36

    
37

    
38
  @Input() public contexts;
39
  @Input() public projects;
40
  @Input() public results;
41
  @Input() public showButton:boolean = true;
42
  @Input() show='claim';
43
  @Input() inlineEntity = null; // the entity from the landing page
44
  @Input() public properties:EnvProperties;
45
  @Output() showChange = new EventEmitter();
46

    
47
  @ViewChild (ModalLoading) loading : ModalLoading ;
48
  @ViewChild(AlertModal) alert;
49

    
50
  public claiming =false;
51
  public error = false;
52
  public errorMessage = "";
53
  public warningMessage = "";
54
  public claimsTODO:number = 0;
55
  public claims:number = 0;
56

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

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

    
89
  }else{
90
      this.claiming = true;
91
      var user=Session.getUserEmail();
92
       this.loading.open();
93
      var claims = [];
94
      var directclaims = [];
95
      if(this.results){
96
        console.info("results: "+this.results.length);
97

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

    
122
          }
123
        }
124
        //first call direct index service - when call is done (success or error) call isertBulkClaims method to insert claims in DB
125
        console.info("\n\ndirectclaims: "+directclaims.length+"\n\n");
126
        if(directclaims.length > 0){
127
          this.claimService.insertDirectRecords(directclaims,this.properties.claimsAPIURL).subscribe(
128
            data => {
129
              this.insertedRecords = data.insertedIds;
130

    
131
                this.errorInRecords = data.errorInClaims;
132
                this.isertBulkClaims(claims);
133
            },
134
            err =>  {
135
              err=err.json();
136
              if(err.insertedIds && err.insertedIds.length >0){
137
                this.insertedRecords = err.insertedIds;
138
              }
139
              if(err.errorInClaims && err.errorInClaims.length >0){
140
                this.errorInRecords = err.errorInClaims;
141
              }
142
              this.isertBulkClaims(claims);
143
            }
144
          );
145
      }else{
146
        this.isertBulkClaims(claims);
147
      }
148
  }
149

    
150
}
151

    
152
private isertBulkClaims(claims){
153
  console.info("try to insert "+claims.length+" claims");
154
  this.claimService.insertBulkClaims(claims,this.properties.claimsAPIURL).subscribe(
155
    data => {
156
      this.insertedClaims = data.insertedIds;
157
      this.errorInClaims = data.errorInClaims;
158
      this.afterclaimsInsertion();
159
    },
160
    err =>  {
161
      err=err.json();
162
      if(err.insertedIds && err.insertedIds.length >0){
163
        this.insertedClaims = err.insertedIds;
164
      }
165
      if(err.errorInClaims && err.errorInClaims.length >0){
166
        this.errorInClaims = err.errorInClaims;
167
      }
168
      this.afterclaimsInsertion();
169
    }
170
  );
171
}
172
private validate(){
173
  this.warningMessage = "";
174
  this.errorMessage = "";
175
  if( this.results && this.results.length == 0 &&  ( this.inlineEntity == null)){
176
   this.warningMessage = "There are no research results selected.";
177
 }else if((!this.contexts|| this.contexts.length==0 )&&(!this.projects|| this.projects.length==0 )&&  ( this.inlineEntity == null)){
178
   this.warningMessage = "There are no projects or communities to link.";
179
 // }else if (this.inline && !this.inlineEntity){
180
 //   this.errorMessage = "No inline entity";
181
 //   console.log(this.inline + "   "+ this.inlineEntity);
182
 }else{
183
   return true;
184
 }
185
 return false;
186
}
187
private validateDates(){
188
  if(this.projects){
189
    for (var k = 0; k < this.projects.length; k++) {
190
      var project = this.projects[k];
191
      console.info(project.startDate+" "+project.endDate + " "+project.projectAcronym);
192
      if(this.results){
193
        for (var i = 0; i < this.results.length; i++) {
194
          var result = this.results[i];
195
          if(result.date && result.date != null){
196
            console.info("Date :"+ result.date + " & embargoEndDate :" +result.embargoEndDate );
197
            if((project.startDate && result.date < project.startDate) || ( project.endDate && result.date > (project.endDate+5)) ){
198
              this.confirmOpen();
199
              return false;
200
            }
201
          }
202
        }
203
      }
204

    
205

    
206
    }
207
  }
208
  if(this.results){
209
    for (var i = 0; i < this.results.length; i++) {
210
      var result = this.results[i];
211
      if(result.date && result.date != null){
212
        console.info("Date :"+ result.date + " & embargoEndDate :" +result.embargoEndDate );
213
         if((result.embargoEndDate && result.embargoEndDate != null) && result.date >result.embargoEndDate ){
214
          this.confirmOpen();
215
          return false;
216
        }
217
      }
218
    }
219
  }
220

    
221
 return true;
222
}
223
private afterclaimsInsertion(){
224

    
225
    this.loading.close();
226
    this.claiming = false;
227

    
228
    if(this.errorInClaims.length == 0 && this.insertedClaims.length > 0  && this.errorInRecords.length == 0){
229

    
230
        this._router.navigate( ['/myclaims'] );
231
      this.showChange.emit({
232
        value: this.show
233
      });
234
    }else{
235
      this.errorsInClaimsInsertion();
236
    }
237
}
238
private errorsInClaimsInsertion(){
239
  this.errorMessage = "";
240
  this.loading.close();
241
  this.error =  true;
242
  this.claiming = false;
243
  this.showButton = false;
244
  var text =""
245
  console.log("Errors: this.errorInRecords.length: "+this.errorInRecords.length+" - this.errorInClaims.length: "+this.errorInClaims.length);
246
  if(this.errorInRecords.length>0){
247
    text+="<div>The following records couldn't automatically inserted to the Openaire Info space: <ul>";
248
    for(var i=0; i< this.errorInRecords.length ; i++){
249
      for(var k=0; k< this.results.length ; k++){
250
        if(this.results[k].id == this.errorInRecords[i]){
251
          text+="<li>"+this.results[i].title+" from "+this.results[i].source+"</li>";
252
        }
253
      }
254
    }
255
    text+="</ul></div>";
256

    
257
  }
258
  if(this.errorInClaims.length > 0){
259
    text+="<div>The following links couldn't be saved: <ul>";
260
    for(var i=0; i< this.errorInClaims.length ; i++){
261
      // 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)};
262

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

    
265
    }
266
    text+="</ul></div>";
267
  }
268
  this.errorMessage+="<div>An error occured:</div>"+text;
269
  console.log(text);
270
  //   if(this.inline){
271
  //     this.show = "error";
272
  //     this.showChange.emit({
273
  //       value: this.show
274
  //     });
275
  // }
276

    
277
}
278

    
279

    
280

    
281
  private createContextClaim(result:any, context:any, user:any){
282
    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)};
283
    return claim;
284
  }
285
  private createProjectClaim(result:any, project:any, user:any){
286
    //project.projectId
287
    // var dummyID = "dummyID";
288
    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)};
289
    return claim;
290
  }
291
  private createResultClaim(inlineResult:any, result:any, user:any){
292
    var claim =  { claimedBy : user, sourceId : result.id, sourceType : result.type, sourceCollectedFrom: result.source, sourceAccessRights: result.accessRights, sourceEmbargoEndDate: result.embargoEndDate, targetId :  inlineResult.id , targetType : inlineResult.type, targetCollectedFrom: inlineResult.source, targetAccessRights: inlineResult.accessRights, targetEmbargoEndDate: (inlineResult.embargoEndDate == null?"":inlineResult.embargoEndDate)};
293
    return claim;
294
  }
295
createDirectClaim(result, projects, contexts){
296
  var entity = {};
297
  var md5_id = Md5.hashStr(result.id);
298
  entity["originalId"]="userclaim___::"+md5_id;
299
  entity["openaireId"]="userclaim___::"+md5_id;
300
  entity["title"]=result.title;
301
  entity["title"] =(Array.isArray(result.title) && result.title.length > 0 )?result.title[0]:result.title;
302

    
303
  if(result.authors && result.authors.length > 0){
304
    entity["authors"]=result.authors;
305
  }
306
  if(result.publisher){
307
    entity["publisher"]=result.publisher;
308
  }
309
  if(result.description){
310
    entity["description"]=result.description;
311
  }
312
  // entity["language"]=""; no info
313
  entity["type"]=result.type;
314
  if(result.source == "crossref" || result.source == "datacite"){
315
    entity["pids"]= [];//{type:string, value:string}[];
316
    entity["pids"].push({type:"doi",value:result.id})
317
  }
318
  entity["licenseCode"]=result.accessRights;
319
  if(result.accessRights == "EMBARGO"){
320
    entity["embargoEndDate"]=result.embargoEndDate;
321
  }
322
  if(result.type =="publication"){
323
    entity["resourceType"]="0001";
324
  }else if(result.type =="dataset"){
325
    entity["resourceType"]="0021";
326
  }else if(result.type =="software"){
327
    entity["resourceType"]="0029";
328
  }
329
  entity["url"]=result.url;
330
  entity["hostedById"]="openaire____::1256f046-bf1f-4afc-8b47-d0b147148b18";
331
  if(result.source == "crossref"){
332
    entity["collectedFromId"]="openaire____::crossref";
333
  }else if(result.source == "datacite"){
334
    entity["collectedFromId"]="openaire____::datacite";
335
  }else if(result.source == "orcid"){
336
    entity["collectedFromId"]="openaire____::orcid";
337
  }else if(result.source == "orpenaire"){
338
    entity["collectedFromId"]="openaire____::driver";
339
  }
340

    
341
  if(projects.length>0){
342
    entity["linksToProjects"]=[];
343
    for(var i =0; i < projects.length; i++){
344
      // "info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus",
345
      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);
346
    }
347
  }
348
  if(contexts.length > 0){
349
    entity["contexts"]=[];
350
    for(var i =0; i < contexts.length; i++){
351
      entity["contexts"].push(contexts[i].concept.id);
352
    }
353
  }
354
  var json = JSON.stringify(entity);
355
  console.log("\nJSON:\n"+json);
356
  return entity;
357

    
358

    
359

    
360
}
361
  confirmOpen(){
362
    this.alert.cancelButton = true;
363
    this.alert.okButton = true;
364
    this.alert.alertTitle = "Invalid dates";
365
    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.";
366
    this.alert.okButtonText = "Proceed anyway";
367
    this.alert.cancelButtonText = "Cancel";
368
    this.alert.open();
369
  }
370
   confirmClose(data){
371
    this.insertActions();
372
  }
373
}
(1-1/2)