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

    
12
@Component({
13
    selector: 'claim-insert',
14
    template: `
15
    <div *ngIf="errorMessage.length > 0">
16
      <div class="uk-alert uk-alert-danger" role="alert" [innerHTML]="errorMessage"></div>
17
      <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>
18
    </div>
19
    <div *ngIf="warningMessage.length > 0">
20
      <div class="uk-alert uk-alert-warning" role="alert">{{warningMessage}}</div>
21
    </div>
22

    
23

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

    
36

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

    
45
  @ViewChild (ModalLoading) loading : ModalLoading ;
46
  @ViewChild(AlertModal) alert;
47

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

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

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

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

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

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

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

    
148
}
149

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

    
203

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

    
219
 return true;
220
}
221
private afterclaimsInsertion(){
222

    
223
    this.loading.close();
224
    this.claiming = false;
225

    
226
    if(this.errorInClaims.length == 0 && this.insertedClaims.length > 0  && this.errorInRecords.length == 0){
227

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

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

    
261
      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>";
262

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

    
275
}
276

    
277

    
278

    
279
  private createContextClaim(result:any, context:any, user:any){
280
    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)};
281
    return claim;
282
  }
283
  private createProjectClaim(result:any, project:any, user:any){
284
    //project.projectId
285
    // var dummyID = "dummyID";
286
    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)};
287
    return claim;
288
  }
289
  private createResultClaim(inlineResult:any, result:any, user:any){
290
    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)};
291
    return claim;
292
  }
293
createDirectClaim(result, projects, contexts){
294
  var entity = {};
295
  var md5_id = Md5.hashStr(result.id);
296
  entity["originalId"]="userclaim___::"+md5_id;
297
  entity["openaireId"]="userclaim___::"+md5_id;
298
  entity["title"]=result.title;
299
  entity["title"] =(Array.isArray(result.title) && result.title.length > 0 )?result.title[0]:result.title;
300

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

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

    
356

    
357

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