Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
4
import {Observable, throwError} from 'rxjs';
5
import {AutoCompleteValue} from '../../searchPages/searchUtils/searchHelperClasses.class';
6

    
7

    
8

    
9
import{EnvProperties} from '../properties/env-properties';
10

    
11
import {StringUtils} from '../string-utils.class';
12
import {catchError, map} from "rxjs/operators";
13
@Injectable()
14
export class EntitiesSearchService {
15
    public ready:boolean = false;
16
    constructor(private http: HttpClient ) {}
17

    
18
    searchProjectsByFunder(keyword:string, funderId:string, properties:EnvProperties ):any {
19
      this.ready = false;
20
      let url = properties.searchResourcesAPIURL;
21
      //console.log("Funder is " + funderId);
22
      url = url+"?query=(oaftype exact project and deletedbyinference=false) ";
23
      if(keyword!= null && keyword != ''  ) {
24
        url +=  'and ((projectcode_nt exact "'+keyword+'" )or('+keyword+')) ' ;
25
        url+=((funderId && funderId.length > 0 )?("&fq=funder exact " + '"'+funderId+ '"'):"");
26
      }
27

    
28
      url += "&page=0&size=10";
29
      url += "&format=json";
30
      //console.log("URL " + url);
31
      // let url =  properties.searchAPIURLLAst+"projects?"+((keyword && keyword.length > 0)?("q=" +keyword):"")+((funderId && funderId.length > 0 )?"&fq=funder exact " + '"'+funderId+ '"':"")+"&size=10&page=0&format=json";
32
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
33
      .then(request =>
34
        {
35
          //request = request.json().results;
36
          request = request['results'];
37
          this.ready = true;
38
          return this.parse(request,"oaf:project","project");
39
        }).catch((ex) => {
40
          console.error('An error occured', ex);
41
          return  [{id:'-2',label:'Error'}];;
42
        });
43
      }
44
      searchByDepositType(keyword:string, DepositType:string, properties:EnvProperties ):any {
45
        this.ready = false;
46

    
47
        let link = properties.searchResourcesAPIURL;
48

    
49
        let url = link+"?query=";
50
        if(keyword!= null && keyword != ''  ) {
51
          /*url += "((oaftype exact organization and deletedbyinference=false and "+
52
            "(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy or relprojectid=* or reldatasourcecompatibilityid = native))"+
53
            " and ((organizationlegalname all "+'"'+keyword+'"'+") or (organizationlegalshortname all "+'"'+keyword+'"'+")) " +
54
            // "and " + this.quote(params) + " " +
55
            "and (collectedfrom exact "+StringUtils.quote(StringUtils.URIEncode(DepositType))+")) "*/
56

    
57
            // in search there is this filter:
58
            //reldatasourcecompatibilityid exact driver or reldatasourcecompatibilityid exact driver-openaire2.0 or reldatasourcecompatibilityid exact openaire2.0 or reldatasourcecompatibilityid exact openaire3.0 or reldatasourcecompatibilityid exact openaire2.0_data or reldatasourcecompatibilityid exact hostedBy or relproject=*
59

    
60

    
61
          //url += "((oaftype exact organization and deletedbyinference=false )"+
62
          url += "((oaftype exact organization and deletedbyinference=false and"+
63
            "(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy or relprojectid=* or reldatasourcecompatibilityid = native))"+
64
            " and ((organizationlegalname all "+'"'+keyword+'"'+") or (organizationlegalshortname all "+'"'+keyword+'"'+")) " +
65
            // "and " + this.quote(params) + " " +
66
            //"and (collectedfrom exact "+StringUtils.quote(StringUtils.URIEncode(DepositType))+")) "
67
            ")";
68
        }
69

    
70
        url += "&page=0&size=10";
71
        url += "&format=json";
72

    
73
        // let url =  properties.searchAPIURLLAst+"projects?"+((keyword && keyword.length > 0)?("q=" +keyword):"")+((funderId && funderId.length > 0 )?"&fq=funderid exact " + '"'+funderId+ '"':"")+"&size=10&page=0&format=json";
74
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
75
        .then(request =>
76
          {
77
            //request = request.json().results;
78
            request = request['results'];
79
            //console.log(request);
80
            this.ready = true;
81
            return this.parse(request,"oaf:organization","organization");
82
          }).catch((ex) => {
83
            console.error('An error occured', ex);
84
            return  [{id:'-2',label:'Error'}];;
85
          });
86
        }
87

    
88
    searchByType(keyword:string,type:string, properties:EnvProperties ){
89
       if (type == "project"){
90
         return  this.searchEntity(keyword,"projects","oaf:project","project", properties);
91
      }else if (type == "dataset"){
92
        return  this.searchEntity(keyword,"datasets","oaf:result","dataset", properties);
93
      }else if (type == "datasource" || type == "hostedBy" || type== "collectedFrom"){
94
        return  this.searchEntity(keyword,"datasources","oaf:datasource","datasource", properties);
95
      }else if (type == "publication"){
96
        return  this.searchEntity(keyword,"publications","oaf:result","publication", properties);
97
      }else if (type == "organization"){
98
        return  this.searchEntity(keyword,"organizations","oaf:organization","organization", properties);
99

    
100
      }
101

    
102
    }
103
    fetchByType(id:string,type:string, properties:EnvProperties ){
104
       if (type == "project"){
105
         return  this.fetchEntity(id,"projects","oaf:project","project", properties);
106
      }else if (type == "dataset"){
107
        return  this.fetchEntity(id,"datasets","oaf:result","dataset", properties);
108
      }else if (type == "datasource"  || type == "hostedBy" || type== "collectedFrom"){
109
        return  this.fetchEntity(id,"datasources","oaf:datasource","datasource", properties);
110
      }else if (type == "publication"){
111
        return  this.fetchEntity(id,"publications","oaf:result","publication", properties);
112
      }else if (type == "organization"){
113
        return  this.fetchEntity(id,"organizations","oaf:organization","organization", properties);
114

    
115
      }
116

    
117
    }
118
private searchEntity (keyword: string,APIname:string,oafEntityType:string, type:string, properties:EnvProperties ):any {
119
      let link = properties.searchAPIURLLAst+APIname;
120
      return this.search(link,keyword,oafEntityType,type, properties)
121

    
122
}
123
private fetchEntity (id: string,APIname:string,oafEntityType:string, type:string, properties:EnvProperties ):any {
124
    let link = properties.searchAPIURLLAst+APIname;
125
    return this.fetch(link,id,oafEntityType,type, properties)
126
}
127
private fetch (link,id,oafEntityType,type, properties:EnvProperties ){
128
  this.ready = false;
129
  let url = link+"/"+id+"?format=json";
130
  return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
131
    //.map(request => <any> request.json())
132
    // .do(res => console.info(res))
133
    .pipe(map(request => {
134
      this.ready = true;
135
      return this.parse(request,oafEntityType,type);
136
    }))
137
    .pipe(catchError((ex) => {
138
      console.error('An error occured', ex);
139
      return  [{id:'-2',label:'Error'}];;
140
    }));
141

    
142
}
143
    private search (link,keyword,oafEntityType,type, properties:EnvProperties ){
144
      this.ready = false;
145
      let url = link+"?";
146
      if(keyword!= null && keyword != ''  ) {
147
          if(type=="project") {
148
            //name, title, acronym, grantid
149
            url += "fq="+'(projectcode_nt="'+keyword+'" ) or (fundershortname='+'"'+keyword+ '"'+') or (projectacronym="'+keyword+'" ) or (projecttitle="'+keyword+'")';
150
          } else if(type=="organization") {
151
            //name fields
152
            url += "fq="+'(organizationlegalname="'+keyword+'" ) or (organizationlegalshortname='+'"'+keyword+ '")';
153
          } else {
154
            url += "q="+ keyword;
155
          }
156
      }
157

    
158
      url += "&page=0&size="+10+"&format=json";
159
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
160
                 .then(request =>
161
                   {
162
                     //request = request.json().results;
163
                     request = request['results'];
164
                     this.ready = true;
165
                     return this.parse(request,oafEntityType,type);
166
                   }).catch((ex) => {
167
                     console.error('An error occured', ex);
168
                     return [{id:'-2',label:'Error'}];
169
                   });
170

    
171

    
172
    }
173

    
174
    private parse(data: any,oafEntityType:string, type:string){
175
      var array:any =[]
176
      let length = Array.isArray(data) ? data.length : 1;
177

    
178
      for(let i=0; i<length; i++) {
179
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity'][oafEntityType] : data['result']['metadata']['oaf:entity'][oafEntityType];
180

    
181
            var value:any={} ;
182
            if(resData['title']){
183
              if(Array.isArray(resData['title'])) {
184
                    value.label = resData['title'][0];
185
              } else {
186
                    value.label = resData['title'];
187
              }
188
              if(oafEntityType=="oaf:result"){
189
                value.label = value.label.content;
190
                value.result = resData;
191
              }
192
            }else if(resData["fullname"]){
193
              if(Array.isArray(resData["fullname"])) {
194
                    value.label = resData["fullname"][0];
195
              } else {
196
                    value.label = resData["fullname"];
197
              }
198
            }else if(resData["legalname"]){
199

    
200
              if(Array.isArray(resData["legalname"])) {
201
                    value.label = resData["legalname"][0];
202
              } else {
203
                    value.label = resData["legalname"];
204
              }
205
              if(resData["legalshortname"]){
206

    
207
                if(Array.isArray(resData["legalshortname"])) {
208
                      value.label += " (" + resData["legalshortname"][0] +")";
209
                } else {
210
                      value.label += " (" +  resData["legalshortname"] +")";
211
                }
212
              }
213

    
214
            }else if(resData["officialname"]){
215

    
216
              if(Array.isArray(resData["officialname"])) {
217
                    value.label = resData["officialname"][0];
218
              } else {
219
                    value.label = resData["officialname"];
220
              }
221
            }
222

    
223
           value.id = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
224

    
225
             if(type=="project"){
226
                  value.projectAcronym = resData['acronym'];
227
                  value.projectName = value.label;
228
                  value.endDate = null;
229
                  value.startDate = null;
230
                  value.funderId = "";
231
                  value.funderName = "";
232
                  value.jurisdiction = "";
233
                  value.fundingLevel0 = "";
234
                  value.code =  resData['code'];
235

    
236
                  if(resData['fundingtree'] && resData['fundingtree']['funder']){
237
                    value.funderId = (resData['fundingtree']['funder']['id'] )?resData['fundingtree']['funder']['id']:"";
238
                    value.funderName = (resData['fundingtree']['funder']['shortname'] )?resData['fundingtree']['funder']['shortname']:"";
239
                    value.jurisdiction = (resData['fundingtree']['funder']['jurisdiction'] )?resData['fundingtree']['funder']['jurisdiction']:"";
240
                    if(resData['fundingtree']['funding_level_2']){
241
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_2'] && resData['fundingtree']['funding_level_2']['parent'] &&
242
                       resData['fundingtree']['funding_level_2']['parent']['funding_level_1'] && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']
243
                     && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0'])?
244
                      resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0']['name']:"";
245
                    }else if(resData['fundingtree']['funding_level_1']){
246
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_1'] && resData['fundingtree']['funding_level_1']['parent'] && resData['fundingtree']['funding_level_1']['parent']['funding_level_0'])?
247
                      resData['fundingtree']['funding_level_1']['parent']['funding_level_0']['name']:"";
248
                    }else if(resData['fundingtree']['funding_level_0']){
249
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_0']  )?resData['fundingtree']['funding_level_0']['name']:"";
250
                    }else {
251
                      value.fundingLevel0="";
252
                    }
253
                  }
254

    
255
                  if(resData.hasOwnProperty("startdate")) {
256
                    value.startDate = resData.startdate.split('-')[0];
257
                  }
258
                  if(resData.hasOwnProperty("enddate")) {
259
                    value.endDate = resData.enddate.split('-')[0];
260
                  }
261

    
262
             }
263
            //  console.info("add:"+value.label+"   "+value.id);
264

    
265
              array.push(value);
266
        }
267
        if(array.length == 0){
268
          array.push({id:'-1',label:'No results found'});
269
        }
270
        //console.info("Parsing results.... Size:"+array.length);
271

    
272
        return array;
273
    }
274

    
275
    private handleError (error: HttpErrorResponse) {
276
      // in a real world app, we may send the error to some remote logging infrastructure
277
      // instead of just logging it to the console
278
      console.log(error);
279
      return throwError(error  || 'Server error');
280
    }
281
}
(3-3/4)