Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3
import {Observable}     from 'rxjs/Observable';
4
import 'rxjs/add/observable/of';
5
import 'rxjs/add/operator/do';
6
import 'rxjs/add/operator/share';
7
import {SearchResult}     from '../utils/entities/searchResult';
8
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
9
import{EnvProperties} from '../utils/properties/env-properties';
10
import {StringUtils} from '../utils/string-utils.class';
11
@Injectable()
12
export class SearchProjectsService {
13
    private sizeOfDescription: number = 270;
14

    
15
    constructor(private http: Http ) {}
16

    
17
    searchProjects (params: string, refineParams:string, page: number, size: number, refineFields:string[] , properties:EnvProperties ):any {
18

    
19
        console.info("In searchProjects");
20

    
21
        let link = properties.searchAPIURLLAst+"projects";
22

    
23
        let url = link+"?";
24
        if(params!= null && params != ''  ) {
25
            url += params;
26
        }
27
        if(refineParams!= null && refineParams != ''  ) {
28
            url += refineParams;
29
        }
30
        url += "&page="+(page-1)+"&size="+size + "&format=json";
31

    
32

    
33
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
34
                    .map(res => <any> res.json())
35
                    //.do(res => console.info(res))
36
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "project")]);
37
    }
38
    getProjectsforDataProvider (datasourceId: string, page: number, size: number, properties:EnvProperties  ):any {
39
      let url = properties.searchResourcesAPIURL;
40
      var basicQuery = "(oaftype exact project) "
41
      url += "?query=";
42
      if(datasourceId!= null && datasourceId != ''  ) {
43
        url +=" ( "+basicQuery+ " ) " +" and (collectedfromdatasourceid exact \"" + datasourceId + "\")";
44
      }else{
45
        url +=" ( "+basicQuery+ " ) ";
46
      }
47

    
48
      url += "&page="+(page-1)+"&size="+size;
49
      url += "&format=json";
50

    
51
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
52
      .map(res => <any> res.json())
53
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
54
    }
55
    advancedSearchProjects (params: string, page: number, size: number, properties:EnvProperties  ):any {
56
      let url = properties.searchResourcesAPIURL;
57
      var basicQuery = "(oaftype exact project) "
58
      url += "?query=";
59
      if(params!= null && params != ''  ) {
60
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
61
      }else{
62
        url +=" ( "+basicQuery+ " ) ";
63
      }
64

    
65
      url += "&page="+(page-1)+"&size="+size;
66
      url += "&format=json";
67
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
68
      .map(res => <any> res.json())
69
      //.do(res => console.info(res))
70
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
71
    }
72
    getProjectsForOrganizations (organizationId: string, filterquery: string, page: number, size: number, refineFields:string[] , properties:EnvProperties  ):any {
73
      let url = properties.searchResourcesAPIURL;
74
      var basicQuery = "(oaftype exact project) "
75
      url += "?query=";
76
      if(filterquery!= null && filterquery != ''  ) {
77
        url +="( ( "+basicQuery+ " )  and (relorganizationid exact \"" + organizationId + "\")"+"  " + filterquery + ")";
78
      }else{
79
        url +=" (( "+basicQuery+ " ) " +" and (relorganizationid exact \"" + organizationId + "\"))";
80
      }
81
      if(refineFields!= null && refineFields.length > 0 ) {
82
        url +="&refine=true";
83
        for(let i=0; i< refineFields.length ; i++ ){
84
          url +="&fields="+refineFields[i];
85
        }
86
      }
87
      url += "&page="+(page-1)+"&size="+size;
88
      url += "&format=json";
89

    
90
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
91
                  .map(res => <any> res.json())
92
                  //.do(res => console.info(res))
93
                  .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "project")]);
94
    }
95
    getFunders(properties:EnvProperties ):any {
96
       let url = properties.searchAPIURLLAst+"projects?refine=true&fields=funder&size=0"+ "&format=json";;
97

    
98
       return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
99
                   .map(res => <any> res.json())
100
                   .map(res => [res['meta'].total, res['refineResults']['funder']]);
101

    
102

    
103
      }
104

    
105
      searchForProjectsObs(keyword:string, funderId:string, properties:EnvProperties ):any {
106
         let url = 'search?action=search&sTransformer=projects_openaire&query='+
107
         '%28oaftype+exact+project%29+and+%28%28projecttitle+%3D+%22'+keyword+'%22%29+or+%28projectacronym+%3D+%22'+keyword+'%22%29+or+%28projectcode+%3D+%22'+keyword+'%22%29%29+and+%28funder+exact+'+funderId+'%29&size=10&locale=en_GB&format=json';
108

    
109
         return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
110
                    .then(request =>{
111
                      return (request.json().response.results)?request.json().response.results.result:request.json().response.result;
112

    
113
                }) ;
114
        }
115
    parseResults(data: any): SearchResult[] {
116
        let results: SearchResult[] = [];
117

    
118
        let length = Array.isArray(data) ? data.length : 1;
119

    
120
        for(let i=0; i<length; i++) {
121
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:project'] : data['result']['metadata']['oaf:entity']['oaf:project'];
122

    
123
            var result: SearchResult = new SearchResult();
124
            result.openAccessMandatePublications = (resData['oamandatepublications'])?true:false;
125
            result.openAccessMandateDatasets = (resData['ecarticle29_3'])?true:false;
126
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
127
            // if(resData['acronym'] != undefined && resData['acronym'] != "") {
128
            //     result['title'].name = resData['acronym'] + " - ";
129
            // }
130
            if(Array.isArray(resData['title'])) {
131
                result['title'].name += resData['title'][0];
132
            } else {
133
                result['title'].name += resData['title'];
134
            }
135

    
136
            // if(result['title'].name != '') {
137
            //     result['title'].name += " ("+resData['code']+")"
138
            // }
139

    
140
            if(resData['ecsc39'] == true) {
141
                result['title'].sc39 = "sc39";
142
            }
143

    
144
            result.acronym = resData['acronym'];
145
            result.code = resData['code'];
146

    
147
            result.id = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
148

    
149
            if(resData['rels'].hasOwnProperty("rel")) {
150
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
151

    
152
                for(let j=0; j<relLength; j++) {
153
                    let relation = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'][j] : resData['rels']['rel'];
154

    
155
                    if(relation.hasOwnProperty("to")) {
156
                         if(relation['to'].class == "hasParticipant") {
157
                            if(result['organizations'] == undefined) {
158
                                result['organizations'] = new Array<
159
                                    { "name": string, "id": string}>();
160
                            }
161

    
162
                            let countOrganizations = result['organizations'].length;
163

    
164
                            result['organizations'][countOrganizations] = { "name": "", "id": "" }
165

    
166
                            result['organizations'][countOrganizations]['id'] =
167
                                /*OpenaireProperties.getsearchLinkToOrganization() + */relation['to'].content;
168
                            if(relation.legalshortname) {
169
                              result['organizations'][countOrganizations]['name'] = relation.legalshortname;
170
                            } else {
171
                              result['organizations'][countOrganizations]['name'] = relation.legalname;
172
                            }
173
                        }
174
                    }
175
                }
176
            }
177
            if(resData.hasOwnProperty("fundingtree")) {
178
              /*let funderSet: Set<string>;
179
              if(result['funders'] == undefined) {
180
                  result['funders'] = new Array<
181
                      {"funderShortname": string, "funderName": string}>();
182
                  funderSet = new Set<string>();
183
              }
184

    
185
                let fundingLength = Array.isArray(resData['fundingtree']) ? resData['fundingtree'].length : 1;
186

    
187
                for(let z=0; z<fundingLength; z++) {
188
                    let fundingData = Array.isArray(resData['fundingtree']) ? resData['fundingtree'][z] : resData['fundingtree'];
189
                    if(fundingData.hasOwnProperty("funder")) {
190
                        if(!funderSet.has(fundingData['funder'].shortname)) {
191
                          let countFunders = result['funders'].length;
192

    
193
                          result['funders'][countFunders] =   {"funderShortname": "", "funderName": ""};
194
                          result['funders'][countFunders]['funderShortname'] = fundingData['funder'].shortname;
195
                          result['funders'][countFunders]['funderName'] = fundingData['funder'].name;
196
                          funderSet.add(fundingData['funder'].shortname);
197
                        }
198
                    }
199
                }*/
200

    
201
                let fundingLength = Array.isArray(resData['fundingtree']) ? resData['fundingtree'].length : 1;
202

    
203
                for(let z=0; z<fundingLength; z++) {
204
                  let fundingData = Array.isArray(resData['fundingtree']) ? resData['fundingtree'][z] : resData['fundingtree'];
205
                  if(fundingData.hasOwnProperty("funder")) {
206
                    result['funderShortname'] = fundingData['funder'].shortname;
207
                    break;
208
                  }
209
                }
210
            }
211
            if(resData.hasOwnProperty("startdate")) {
212
              result.startYear = resData.startdate.split('-')[0];
213
            }
214
            if(resData.hasOwnProperty("enddate")) {
215
              result.endYear = resData.enddate.split('-')[0];
216
            }
217

    
218
            results.push(result);
219
        }
220

    
221
        return results;
222
    }
223

    
224
    numOfProjects(url: string, properties:EnvProperties ):any {
225

    
226
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
227
                  .map(res => <any> res.json())
228
                  .map(res => res.total);
229
    }
230

    
231
    numOfEntityProjects(id: string, entity: string, properties:EnvProperties ):any {
232
        //let url = properties.searchAPIURLLAst+params+(params.indexOf("?") == -1 ?"?":"&")+"format=json";
233
        var parameters: string = "";
234
        if(entity == "organization") {
235
          parameters = "organizations/"+id+"/projects/count";
236
        }
237

    
238
        let url = properties.searchAPIURLLAst+parameters+ "?format=json";
239

    
240
        return this.numOfProjects(url, properties);
241
    }
242

    
243
    numOfSearchProjects(params: string, properties:EnvProperties ):any {
244
        let url = properties.searchAPIURLLAst+"projects/count?format=json";
245
        if(params != "") {
246
          url += "&q=" + StringUtils.URIEncode(params);
247
        }
248
        return this.numOfProjects(url, properties);
249
    }
250
}
(18-18/21)