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, { static: true }) 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(this.searchPage.searchUtils.refineStatus == this.errorCodes.DONE) {
117
        if (params['page'] != undefined && this.filters && !firstLoad && this.searchUtils.page != +params['page']) {
118
          refine = false;
119
        }
120

    
121
        if (params['size'] != undefined && this.filters && !firstLoad && this.searchUtils.size != params['size']) {
122
          refine = false;
123
        }
124
      }
125
      let page = (params['page']=== undefined)?1:+params['page'];
126
      this.searchUtils.page = ( page <= 0 ) ? 1 : page;
127

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

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

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

    
170
          },
171
          err => {
172
            this.filters = this.searchPage.prepareFiltersToShow([], 0);
173
            this.rangeFilters = this.searchPage.prepareRangeFiltersToShow();
174

    
175
            this.handleError("Error getting refine filters for projects: ", err);
176
            this.searchUtils.refineStatus = this.errorMessages.getErrorCode(err.status);
177

    
178
            this.disableRefineForms = false;
179
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
180
          }
181
        );
182
    }
183
  }
184

    
185

    
186
  public filtersReturned(refine: boolean, filters: Filter[], totalResults, page: number) {
187
    if (refine) {
188
      this.filters = this.searchPage.prepareFiltersToShow(filters, totalResults);
189
      this.rangeFilters = this.searchPage.prepareRangeFiltersToShow();
190
    }
191

    
192
    this.searchUtils.refineStatus = this.errorCodes.DONE;
193
    if(totalResults == 0) {
194
      this.searchUtils.refineStatus = this.errorCodes.NONE;
195
    }
196

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

    
208
    if(this.searchUtils.refineStatus != this.errorCodes.DONE && this.searchUtils.status != this.searchUtils.refineStatus) {
209
      if (this.searchResultsSub) {
210
        this.searchResultsSub.unsubscribe();
211
      }
212
      this.resultsReturned(refine, [], totalResults, page);
213
    }
214

    
215
    this.disableRefineForms = false;
216
    this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
217
  }
218

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

    
233
      this.csvParams = (parameters ? ("&fq=("+parameters) : "") + (parameters ? ")" : "");
234
      this.csvParams += (refineFieldsFilterQuery ? refineFieldsFilterQuery : "");
235

    
236
      this.searchUtils.status = this.errorCodes.LOADING;
237
      //this.searchPage.openLoading();
238
      this.disableForms = true;
239
      this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils});
240
      this.results = [];
241
      this.searchUtils.totalResults = 0;
242

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

    
270
              //this.searchPage.closeLoading();
271
              this.disableForms = false;
272
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
273
            this.searchPage.hideFilters = false;
274
          }
275
      );
276
    }
277
  }
278

    
279
  public resultsReturned(refine: boolean, results: any, totalResults, page: number) {
280
    this.searchUtils.totalResults = totalResults;
281
    this.results = results;
282
    if(!refine) {
283
      this.searchPage.buildPageURLParameters(this.filters, this.rangeFilters, false);
284
    }
285

    
286
    this.searchPage.hideFilters = false;
287

    
288
    this.searchUtils.status = this.errorCodes.DONE;
289
    if (this.searchUtils.totalResults == 0) {
290
      this.searchUtils.status = this.errorCodes.NONE;
291
    }
292

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

    
305
    if(this.searchUtils.status != this.errorCodes.DONE && this.searchUtils.refineStatus != this.searchUtils.status) {
306
      if(this.searchFiltersSub) {
307
        this.searchFiltersSub.unsubscribe();
308
      }
309
      this.filtersReturned(refine, [], totalResults, page);
310
    }
311

    
312
    this.disableForms = false;
313
    this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
314
  }
315

    
316
  private handleError(message: string, error) {
317
    console.error("Projects advanced Search Page: "+message, error);
318
  }
319
}
(5-5/8)