openaire-library/claims/linking/insertClaim/insertClaim.component.ts

408 lines
16 KiB
TypeScript
Raw Normal View History

import {Component, Input, Output, EventEmitter, ViewChild} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Router, ActivatedRoute} from '@angular/router';
import {ClaimsService} from '../../claim-utils/service/claims.service';
import {ModalLoading} from '../../../utils/modal/loading.component';
import {AlertModal} from '../../../utils/modal/alert';
import {Md5} from 'ts-md5/dist/md5';
import {Session} from '../../../login/utils/helper.class';
import {LoginErrorCodes} from '../../../login/utils/guardHelper.class';
import{EnvProperties} from '../../../utils/properties/env-properties';
@Component({
selector: 'claim-insert',
template: `
<div class="uk-width-1-1">
<modal-loading [message]= "'Please wait...'"></modal-loading>
<modal-alert (alertOutput)="confirmClose($event)">
</modal-alert>
<div class="uk-clearfix">
<div *ngIf="errorMessage.length > 0">
<div class="uk-alert uk-alert-danger uk-margin-top" role="alert" [innerHTML]="errorMessage"></div>
<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>
</div>
<div *ngIf="warningMessage.length > 0">
<div class="uk-alert uk-alert-warning uk-margin-top" role="alert">{{warningMessage}}</div>
</div>
<div>
<button *ngIf="!claiming && showButton" (click)="validateInsertions()" class="uk-button portal-button uk-float-right" >Finish</button>
</div>
`
})
export class ClaimInsertComponent {
constructor (private claimService: ClaimsService, private _router:Router, private route: ActivatedRoute,) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.params = params;
});
// console.info("Inlineentity:" +(this.inlineEntity)?this.inlineEntity+(this.inlineEntity.id)?this.inlineEntity.id:"no id":"null"+ + " show "+ (!this.claiming && this.showButton) );
}
params= {};
@Input() public contexts;
@Input() public projects;
@Input() public results;
@Input() public showButton:boolean = true;
@Input() show='claim';
@Input() inlineEntity = null; // the entity from the landing page
@Input() public properties:EnvProperties;
@Output() showChange = new EventEmitter();
@Input() localStoragePrefix:string="";
@ViewChild (ModalLoading) loading : ModalLoading ;
@ViewChild(AlertModal) alert;
public claiming =false;
public error = false;
public errorMessage = "";
public warningMessage = "";
public claimsTODO:number = 0;
public claims:number = 0;
private servicesRespond:number = 0;
private insertedClaims=[];
private errorInClaims=[];
private insertedRecords=[];
private errorInRecords=[];
public validateInsertions(){
// console.info("Inlineentity:" +(this.inlineEntity)?this.inlineEntity+(this.inlineEntity.id)?this.inlineEntity.id:"no id":"null"+ + " show "+ (!this.claiming && this.showButton) );
if(this.validate()){
if(this.validateDates()){
this.insertActions();
return true;
}
}
return false;
}
private insertActions(){
this.servicesRespond = 0;
this.insertedClaims=[];
this.errorInClaims=[];
this.insertedRecords=[];
this.errorInRecords=[];
if(!Session.isLoggedIn()){
this.showButton = false;
localStorage.setItem(this.localStoragePrefix + "projects", JSON.stringify(this.projects));
localStorage.setItem(this.localStoragePrefix + "contexts", JSON.stringify(this.contexts));
localStorage.setItem(this.localStoragePrefix + "results", JSON.stringify(this.results));
if(this.inlineEntity != null){
localStorage.setItem(this.localStoragePrefix + "inlineEntity", JSON.stringify(this.inlineEntity));
}
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
}else{
this.claiming = true;
var user=Session.getUserEmail();
this.loading.open();
var claims = [];
var directclaims = [];
if(this.results ){
for (var i = 0; i < this.results.length; i++) {
var result=this.results[i];
if(["crossref","datacite","orcid"].indexOf(result.source) != -1){
directclaims.push({"id":result.id, "record":this.createDirectClaim(result,this.projects,this.contexts)});
}
if(this.contexts){
for (var j = 0; j < this.contexts.length; j++) {
var context = this.contexts[j];
var claim = this.createContextClaim(result, context, user);
claims.push(claim);
}
}
if(this.projects){
for (var k = 0; k < this.projects.length; k++) {
var project = this.projects[k];
var projectClaim = this.createProjectClaim(result, project, user);
claims.push(projectClaim);
}
}
if(this.inlineEntity != null){
var resultClaim = this.createResultClaim(this.inlineEntity, result, user);
claims.push(resultClaim);
}
}
}
if(this.inlineEntity ){
if(this.contexts){
for (var j = 0; j < this.contexts.length; j++) {
var context = this.contexts[j];
var claim = this.createContextClaim(this.inlineEntity, context, user);
claims.push(claim);
}
}
if(this.projects){
for (var k = 0; k < this.projects.length; k++) {
var project = this.projects[k];
var projectClaim = this.createProjectClaim(this.inlineEntity, project, user);
claims.push(projectClaim);
}
}
}
//first call direct index service - when call is done (success or error) call isertBulkClaims method to insert claims in DB
if(directclaims.length > 0){
this.claimService.insertDirectRecords(directclaims,this.properties.claimsAPIURL).subscribe(
data => {
this.insertedRecords = data.insertedIds;
this.errorInRecords = data.errorInClaims;
this.isertBulkClaims(claims);
},
err => {
err=err.json();
if(err.insertedIds && err.insertedIds.length >0){
this.insertedRecords = err.insertedIds;
}
if(err.errorInClaims && err.errorInClaims.length >0){
this.errorInRecords = err.errorInClaims;
}
this.isertBulkClaims(claims);
}
);
}else{
this.isertBulkClaims(claims);
}
}
}
private isertBulkClaims(claims){
this.claimService.insertBulkClaims(claims,this.properties.claimsAPIURL).subscribe(
data => {
this.insertedClaims = data.insertedIds;
this.errorInClaims = data.errorInClaims;
this.afterclaimsInsertion();
},
err => {
err=err.json();
if(err.insertedIds && err.insertedIds.length >0){
this.insertedClaims = err.insertedIds;
}
if(err.errorInClaims && err.errorInClaims.length >0){
this.errorInClaims = err.errorInClaims;
}
if(this.projects != null){
localStorage.setItem(this.localStoragePrefix + "projects", JSON.stringify(this.projects));
}
localStorage.setItem(this.localStoragePrefix + "contexts", JSON.stringify(this.contexts));
if(this.results != null){
localStorage.setItem(this.localStoragePrefix + "results", JSON.stringify(this.results));
}
if(this.inlineEntity != null){
localStorage.setItem(this.localStoragePrefix + "inlineEntity", JSON.stringify(this.inlineEntity));
}
this.afterclaimsInsertion();
}
);
}
private validate(){
this.warningMessage = "";
this.errorMessage = "";
if( this.results && this.results.length == 0 && ( this.inlineEntity == null)){
this.warningMessage = "There are no research results selected.";
}else if((!this.contexts|| this.contexts.length==0 )&&(!this.projects|| this.projects.length==0 )&& ( this.inlineEntity == null)){
this.warningMessage = "There are no projects or communities to link.";
// }else if (this.inline && !this.inlineEntity){
// this.errorMessage = "No inline entity";
// console.log(this.inline + " "+ this.inlineEntity);
}else{
return true;
}
return false;
}
private validateDates(){
if(this.projects){
for (var k = 0; k < this.projects.length; k++) {
var project = this.projects[k];
if(this.results){
for (var i = 0; i < this.results.length; i++) {
var result = this.results[i];
if(result.date && result.date != null){
if((project.startDate && result.date < project.startDate) || ( project.endDate && result.date > (project.endDate+5)) ){
this.confirmOpen();
return false;
}
}
}
}
}
}
if(this.results){
for (var i = 0; i < this.results.length; i++) {
var result = this.results[i];
if(result.date && result.date != null){
if((result.embargoEndDate && result.embargoEndDate != null) && result.date >result.embargoEndDate ){
this.confirmOpen();
return false;
}
}
}
}
return true;
}
private afterclaimsInsertion(){
this.loading.close();
this.claiming = false;
if(this.errorInClaims.length == 0 && this.insertedClaims.length > 0 && this.errorInRecords.length == 0){
localStorage.removeItem(this.localStoragePrefix + "projects");
localStorage.removeItem(this.localStoragePrefix + "contexts");
localStorage.removeItem(this.localStoragePrefix + "results");
this._router.navigate( ['/myclaims'],{ queryParams: this.params } );
this.showChange.emit({
value: this.show
});
}else{
this.errorsInClaimsInsertion();
}
}
private errorsInClaimsInsertion(){
this.errorMessage = "";
this.loading.close();
this.error = true;
this.claiming = false;
this.showButton = false;
var text =""
//console.log("Errors: this.errorInRecords.length: "+this.errorInRecords.length+" - this.errorInClaims.length: "+this.errorInClaims.length);
if(this.errorInRecords.length>0){
text+="<div>The following results couldn't automatically inserted to the Openaire Info space: <ul>";
for(var i=0; i< this.errorInRecords.length ; i++){
for(var k=0; k< this.results.length ; k++){
if(this.results[k].id == this.errorInRecords[i]){
text+="<li>Title: \""+this.results[i].title+"\" ("+this.results[i].source+")</li>";
}
}
}
text+="</ul></div>";
}
if(this.errorInClaims.length > 0){
text+="<div>The following links couldn't be saved: <ul>";
for(var i=0; i< this.errorInClaims.length ; i++){
// 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)};
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>";
}
text+="</ul></div>";
}
this.errorMessage+="<div>An error occured:</div>"+text;
//console.log(text);
// if(this.inline){
// this.show = "error";
// this.showChange.emit({
// value: this.show
// });
// }
}
private createClaim(inlineResult:any, result:any, user:any){
}
private createContextClaim(result:any, context:any, user:any){
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)};
return claim;
}
private createProjectClaim(result:any, project:any, user:any){
//project.projectId
// var dummyID = "dummyID";
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)};
return claim;
}
private createResultClaim(inlineResult:any, result:any, user:any){
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)};
return claim;
}
createDirectClaim(result, projects, contexts){
var entity = {};
var md5_id = Md5.hashStr(result.id);
entity["originalId"]="userclaim___::"+md5_id;
entity["openaireId"]="userclaim___::"+md5_id;
entity["title"]=result.title;
entity["title"] =(Array.isArray(result.title) && result.title.length > 0 )?result.title[0]:result.title;
if(result.authors && result.authors.length > 0){
entity["authors"]=result.authors;
}
if(result.publisher){
entity["publisher"]=result.publisher;
}
if(result.description){
entity["description"]=result.description;
}
// entity["language"]=""; no info
entity["type"]=result.type;
if(result.source == "crossref" || result.source == "datacite"){
entity["pids"]= [];//{type:string, value:string}[];
entity["pids"].push({type:"doi",value:result.id})
}
entity["licenseCode"]=result.accessRights;
if(result.accessRights == "EMBARGO"){
entity["embargoEndDate"]=result.embargoEndDate;
}
if(result.type =="publication"){
entity["resourceType"]="0001";
}else if(result.type =="dataset"){
entity["resourceType"]="0021";
}else if(result.type =="software"){
entity["resourceType"]="0029";
}else if(result.type =="other"){
entity["resourceType"]="0020";
}
entity["url"]=result.url;
entity["hostedById"]="openaire____::1256f046-bf1f-4afc-8b47-d0b147148b18";
if(result.source == "crossref"){
entity["collectedFromId"]="openaire____::crossref";
}else if(result.source == "datacite"){
entity["collectedFromId"]="openaire____::datacite";
}else if(result.source == "orcid"){
entity["collectedFromId"]="openaire____::orcid";
}else if(result.source == "orpenaire"){
entity["collectedFromId"]="openaire____::driver";
}
if(projects.length>0){
entity["linksToProjects"]=[];
for(var i =0; i < projects.length; i++){
// "info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus",
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);
}
}
if(contexts.length > 0){
entity["contexts"]=[];
for(var i =0; i < contexts.length; i++){
entity["contexts"].push(contexts[i].concept.id);
}
}
var json = JSON.stringify(entity);
//console.log("\nJSON:\n"+json);
return entity;
}
confirmOpen(){
this.alert.cancelButton = true;
this.alert.okButton = true;
this.alert.alertTitle = "Invalid dates";
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.";
this.alert.okButtonText = "Proceed anyway";
this.alert.cancelButtonText = "Cancel";
this.alert.open();
}
confirmClose(data){
this.insertActions();
}
}