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 {SearchOrganizationsService} from '../services/searchOrganizations.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 {properties} from "../../../environments/environment";
12

    
13

    
14
@Component({
15
    selector: 'search-organizations',
16
    template: `
17
      <new-search-page
18
        pageTitle="{{(simpleView?'':'Advanced ')}} Search for {{ 'organizations' | titlecase }}"
19
        entityType="organization"
20
        type="organizations"
21
        [results]="results"
22
        [searchUtils]="searchUtils"
23
        [sortedByChanged]="searchUtils.sortBy" [resultsPerPageChanged]="searchUtils.size"
24
        [fieldIds]="fieldIds" [fieldIdsMap]="fieldIdsMap" [selectedFields]="selectedFields"
25
        [csvParams]="csvParams" csvPath="organizations"
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="organizationsSearchForm"
34
        [includeOnlyResultsAndFilter]="includeOnlyResultsAndFilter"
35
        [sort]="false"
36
        [filters]="filters"
37
        [simpleView]="simpleView" formPlaceholderText="Search by organization name..."
38
        [showSwitchSearchLink]="showSwitchSearchLink"
39
        [showBreadcrumb]="showBreadcrumb"
40
      >
41
      </new-search-page>
42
    `
43
 })
44

    
45
export class SearchOrganizationsComponent {
46
  private errorCodes: ErrorCodes;
47
  private errorMessages: ErrorMessagesComponent;
48
  properties:EnvProperties;
49
  @Input() piwikSiteId = null;
50
  public results =[];
51
  public filters =[];
52
  public searchUtils:SearchUtilsClass = new SearchUtilsClass();
53
  public searchFields:SearchFields = new SearchFields();
54

    
55
  public fieldIds:  string[] = this.searchFields.ORGANIZATION_ADVANCED_FIELDS;
56
  public fieldIdsMap  = this.searchFields.ORGANIZATION_FIELDS;
57
  public selectedFields:AdvancedField[] =  [];
58
  public csvParams: string;
59
  public disableForms: boolean = false;
60
  public disableRefineForms: boolean = false;
61
  public loadPaging: boolean = true;
62
  public oldTotalResults: number = 0;
63
  public pagingLimit: number = 0;
64
  public isPiwikEnabled;
65

    
66
  @Input() customFilter:SearchCustomFilter= null;
67
  public refineFields: string[] = this.searchFields.ORGANIZATION_REFINE_FIELDS;
68
  @ViewChild(NewSearchPageComponent, { static: true }) searchPage: NewSearchPageComponent;
69
  @Input() simpleView: boolean = true;
70
  @Input() simpleSearchLink: string = "";
71
  advancedSearchLink: string = "";
72
  @Input() hasPrefix: boolean = true;
73
  @Input() openaireLink: string;
74
  @Input() includeOnlyResultsAndFilter: boolean = false;
75
  @Output() searchPageUpdates = new EventEmitter();
76
  @Input() showSwitchSearchLink:boolean = true;
77
  @Input() showBreadcrumb: boolean = false;
78
  public resourcesQuery = "(oaftype exact organization)";
79

    
80
  subs: any[] = [];
81
  searchResultsSub: any;
82
  searchFiltersSub: any;
83

    
84
  constructor (private route: ActivatedRoute, private _searchOrganizationsService: SearchOrganizationsService ) {
85
    this.results =[];
86
    this.errorCodes = new ErrorCodes();
87
    this.errorMessages = new ErrorMessagesComponent();
88
    this.searchUtils.status = this.errorCodes.LOADING;
89

    
90

    
91

    
92
  }
93
  ngOnInit() {
94

    
95
    this.properties= properties;
96
    if (!this.simpleSearchLink) {
97
      this.simpleSearchLink = this.properties.searchLinkToOrganizations;
98
    }
99
    this.advancedSearchLink = this.properties.searchLinkToAdvancedOrganizations;
100
    this.searchUtils.baseUrl = (this.simpleView)?this.simpleSearchLink:this.advancedSearchLink;
101
    this.pagingLimit = properties.pagingLimit;
102
    this.isPiwikEnabled = properties.enablePiwikTrack;
103

    
104
    this.searchUtils.status = this.errorCodes.LOADING;
105
    var firstLoad = true;
106

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

    
119
        if (params['size'] != undefined && this.filters && !firstLoad && this.searchUtils.size != params['size']) {
120
          refine = false;
121
        }
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.selectedFields = this.selectedFields;
135
      // this.searchPage.fieldIdsMap = this.fieldIdsMap;
136
      // this.searchPage.customFilter = this.customFilter;
137
      // this.searchPage.getSelectedFiltersFromUrl(params);
138
      this.searchPage.prepareSearchPage(this.fieldIds, this.selectedFields, this.refineFields, [], this.fieldIdsMap,this.customFilter,params, "organization");
139
      if(refine) {
140
        this._getFilters(this.searchPage.getSearchAPIQueryForAdvancedSearhFields(),  this.searchUtils.page, 0, true, this.searchPage.getSearchAPIQueryForRefineFields(params, firstLoad));
141
      } else {
142
        this.searchUtils.refineStatus = this.errorCodes.DONE;
143
      }
144
      this.getResults(this.searchPage.getSearchAPIQueryForAdvancedSearhFields(),  this.searchUtils.page, this.searchUtils.size, refine, this.searchPage.getSearchAPIQueryForRefineFields(params, firstLoad));
145
      firstLoad = false;
146
    }));
147
  }
148
  ngOnDestroy() {
149
    if(this.searchResultsSub) {
150
      this.searchResultsSub.unsubscribe();
151
    }
152
    if(this.searchFiltersSub) {
153
      this.searchFiltersSub.unsubscribe();
154
    }
155
    for (let sub of this.subs) {
156
      sub.unsubscribe();
157
    }
158
  }
159

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

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

    
179
            this.disableRefineForms = false;
180
            this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
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
    }
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
    this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
216

    
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

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

    
233
      //var errorCodes:ErrorCodes = new ErrorCodes();
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

    
239
      this.results = [];
240
      this.searchUtils.totalResults = 0;
241

    
242
      //console.info("Advanced Search for Organizations: Execute search query "+parameters);
243
       //this._searchOrganizationsService.advancedSearchOrganizations(parameters, page, size, this.properties,(refine) ? this.searchPage.getRefineFieldsQuery() : null, this.searchPage.getFields(), refineFieldsFilterQuery).subscribe(
244
      this.searchResultsSub = this._searchOrganizationsService.advancedSearchOrganizations(parameters, page, size, this.properties, null, this.searchPage.getFields(), refineFieldsFilterQuery).subscribe(
245
        data => {
246
          let totalResults = data[0];
247
          let results = data[1];
248
          this.resultsReturned(refine, results, totalResults, page);
249
        },
250
        err => {
251
            //console.log(err);
252
            this.handleError("Error getting organizations", err);
253
            this.searchUtils.status = this.errorMessages.getErrorCode(err.status);
254
            //this.searchUtils.totalResults = 0;
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, [], 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
    this.searchPageUpdates.emit({disableForms: this.disableForms, disableRefineForms: this.disableRefineForms, searchUtils: this.searchUtils})
313

    
314
  }
315

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