Project

General

Profile

1
import {Component, EventEmitter, Input, Output, ViewChild} from '@angular/core';
2
import {ActivatedRoute} from '@angular/router';
3
import {AdvancedField, Filter} from './searchUtils/searchHelperClasses.class';
4
import {SearchProjectsService} from '../services/searchProjects.service';
5
import {ErrorCodes} from '../utils/properties/errorCodes';
6
import {ErrorMessagesComponent} from '../utils/errorMessages.component';
7
import {SearchFields} from '../utils/properties/searchFields';
8
import {SearchCustomFilter, SearchUtilsClass} from './searchUtils/searchUtils.class';
9
import {EnvProperties} from '../utils/properties/env-properties';
10
import {NewSearchPageComponent} from "./searchUtils/newSearchPage.component";
11
import {RangeFilter} from "../utils/rangeFilter/rangeFilterHelperClasses.class";
12
import {properties} from "../../../environments/environment";
13

    
14
@Component({
15
    selector: 'search-projects',
16
    template: `
17
      <new-search-page
18
        pageTitle="{{(simpleView?'':'Advanced ')}} Search for {{ 'projects' | titlecase }}"
19
        entityType="project"
20
        type="projects"
21
        [results]="results"
22
        [searchUtils]="searchUtils"
23
        [sortedByChanged]="searchUtils.sortBy" [resultsPerPageChanged]="searchUtils.size"
24
        [fieldIds]="fieldIds" [fieldIdsMap]="fieldIdsMap" [selectedFields]="selectedFields"
25
        [csvParams]="csvParams" csvPath="projects"
26
        [simpleSearchLink]="simpleSearchLink" [advancedSearchLink]="advancedSearchLink"
27
        [disableForms]="disableForms"
28
        [disableRefineForms]="disableRefineForms"
29
        [loadPaging]="loadPaging"
30
        [oldTotalResults]="oldTotalResults"
31
        [openaireLink]=openaireLink
32
        [piwikSiteId]=piwikSiteId [hasPrefix]="hasPrefix"
33
        searchFormClass="projectsSearchForm"
34
        [includeOnlyResultsAndFilter]="includeOnlyResultsAndFilter"
35
        [filters]="filters"
36
        [rangeFilters]="rangeFilters" [rangeFields]="rangeFields"
37
        [simpleView]="simpleView" formPlaceholderText="Search by title, acronym, project code..."
38
        [showSwitchSearchLink]="showSwitchSearchLink"
39
        [sort]="false" [showBreadcrumb]="showBreadcrumb"
40
      >
41
      </new-search-page>
42

    
43
    `
44
 })
45

    
46
export class SearchProjectsComponent {
47
  private errorCodes: ErrorCodes;
48
  private errorMessages: ErrorMessagesComponent;
49
@Input() piwikSiteId = null;
50
@Input() customFilter:SearchCustomFilter= null;
51
  public results =[];
52
  public filters =[];
53
  public rangeFilters: RangeFilter[] = [];
54

    
55
  public searchUtils:SearchUtilsClass = new SearchUtilsClass();
56
  public searchFields:SearchFields = new SearchFields();
57

    
58
  public fieldIds:  string[] = this.searchFields.PROJECT_ADVANCED_FIELDS;
59
  public fieldIdsMap = this.searchFields.PROJECT_FIELDS;
60
  public rangeFields:string[][] = this.searchFields.PROJECT_RANGE_FIELDS;
61
  public selectedFields:AdvancedField[] =  [];
62
  properties:EnvProperties;
63

    
64
  public resourcesQuery = "(oaftype exact project)";
65
  public csvParams: string;
66
  public disableForms: boolean = false;
67
  public disableRefineForms: boolean = false;
68
  public loadPaging: boolean = true;
69
  public oldTotalResults: number = 0;
70
  public pagingLimit: number = 0;
71
  public isPiwikEnabled;
72
  public refineFields: string[] = this.searchFields.PROJECT_REFINE_FIELDS;
73
  @ViewChild(NewSearchPageComponent) searchPage: NewSearchPageComponent;
74
  @Input() simpleView: boolean = true;
75
  @Input() simpleSearchLink: string = "";
76
  advancedSearchLink: string = "";
77
  @Input() hasPrefix: boolean = true;
78
  @Input() openaireLink: string;
79
  @Input() includeOnlyResultsAndFilter: boolean = false;
80
  @Output() searchPageUpdates = new EventEmitter();
81
  @Input() showSwitchSearchLink:boolean = true;
82
  @Input() showBreadcrumb: boolean = false;
83
  subs: any[] = [];
84
  searchResultsSub: any;
85
  searchFiltersSub: any;
86

    
87
  constructor (private route: ActivatedRoute, private _searchProjectsService: SearchProjectsService ) {
88
    this.results =[];
89
    this.errorCodes = new ErrorCodes();
90
    this.errorMessages = new ErrorMessagesComponent();
91
    this.searchUtils.status = this.errorCodes.LOADING;
92
    this.searchUtils.refineStatus = this.errorCodes.LOADING;
93
  }
94

    
95
  ngOnInit() {
96

    
97
    this.properties= properties;
98
    if (!this.simpleSearchLink) {
99
      this.simpleSearchLink = this.properties.searchLinkToProjects;
100
    }
101
    this.advancedSearchLink = this.properties.searchLinkToAdvancedProjects;
102
    this.searchUtils.baseUrl = (this.simpleView)?this.simpleSearchLink:this.advancedSearchLink;
103
     this.pagingLimit = properties.pagingLimit;
104
     this.isPiwikEnabled = properties.enablePiwikTrack;
105

    
106
    this.searchUtils.status = this.errorCodes.LOADING;
107
    var firstLoad = true;
108

    
109
    this.subs.push(this.route.queryParams.subscribe(params => {
110
      this.loadPaging = true;
111
      if(params['page'] && this.searchUtils.page != params['page']) {
112
        this.loadPaging = false;
113
        this.oldTotalResults = this.searchUtils.totalResults;
114
      }
115
      var refine = true;
116
      if (params['page'] != undefined && this.filters && !firstLoad && this.searchUtils.page != +params['page']) {
117
        refine = false;
118
      }
119

    
120
      if (params['size'] != undefined && this.filters && !firstLoad && this.searchUtils.size != params['size']) {
121
        refine = false;
122
      }
123

    
124
      let page = (params['page']=== undefined)?1:+params['page'];
125
      this.searchUtils.page = ( page <= 0 ) ? 1 : page;
126

    
127
      this.searchUtils.size = (params['size']=== undefined)?10:+params['size'];
128
      if(this.searchUtils.size != 5 && this.searchUtils.size != 10 && this.searchUtils.size != 20 && this.searchUtils.size != 50) {
129
        this.searchUtils.size = 10;
130
      }
131

    
132
      this.searchPage.fieldIds = this.fieldIds;
133
      this.selectedFields = [];
134
      this.searchPage.prepareSearchPage(this.fieldIds, this.selectedFields, this.refineFields, this.rangeFields, this.fieldIdsMap,this.customFilter,params, "project");
135
      if(refine) {
136
        this._getFilters(this.searchPage.getSearchAPIQueryForAdvancedSearhFields(), this.searchUtils.page, 0, "", true, this.searchPage.getSearchAPIQueryForRangeFields(params)+this.searchPage.getSearchAPIQueryForRefineFields(params, firstLoad));
137
      } else {
138
        this.searchUtils.refineStatus = this.errorCodes.DONE;
139
      }
140
      this.getResults(this.searchPage.getSearchAPIQueryForAdvancedSearhFields(),  this.searchUtils.page, this.searchUtils.size, refine, this.searchPage.getSearchAPIQueryForRangeFields(params)+this.searchPage.getSearchAPIQueryForRefineFields(params, firstLoad));
141
      firstLoad = false;
142
    }));
143
  }
144
  ngOnDestroy() {
145
    if(this.searchResultsSub) {
146
      this.searchResultsSub.unsubscribe();
147
    }
148
    if(this.searchFiltersSub) {
149
      this.searchFiltersSub.unsubscribe();
150
    }
151
    for (let sub of this.subs) {
152
      sub.unsubscribe();
153
    }
154
  }
155

    
156
  public _getFilters(parameters: string, page: number, size: number, sortBy: string, refine: boolean, refineFieldsFilterQuery = null) {
157
    if (page <= this.pagingLimit || this.searchUtils.refineStatus == this.errorCodes.LOADING) {
158
      this.searchUtils.refineStatus = this.errorCodes.LOADING;
159
      this.disableRefineForms = true;
160
      this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils});
161
      this.searchFiltersSub = this._searchProjectsService.advancedSearchProjects(parameters,  page, size, this.properties,(refine) ? this.searchPage.getRefineFieldsQuery() : null, this.searchPage.getFields(), refineFieldsFilterQuery)
162
      //.switchMap(
163
        .subscribe(
164
          data => {
165
            let totalResults = data[0];
166
            let filters = data[2];
167
            this.filtersReturned(refine, filters, totalResults, page);
168
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
169
          },
170
          err => {
171
            this.handleError("Error getting projects: ", err);
172
            this.searchUtils.refineStatus = this.errorMessages.getErrorCode(err.status);
173

    
174
            this.disableRefineForms = false;
175
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
176
          }
177
        );
178
    }
179
  }
180

    
181

    
182
  public filtersReturned(refine: boolean, filters: Filter[], totalResults, page: number) {
183
    if (refine) {
184
      this.filters = this.searchPage.prepareFiltersToShow(filters, totalResults);
185
      this.rangeFilters = this.searchPage.prepareRangeFiltersToShow();
186
    }
187

    
188
    this.searchUtils.refineStatus = this.errorCodes.DONE;
189
    if(totalResults == 0) {
190
      this.searchUtils.refineStatus = this.errorCodes.NONE;
191
    }
192

    
193
    if (this.searchUtils.refineStatus == this.errorCodes.DONE) {
194
      // Page out of limit!!!
195
      let totalPages: any = totalResults / (this.searchUtils.size);
196
      if (!(Number.isInteger(totalPages))) {
197
        totalPages = (parseInt(totalPages, 10) + 1);
198
      }
199
      if (totalPages < page) {
200
        this.searchUtils.refineStatus = this.errorCodes.OUT_OF_BOUND;
201
      }
202
    }
203

    
204
    if(this.searchUtils.refineStatus != this.errorCodes.DONE && this.searchUtils.status != this.searchUtils.refineStatus) {
205
      if (this.searchResultsSub) {
206
        this.searchResultsSub.unsubscribe();
207
      }
208
      this.resultsReturned(refine, [], totalResults, page);
209
    }
210

    
211
    this.disableRefineForms = false;
212
  }
213

    
214
  public getResults(parameters:string, page: number, size: number, refine: boolean, refineFieldsFilterQuery = null){
215
    if(page > this.pagingLimit) {
216
      size=0;
217
    }
218
    if(page <= this.pagingLimit || this.searchUtils.status == this.errorCodes.LOADING) {
219
      // if(parameters!= null && parameters != ''  ) {
220
      //   this.csvParams ="&fq=( "+this.resourcesQuery + "and (" + parameters + "))";
221
      // }else{
222
      //   this.csvParams ="&fq="+this.resourcesQuery;
223
      // }
224
      // this.csvParams += (refineFieldsFilterQuery?refineFieldsFilterQuery:'');
225
      //
226
      // //var errorCodes:ErrorCodes = new ErrorCodes();
227

    
228
      this.csvParams = (parameters ? ("&fq=("+parameters) : "") + (parameters ? ")" : "");
229
      this.csvParams += (refineFieldsFilterQuery ? refineFieldsFilterQuery : "");
230

    
231
      this.searchUtils.status = this.errorCodes.LOADING;
232
      //this.searchPage.openLoading();
233
      this.disableForms = true;
234
      this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils});
235
      this.results = [];
236
      this.searchUtils.totalResults = 0;
237

    
238
      //console.info("Advanced Search for Publications: Execute search query "+parameters);
239
      this.searchResultsSub = this._searchProjectsService.advancedSearchProjects(parameters,  page, size, this.properties,null, this.searchPage.getFields(), refineFieldsFilterQuery).subscribe(
240
      //this._searchProjectsService.advancedSearchProjects(parameters,  page, size, this.properties,(refine) ? this.searchPage.getRefineFieldsQuery() : null, this.searchPage.getFields(), refineFieldsFilterQuery).subscribe(
241
          data => {
242
            let totalResults = data[0];
243
            let results = data[1];
244
            this.resultsReturned(refine, results, totalResults, page);
245
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils});
246
          },
247
          err => {
248
              //console.log(err);
249
              this.handleError("Error getting projects", err);
250
              this.searchUtils.status = this.errorMessages.getErrorCode(err.status);
251
              //this.searchUtils.totalResults = null;
252
              //TODO check erros (service not available, bad request)
253
              // if( ){
254
              //   this.searchUtils.status = errorCodes.ERROR;
255
              // }
256
              //var errorCodes:ErrorCodes = new ErrorCodes();
257
              //this.searchUtils.status = errorCodes.NOT_AVAILABLE;
258
              /*if(err.status == '404') {
259
                this.searchUtils.status = this.errorCodes.NOT_FOUND;
260
              } else if(err.status == '500') {
261
                this.searchUtils.status = this.errorCodes.ERROR;
262
              } else {
263
                this.searchUtils.status = this.errorCodes.NOT_AVAILABLE;
264
              }*/
265

    
266
              //this.searchPage.closeLoading();
267
              this.disableForms = false;
268
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
269
            this.searchPage.hideFilters = false;
270
          }
271
      );
272
    }
273
  }
274

    
275
  public resultsReturned(refine: boolean, results: any, totalResults, page: number) {
276
    this.searchUtils.totalResults = totalResults;
277
    this.results = results;
278
    if(!refine) {
279
      this.searchPage.buildPageURLParameters(this.filters, this.rangeFilters, false);
280
    }
281

    
282
    this.searchPage.hideFilters = false;
283

    
284
    this.searchUtils.status = this.errorCodes.DONE;
285
    if (this.searchUtils.totalResults == 0) {
286
      this.searchUtils.status = this.errorCodes.NONE;
287
    }
288

    
289
    if (this.searchUtils.status == this.errorCodes.DONE) {
290
      // Page out of limit!!!
291
      let totalPages: any = this.searchUtils.totalResults / (this.searchUtils.size);
292
      if (!(Number.isInteger(totalPages))) {
293
        totalPages = (parseInt(totalPages, 10) + 1);
294
      }
295
      if (totalPages < page) {
296
        this.searchUtils.totalResults = 0;
297
        this.searchUtils.status = this.errorCodes.OUT_OF_BOUND;
298
      }
299
    }
300

    
301
    if(this.searchUtils.status != this.errorCodes.DONE && this.searchUtils.refineStatus != this.searchUtils.status) {
302
      if(this.searchFiltersSub) {
303
        this.searchFiltersSub.unsubscribe();
304
      }
305
      this.filtersReturned(refine, [], totalResults, page);
306
    }
307

    
308
    this.disableForms = false;
309
  }
310

    
311
  private handleError(message: string, error) {
312
    console.error("Projects advanced Search Page: "+message, error);
313
  }
314
}
(5-5/8)