Project

General

Profile

1
import {Component, EventEmitter, Input, Output, ViewChild} from '@angular/core';
2
import {ActivatedRoute} from '@angular/router';
3
import {AdvancedField} 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..."  [showAdvancedSearchLink]="showAdvancedSearchLink"
38
        [sort]="false"
39
      >
40
      </new-search-page>
41

    
42
    `
43
 })
44

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

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

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

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

    
82
  subs: any[] = [];
83

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

    
92
  ngOnInit() {
93
    // this.route.data
94
    //   .subscribe((data: { envSpecific: EnvProperties }) => {
95
        this.properties= properties;
96
        if (!this.simpleSearchLink) {
97
          this.simpleSearchLink = this.properties.searchLinkToProjects;
98
        }
99
        this.advancedSearchLink = this.properties.searchLinkToAdvancedProjects;
100
        this.searchUtils.baseUrl = (this.simpleView)?this.simpleSearchLink:this.advancedSearchLink;
101
         this.pagingLimit = properties.pagingLimit;
102
         this.isPiwikEnabled = properties.enablePiwikTrack;
103

    
104
      // });
105
    //var errorCodes:ErrorCodes = new ErrorCodes();
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 (
117
        (
118
          this.searchUtils.page != ((params['page'] === undefined) ? 1 : +params['page'])
119
          && (this.searchUtils.page == 1 || params['page'])
120
        )
121
        && this.filters && !firstLoad
122
      ) {
123
        refine = false;
124
        this.searchUtils.status = this.errorCodes.DONE;
125
      }
126

    
127
      if (
128
        (
129
          this.searchUtils.sortBy != ((params['sortBy'] === undefined) ? "" : params['sortBy'])
130
          && (this.searchUtils.sortBy == "" || params['sortBy'])
131
        )
132
        && this.filters && !firstLoad
133
      ) {
134
        refine = false;
135

    
136
        this.searchUtils.status = this.errorCodes.DONE;
137
      }
138

    
139
      if (
140
        (
141
          this.searchUtils.size != ((params['size'] === undefined) ? 10 : +params['size'])
142
          && (this.searchUtils.size == 10 || params['size'])
143
        )
144
        && this.filters && !firstLoad
145
      ) {
146
        refine = false;
147
        this.searchUtils.status = this.errorCodes.DONE;
148
      }
149

    
150
      let page = (params['page']=== undefined)?1:+params['page'];
151
      this.searchUtils.page = ( page <= 0 ) ? 1 : page;
152

    
153
      this.searchUtils.size = (params['size']=== undefined)?10:+params['size'];
154
      if(this.searchUtils.size != 5 && this.searchUtils.size != 10 && this.searchUtils.size != 20 && this.searchUtils.size != 50) {
155
        this.searchUtils.size = 10;
156
      }
157

    
158
      this.searchPage.fieldIds = this.fieldIds;
159
      this.selectedFields = [];
160
      this.searchPage.prepareSearchPage(this.fieldIds, this.selectedFields, this.refineFields, this.rangeFields, this.fieldIdsMap,this.customFilter,params, "project");
161
      if(refine) {
162
        this._getFilters(this.searchPage.getSearchAPIQueryForAdvancedSearhFields(), this.searchUtils.page, 0, "", true, this.searchPage.getSearchAPIQueryForRangeFields(params)+this.searchPage.getSearchAPIQueryForRefineFields(params, firstLoad));
163
      }
164
      this.getResults(this.searchPage.getSearchAPIQueryForAdvancedSearhFields(),  this.searchUtils.page, this.searchUtils.size, refine, this.searchPage.getSearchAPIQueryForRangeFields(params)+this.searchPage.getSearchAPIQueryForRefineFields(params, firstLoad));
165
      firstLoad = false;
166
    }));
167
  }
168
  ngOnDestroy() {
169
    for (let sub of this.subs) {
170
      sub.unsubscribe();
171
    }
172
  }
173

    
174
  public _getFilters(parameters: string, page: number, size: number, sortBy: string, refine: boolean, refineFieldsFilterQuery = null) {
175
    if (page <= this.pagingLimit || this.searchUtils.refineStatus == this.errorCodes.LOADING) {
176
      this.searchUtils.refineStatus = this.errorCodes.LOADING;
177
      this.disableRefineForms = true;
178
      this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils});
179
      this.subs.push(this._searchProjectsService.advancedSearchProjects(parameters,  page, size, this.properties,(refine) ? this.searchPage.getRefineFieldsQuery() : null, this.searchPage.getFields(), refineFieldsFilterQuery)
180
      //.switchMap(
181
        .subscribe(
182
          data => {
183
            if (refine) {
184
              this.filters = this.searchPage.prepareFiltersToShow(data[2], data[0]);
185
              this.rangeFilters = this.searchPage.prepareRangeFiltersToShow();
186
            }
187

    
188
            this.searchUtils.refineStatus = this.errorCodes.DONE;
189
            // if (this.searchUtils.totalResults == 0) {
190
            //   this.searchUtils.status = this.errorCodes.NONE;
191
            // }
192
            this.disableRefineForms = false;
193
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
194
          },
195
          err => {
196
            this.handleError("Error getting projects: ", err);
197
            this.searchUtils.refineStatus = this.errorMessages.getErrorCode(err.status);
198

    
199
            this.disableRefineForms = false;
200
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
201
          }
202
        ));
203
    }
204
  }
205

    
206
  public getResults(parameters:string, page: number, size: number, refine: boolean, refineFieldsFilterQuery = null){
207
    if(page > this.pagingLimit) {
208
      size=0;
209
    }
210
    if(page <= this.pagingLimit || this.searchUtils.status == this.errorCodes.LOADING) {
211
      // if(parameters!= null && parameters != ''  ) {
212
      //   this.csvParams ="&fq=( "+this.resourcesQuery + "and (" + parameters + "))";
213
      // }else{
214
      //   this.csvParams ="&fq="+this.resourcesQuery;
215
      // }
216
      // this.csvParams += (refineFieldsFilterQuery?refineFieldsFilterQuery:'');
217
      //
218
      // //var errorCodes:ErrorCodes = new ErrorCodes();
219

    
220
      this.csvParams = (parameters ? ("&fq=("+parameters) : "") + (parameters ? ")" : "");
221
      this.csvParams += (refineFieldsFilterQuery ? refineFieldsFilterQuery : "");
222

    
223
      this.searchUtils.status = this.errorCodes.LOADING;
224
      //this.searchPage.openLoading();
225
      this.disableForms = true;
226
      this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils});
227
      this.results = [];
228
      this.searchUtils.totalResults = 0;
229

    
230
      //console.info("Advanced Search for Publications: Execute search query "+parameters);
231
      this.subs.push(this._searchProjectsService.advancedSearchProjects(parameters,  page, size, this.properties,null, this.searchPage.getFields(), refineFieldsFilterQuery).subscribe(
232
      //this._searchProjectsService.advancedSearchProjects(parameters,  page, size, this.properties,(refine) ? this.searchPage.getRefineFieldsQuery() : null, this.searchPage.getFields(), refineFieldsFilterQuery).subscribe(
233
          data => {
234
              this.searchUtils.totalResults = data[0];
235
              this.results = data[1];
236
              // this.searchPage.updateBaseUrlWithParameters();
237
              // if (refine) {
238
              //   this.filters = this.searchPage.prepareFiltersToShow(data[2], this.searchUtils.totalResults);
239
              //   this.rangeFilters = this.searchPage.prepareRangeFiltersToShow();
240
              // }else{
241
              if(!refine) {
242
                this.searchPage.buildPageURLParameters(this.filters, this.rangeFilters, false);
243
              }
244

    
245
            //var errorCodes:ErrorCodes = new ErrorCodes();
246
              this.searchUtils.status = this.errorCodes.DONE;
247
              if(this.searchUtils.totalResults == 0 ){
248
                this.searchUtils.status = this.errorCodes.NONE;
249
              }
250
              //this.searchPage.closeLoading();
251
              this.disableForms = false;
252
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
253

    
254
              if(this.searchUtils.status == this.errorCodes.DONE) {
255
                // Page out of limit!!!
256
                let totalPages:any = this.searchUtils.totalResults/(this.searchUtils.size);
257
                if(!(Number.isInteger(totalPages))) {
258
                    totalPages = (parseInt(totalPages, 10) + 1);
259
                }
260
                if(totalPages < page) {
261
                  this.searchUtils.totalResults = 0;
262
                  this.searchUtils.status = this.errorCodes.OUT_OF_BOUND;
263
                }
264
              }
265
          },
266
          err => {
267
              //console.log(err);
268
              this.handleError("Error getting projects", err);
269
              this.searchUtils.status = this.errorMessages.getErrorCode(err.status);
270
              //this.searchUtils.totalResults = null;
271
              //TODO check erros (service not available, bad request)
272
              // if( ){
273
              //   this.searchUtils.status = errorCodes.ERROR;
274
              // }
275
              //var errorCodes:ErrorCodes = new ErrorCodes();
276
              //this.searchUtils.status = errorCodes.NOT_AVAILABLE;
277
              /*if(err.status == '404') {
278
                this.searchUtils.status = this.errorCodes.NOT_FOUND;
279
              } else if(err.status == '500') {
280
                this.searchUtils.status = this.errorCodes.ERROR;
281
              } else {
282
                this.searchUtils.status = this.errorCodes.NOT_AVAILABLE;
283
              }*/
284

    
285
              //this.searchPage.closeLoading();
286
              this.disableForms = false;
287
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
288

    
289
          }
290
      ));
291
    }
292
  }
293

    
294
  private handleError(message: string, error) {
295
    console.error("Projects advanced Search Page: "+message, error);
296
  }
297
}
(5-5/8)