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
    // this.route.data
97
    //   .subscribe((data: { envSpecific: EnvProperties }) => {
98
        this.properties= properties;
99
        if (!this.simpleSearchLink) {
100
          this.simpleSearchLink = this.properties.searchLinkToProjects;
101
        }
102
        this.advancedSearchLink = this.properties.searchLinkToAdvancedProjects;
103
        this.searchUtils.baseUrl = (this.simpleView)?this.simpleSearchLink:this.advancedSearchLink;
104
         this.pagingLimit = properties.pagingLimit;
105
         this.isPiwikEnabled = properties.enablePiwikTrack;
106

    
107
      // });
108
    //var errorCodes:ErrorCodes = new ErrorCodes();
109
    this.searchUtils.status = this.errorCodes.LOADING;
110
    var firstLoad = true;
111

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

    
123
      if (params['size'] != undefined && this.filters && !firstLoad && this.searchUtils.size != params['size']) {
124
        refine = false;
125
      }
126

    
127
      let page = (params['page']=== undefined)?1:+params['page'];
128
      this.searchUtils.page = ( page <= 0 ) ? 1 : page;
129

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

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

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

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

    
184

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

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

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

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

    
214
    this.disableRefineForms = false;
215
  }
216

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

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

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

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

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

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

    
285
    this.searchPage.hideFilters = false;
286

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

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

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

    
311
    this.disableForms = false;
312
  }
313

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